Beispiel #1
0
        //以下为各种method---------------------------------分割线---------------------------------

        //外部事件方法建立
        //创建图纸,添加视图
        public ViewSheet CreatViewSheetPort(Document doc, FamilySymbol familySymbol, ElementId activeViewId, string activeViewName, XYZ xYZ)//参数说明:doc, 标题栏族, 需要创建视口的视图id,所选视图id的名字
        {
            using (Transaction ViewSheetViewPort_new = new Transaction(doc))
            {
                ViewSheetViewPort_new.Start("ViewSheetViewPort_new");
                ViewSheet viewSheet = ViewSheet.Create(doc, familySymbol.Id);
                if (viewSheet == null)
                {
                    TaskDialog.Show("Revit2020", "未能成功创建新图纸.");
                    return(null);
                }
                //设置视口位置
                //UV location = new UV((viewSheet.Outline.Max.U - viewSheet.Outline.Min.U) / 2, (viewSheet.Outline.Max.V - viewSheet.Outline.Min.V) / 2);

                if (Viewport.CanAddViewToSheet(doc, viewSheet.Id, activeViewId))//判断视图是否能够加入图纸
                {
                    Viewport.Create(doc, viewSheet.Id, activeViewId, xYZ);
                }
                else
                {
                    TaskDialog.Show("Revit2020", activeViewName + "已经存在与图纸中");
                }
                ViewSheetViewPort_new.Commit();
                return(viewSheet);
            }
        }
Beispiel #2
0
        private void SetViewForSheet(View view, ViewSheet sheet, int scale)
        {
            if (scale > 0)
            {
                try
                {
                    view.Scale = scale;
                }
                catch (Exception ex)
                {
                }
            }

            try
            {
                if (Viewport.CanAddViewToSheet(view.Document, sheet.Id, view.Id))
                {
                    BoundingBoxUV sheetBox    = sheet.Outline;
                    XYZ           sheetOrigin = sheet.Origin;

                    Viewport viewport = Viewport.Create(view.Document, sheet.Id, view.Id, XYZ.Zero);

                    BoundingBoxXYZ viewportBoundingBox = viewport.get_BoundingBox(sheet);
                    XYZ            viewportOrigin      = viewportBoundingBox.Min;

                    ElementTransformUtils.MoveElement(view.Document, viewport.Id, new XYZ(sheetOrigin.X - viewportOrigin.X, sheetOrigin.Y - viewportOrigin.Y, 0));
                }
                else
                {
                }
            }
            catch (ArgumentException ex)
            {
            }
        }
        private void SetViewForSheet(View view, ViewSheet sheet, int scale)
        {
            if (scale > 0)
            {
                try
                {
                    view.Scale = scale;
                }
                catch (Exception ex)
                {
                }
            }

            try
            {
                if (Viewport.CanAddViewToSheet(view.Document, sheet.Id, view.Id))
                {
                    BoundingBoxUV sheetBox  = sheet.Outline;
                    double        yPosition = (sheetBox.Max.V - sheetBox.Min.V) / 2 + sheetBox.Min.V;
                    double        xPosition = (sheetBox.Max.U - sheetBox.Min.U) / 2 + sheetBox.Min.U;

                    XYZ      orig     = new XYZ(xPosition, yPosition, 0);
                    Viewport viewport = Viewport.Create(view.Document, sheet.Id, view.Id, orig);
                }
                else
                {
                }
            }
            catch (ArgumentException ex)
            {
            }
        }
 public static void CollectData(this Document doc)
 {
     using (TransactionGroup tg = new TransactionGroup(doc, "Output Xml and Update Data"))
     {
         tg.Start();
         using (Transaction t = new Transaction(doc, "Add Parameters:"))
         {
             t.Start();
             foreach (Param p in Parameters)
             {
                 doc.AddParam(p);
             }
             t.Commit();
         }
         using (Transaction t = new Transaction(doc, "Collect Project Data"))
         {
             t.Start();
             var fams   = new FilteredElementCollector(doc).OfClass(typeof(Family)).Count();
             var insts  = new FilteredElementCollector(doc).OfClass(typeof(FamilyInstance)).Count();
             var mats   = new FilteredElementCollector(doc).OfCategory(BuiltInCategory.OST_Materials).Count();
             var Sheets = new FilteredElementCollector(doc).OfCategory(BuiltInCategory.OST_Sheets).ToElementIds().ToList();
             var Views  = new FilteredElementCollector(doc).OfCategory(BuiltInCategory.OST_Views).ToElementIds().ToList();
             var vos    = Views.Where(x => !Viewport.CanAddViewToSheet(doc, Sheets.FirstOrDefault(), x)).Count();
             doc.SetParam(ProjectParams.Families, fams.ToString());
             doc.SetParam(ProjectParams.FamilyInstances, insts.ToString());
             doc.SetParam(ProjectParams.Materials, mats.ToString());
             doc.SetParam(ProjectParams.Sheets, Sheets.Count().ToString());
             doc.SetParam(ProjectParams.Views, Views.Count().ToString());
             doc.SetParam(ProjectParams.ViwesOnSheets, vos.ToString());
             t.Commit();
         }
         tg.Commit();
     }
 }
Beispiel #5
0
        /// <summary>
        /// This method adds the collection of views to the existing ViewSheet and packs them
        /// </summary>
        /// <param name="views"></param>
        private void InternalAddViewsToSheetView(IEnumerable <Autodesk.Revit.DB.View> views)
        {
            var sheet = InternalViewSheet;

            TransactionManager.Instance.EnsureInTransaction(Document);

            // (sic) from Dynamo Legacy
            var width  = sheet.Outline.Max.U - sheet.Outline.Min.U;
            var height = sheet.Outline.Max.V - sheet.Outline.Min.V;
            var packer = new CygonRectanglePacker(width, height);
            int count  = 0;

            foreach (var view in views)
            {
                var viewWidth  = view.Outline.Max.U - view.Outline.Min.U;
                var viewHeight = view.Outline.Max.V - view.Outline.Min.V;

                Autodesk.Revit.DB.UV placement = null;
                if (packer.TryPack(viewWidth, viewHeight, out placement))
                {
                    var dbViews = sheet.GetAllPlacedViews().Select(x => Document.GetElement(x)).
                                  OfType <Autodesk.Revit.DB.View>();
                    if (dbViews.Contains(view))
                    {
                        //move the view
                        //find the corresponding viewport
                        var enumerable =
                            DocumentManager.Instance.ElementsOfType <Autodesk.Revit.DB.Viewport>()
                            .Where(x => x.SheetId == sheet.Id && x.ViewId == view.Id).ToArray();

                        if (!enumerable.Any())
                        {
                            continue;
                        }

                        var viewport = enumerable.First();
                        viewport.SetBoxCenter(new XYZ(placement.U + viewWidth / 2, placement.V + viewHeight / 2, 0));
                    }
                    else
                    {
                        //place the view on the sheet
                        if (Viewport.CanAddViewToSheet(Document, sheet.Id, view.Id))
                        {
                            var viewport = Viewport.Create(Document, sheet.Id, view.Id,
                                                           new XYZ(placement.U + viewWidth / 2, placement.V + viewHeight / 2, 0));
                        }
                    }
                }
                else
                {
                    throw new Exception(String.Format("View {0} could not be packed on the Sheet.  The sheet is {1} x {2} and the view to be added is {3} x {4}",
                                                      count, width, height, viewWidth, viewHeight));
                }

                count++;
            }

            TransactionManager.Instance.TransactionTaskDone();
        }
        public void DeleteUnusedViews()
        {
            // define current document
            Document curDoc = this.Application.ActiveUIDocument.Document;

            // get all views
            FilteredElementCollector viewColl = new FilteredElementCollector(curDoc);

            viewColl.OfCategory(BuiltInCategory.OST_Views);

            // get all sheets
            FilteredElementCollector sheetColl = new FilteredElementCollector(curDoc);

            sheetColl.OfCategory(BuiltInCategory.OST_Sheets);

            // create list of sheets to delete
            List <View> viewsToDelete = new List <View>();

            // loop through view and check each one
            foreach (View curView in viewColl)
            {
                // check if view is a template
                if (curView.IsTemplate == false)
                {
                    // check if view can be added to sheet
                    if (Viewport.CanAddViewToSheet(curDoc, sheetColl.FirstElementId(), curView.Id) == true)
                    {
                        // check if view has prefix
                        if (curView.Name.Contains("working") == false)
                        {
                            // add view to delete list
                            viewsToDelete.Add(curView);
                        }
                    }
                }
            }

            // create transaction
            Transaction t = new Transaction(curDoc, "Delete unused views");

            t.Start();

            // delete views in list
            foreach (View viewToDelete in viewsToDelete)
            {
                // delete view
                curDoc.Delete(viewToDelete.Id);
            }

            // commit changes
            t.Commit();
            t.Dispose();

            // alert user
            TaskDialog.Show("Complete", "Deleted " + viewsToDelete.Count().ToString() + " unused views.");
        }
Beispiel #7
0
        private void DeleteUnusedViews()
        {
            // define current document
            Document curDoc = this.ActiveUIDocument.Document;

            // get all views
            FilteredElementCollector viewCollector = new FilteredElementCollector(curDoc);

            viewCollector.OfCategory(BuiltInCategory.OST_Views);

            // get all sheets
            FilteredElementCollector sheetCollector = new FilteredElementCollector(curDoc);

            sheetCollector.OfCategory(BuiltInCategory.OST_Sheets);

            // create a list of views to delete
            List <View> viewsToDelete = new List <View>();

            // loop through views and check if it's on a sheet
            foreach (View curView in viewCollector)
            {
                // check if current view is a template
                if (curView.IsTemplate == false)
                {
                    // check if view can be added to sheet
                    if (Viewport.CanAddViewToSheet(curDoc, sheetCollector.FirstElementId(), curView.Id) == true)
                    {
                        // add view to delete list
                        viewsToDelete.Add(curView);
                    }
                }
            }

            // create transaction
            Transaction curTrans = new Transaction(curDoc);

            curTrans.Start("Delete Views");

            // delete views in list
            foreach (View viewToDelete in viewsToDelete)
            {
                curDoc.Delete(viewToDelete.Id);
            }

            // commit changes
            curTrans.Commit();
            curTrans.Dispose();

            // alert user
            TaskDialog.Show("Deleted Views", "Deleted " + viewsToDelete.Count().ToString() + " views.");
        }
Beispiel #8
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);
        }
Beispiel #9
0
        private void SetViewForSheet(View view, ViewSheet sheet, int scale)
        {
            if (scale > 0)
            {
                try
                {
                    view.Scale = scale;
                }
                catch (Exception ex)
                {
                }
            }

            try
            {
                if (Viewport.CanAddViewToSheet(view.Document, sheet.Id, view.Id))
                {
                    //TaskDialog.Show("Info", "Viewport.CanAddViewToSheet sheet.Name:" + sheet.Name + " view.Name:" + view.Name);

                    BoundingBoxUV sheetBox  = sheet.Outline;
                    double        yPosition = (sheetBox.Max.V - sheetBox.Min.V) / 2 + sheetBox.Min.V;
                    double        xPosition = (sheetBox.Max.U - sheetBox.Min.U) / 2 + sheetBox.Min.U;

                    XYZ      orig     = new XYZ(xPosition, yPosition, 0);
                    Viewport viewport = Viewport.Create(view.Document, sheet.Id, view.Id, orig);

                    doc.Regenerate();
                }
                else
                {
                    //TaskDialog.Show("Exc", "Viewport.CanAddViewToSheet == false sheet.Name:" + sheet.Name + " view.Name:" + view.Name);
                }
            }
            catch (ArgumentException ex)
            {
                TaskDialog.Show("Exc", ex.Message);
            }
        }
        public static List <ElementId> ViewsToDelete(Room r)
        {
            Document         currentDoc = r.Document;
            List <ElementId> VTDs       = new List <ElementId>();

            string vname = r.Name;

            FilteredElementCollector sheetCollector = new FilteredElementCollector(currentDoc);

            sheetCollector.OfCategory(BuiltInCategory.OST_Sheets);
            FilteredElementCollector viewfilter = new FilteredElementCollector(currentDoc).OfClass(typeof(View));

            foreach (View v in viewfilter)
            {
                if (Viewport.CanAddViewToSheet(currentDoc, sheetCollector.FirstElement().Id, v.Id) != false)
                {
                    if (v.Name.Split('-').First() == vname + ' ')
                    {
                        VTDs.Add(v.Id);
                    }
                }
            }
            return(VTDs);
        }
        public Result Execute(ExternalCommandData commandData, ref string message, ElementSet elements)
        {
            Application app   = commandData.Application.Application;
            Document    doc   = commandData.Application.ActiveUIDocument.Document;
            UIDocument  uidoc = commandData.Application.ActiveUIDocument;

            ElementId sheetId = null;

            if (doc.ActiveView is ViewSheet)
            {
                message = "Active view can not be a sheet!";
                return(Result.Failed);
            }

            List <ElementId> sheedIds = new List <ElementId>();

            foreach (UIView uiview in uidoc.GetOpenUIViews())
            {
                if (doc.GetElement(uiview.ViewId) is ViewSheet)
                {
                    sheedIds.Add(uiview.ViewId);
                }
            }

            if (sheedIds.Count == 0)
            {
                message = "No sheets are open, or a viewport is activated.";
                return(Result.Failed);
            }

            int selectedSheet = 0;

            if (sheedIds.Count > 1)
            {
                List <string> sheetNames = new List <string>();
                foreach (ElementId id in sheedIds)
                {
                    Element e = doc.GetElement(id);
                    sheetNames.Add(e.Name);
                }
                WindowSelectSheet dialog = new WindowSelectSheet(sheetNames);
                dialog.ShowDialog();
                if (dialog.DialogResult.HasValue && dialog.DialogResult.Value)
                {
                    selectedSheet = dialog.comboSheet.SelectedIndex;
                }
                else
                {
                    return(Result.Cancelled);
                }
            }
            sheetId = sheedIds[selectedSheet];


            if (Viewport.CanAddViewToSheet(doc, sheetId, doc.ActiveView.Id))
            {
                using (Transaction t1 = new Transaction(doc, "Add active view to opened sheet"))
                {
                    t1.Start();
                    Viewport.Create(doc, sheetId, doc.ActiveView.Id, new XYZ(0, 0, 0));
                    t1.Commit();
                }
            }
            else
            {
                message = "Active view can not be added to sheet. Maybe it is on a sheet already?";
                return(Result.Failed);
            }

            uidoc.RequestViewChange(doc.GetElement(sheetId) as View);


            return(Result.Succeeded);
        }
Beispiel #12
0
        /// <summary>
        /// Duplicate one existing sheet
        /// </summary>
        /// <param name="shtNumber">The new sheet number</param>
        /// <param name="shtName">The new sheet name</param>
        /// <param name="tbName">The title block for the new sheet</param>
        /// <param name="vsSourceSheet">The ViewSheet to copy</param>
//		public void DuplicateOneSheet(string shtNumber, string shtName, string tbName, ViewSheet vsSourceSheet)
        public void DuplicateOneSheet(NewSheetFormat nsf)
        {
            ViewSheet vsDestinationSheet;

            try
            {
                // try to create the sheet
                // see below about copy parameters
                vsDestinationSheet = CreateOneEmptySheet(nsf);
            }
            catch (Exception e)
            {
                throw new Exception(e.Message);
            }

            // at this point we have a source and destination ViewSheet
            // here we copy the elements on the source ViewSheet and
            // place them onto the destination ViewSheet
            // except, we don't copy the title block as this was added
            // when the ViewSheet was created

            // first, get a collection of elements that exist on the source sheet
            FilteredElementCollector colViewSheet =
                new FilteredElementCollector(_doc, nsf.FcSelViewSht.Id);

            // prepare for the elements to "copy" and "paste"
            ICollection <ElementId> copyIds = new List <ElementId>();

            // this may fail, prepare for the failure and capture the failure message
            try
            {
                // in order to copy detail lines directly onto the sheet, we need to
                // setup a SketchPlane on the "blank" sheet

                SketchPlane sketch = CreateSketchPlane(vsDestinationSheet);

                List <Viewport> vpList       = new List <Viewport>(10);
                List <Viewport> vpListNoCopy = new List <Viewport>(10);

                copyIds.Clear();

                // the ViewSheet has been setup to copy / paste or duplicate the elements
                // held by the ViewSheet - with the exceptions that ViewPorts cannot be copied
                foreach (Element sourceElem in colViewSheet)
                {
                    // ignore GuideGrids
                    if (sourceElem.Category.Id == _cats.get_Item(BuiltInCategory.OST_GuideGrid).Id)
                    {
                        continue;
                    }

                    // is the current element a titleblock? - this is the source titleblock
                    if (sourceElem.Category.Id == _cats.get_Item(BuiltInCategory.OST_TitleBlocks).Id)
                    {
                        ConfigureNewTitleBlock(sourceElem, vsDestinationSheet);
                        continue;
                    }

                    // we cannot copy some viewports or GuideGrids
                    if (sourceElem.Category.Id == _cats.get_Item(BuiltInCategory.OST_Viewports).Id)
                    {
                        Viewport vp = (Viewport)sourceElem;
                        View     vw = (View)_doc.GetElement(vp.ViewId);

                        if (Viewport.CanAddViewToSheet(_doc, vsDestinationSheet.Id, vw.Id))
                        {
                            vpList.Add(vp);                             // got a viewport to copy
                        }
                        else
                        {
                            vpListNoCopy.Add(vp);                             // got a viewport I cannot copy
                        }
                        continue;
                    }

                    // process a not viewport items
                    copyIds.Add(sourceElem.Id);
                }

                // preform the actual copy of the elements
                if (copyIds.Count > 0)
                {
                    ElementTransformUtils.CopyElements((ViewSheet)nsf.SelectedSheet.SheetView, copyIds, vsDestinationSheet,
                                                       Transform.Identity, new CopyPasteOptions());
                }

                // processed all of the items on the view sheet except for the viewports
                // we have a list of viewports we can copy and place onto the sheet
                // here we process the list of viewports that cannot be copy / pasted and replicate
                // them matching their original location
                if (vpList.Count > 0)
                {
                    foreach (Viewport vpSource in vpList)
                    {
                        View vw = _doc.GetElement(vpSource.ViewId) as View;

                        PlaceViewportOnSheet(vsDestinationSheet, vpSource, vw);
                    }
                }

                if (vpListNoCopy.Count > 0 && nsf.OperationOption == OperOpType.DupSheetAndViews)
                {
                    // get all of the view names here to make sure it is current
                    GetAllViewNames();

                    foreach (Viewport vpSource in vpListNoCopy)
                    {
                        View vwSource = _doc.GetElement(vpSource.ViewId) as View;

                        if (!vwSource.CanViewBeDuplicated(ViewDuplicateOption.WithDetailing))
                        {
                            continue;
                        }

                        View vwCopy;

                        // if PrimaryViewId is not InvalidElementId, view is dependant
                        if (vwSource.GetPrimaryViewId() == ElementId.InvalidElementId)
                        {
                            vwCopy = _doc.GetElement(vwSource.Duplicate(ViewDuplicateOption.WithDetailing)) as View;
                        }
                        else
                        {
                            vwCopy = _doc.GetElement(vwSource.Duplicate(ViewDuplicateOption.AsDependent)) as View;
                        }

                        if (vwCopy != null)
                        {
                            vwCopy.Name = FindNextViewName(vwSource.Name, nsf);
//							vwCopy.Name = FindNextViewName(vwSource.Name, nsf.newSheetNumber);

                            PlaceViewportOnSheet(vsDestinationSheet, vpSource, vwCopy);
                        }
                    }
                }
            }
            catch (Exception e)
            {
                throw new Exception(AppStrings.R_ErrDupSheetFailDesc + nl + e.Message);
            }
        }
Beispiel #13
0
        public override Value Evaluate(FSharpList <Value> args)
        {
            var name   = ((Value.String)args[0]).Item;
            var number = ((Value.String)args[1]).Item;
            var tb     = (FamilySymbol)((Value.Container)args[2]).Item;

            if (!args[3].IsList)
            {
                throw new Exception("The views input must be a list of views.");
            }

            var views = ((Value.List)args[3]).Item;

            Autodesk.Revit.DB.ViewSheet sheet = null;

            if (this.Elements.Any())
            {
                if (dynUtils.TryGetElement(this.Elements[0], out sheet))
                {
                    if (sheet.Name != null && sheet.Name != name)
                    {
                        sheet.Name = name;
                    }
                    if (number != null && sheet.SheetNumber != number)
                    {
                        sheet.SheetNumber = number;
                    }
                }
                else
                {
                    //create a new view sheet
                    sheet             = Autodesk.Revit.DB.ViewSheet.Create(dynRevitSettings.Doc.Document, tb.Id);
                    sheet.Name        = name;
                    sheet.SheetNumber = number;
                    Elements[0]       = sheet.Id;
                }
            }
            else
            {
                sheet             = Autodesk.Revit.DB.ViewSheet.Create(dynRevitSettings.Doc.Document, tb.Id);
                sheet.Name        = name;
                sheet.SheetNumber = number;
                Elements.Add(sheet.Id);
            }

            //rearrange views on sheets
            //first clear the collection of views on the sheet
            //sheet.Views.Clear();

            var width  = sheet.Outline.Max.U - sheet.Outline.Min.U;
            var height = sheet.Outline.Max.V - sheet.Outline.Min.V;
            var packer = new CygonRectanglePacker(width, height);

            foreach (var val in views)
            {
                var view = (View)((Value.Container)val).Item;

                var viewWidth  = view.Outline.Max.U - view.Outline.Min.U;
                var viewHeight = view.Outline.Max.V - view.Outline.Min.V;

                UV placement = null;
                if (packer.TryPack(viewWidth, viewHeight, out placement))
                {
                    if (sheet.Views.Contains(view))
                    {
                        //move the view
                        //find the corresponding viewport
                        var collector = new FilteredElementCollector(dynRevitSettings.Doc.Document);
                        collector.OfClass(typeof(Viewport));
                        var found =
                            collector.ToElements()
                            .Cast <Viewport>()
                            .Where(x => x.SheetId == sheet.Id && x.ViewId == view.Id);

                        var enumerable = found as Viewport[] ?? found.ToArray();
                        if (!enumerable.Any())
                        {
                            continue;
                        }

                        var viewport = enumerable.First();
                        viewport.SetBoxCenter(new XYZ(placement.U + viewWidth / 2, placement.V + viewHeight / 2, 0));
                    }
                    else
                    {
                        //place the view on the sheet
                        if (Viewport.CanAddViewToSheet(dynRevitSettings.Doc.Document, sheet.Id, view.Id))
                        {
                            var viewport = Viewport.Create(dynRevitSettings.Doc.Document, sheet.Id, view.Id,
                                                           new XYZ(placement.U + viewWidth / 2, placement.V + viewHeight / 2, 0));
                        }
                    }
                }
                else
                {
                    throw new Exception("View could not be packed on sheet.");
                }
            }

            return(Value.NewContainer(sheet));
        }
Beispiel #14
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();
            }
        }
Beispiel #15
0
        //This line has to be here in order for the command to execute in the current Revit context
        public Result Execute(ExternalCommandData commandData, ref string message, ElementSet elements)
        {
            //Get the Current Session / Project from Revit
            UIApplication uiapp = commandData.Application;

            //Get the Current Document from the Current Session
            Document doc = uiapp.ActiveUIDocument.Document;

            //Create a new instance of the SheetSelection form.
            //This implementation is a Windows Form. For WPF see WPF.SheetSelectionWPF
            WPF.SheetSelectionWPF form = new WPF.SheetSelectionWPF(doc);
            //Make sure the Sheet Selection Form returns the correct DialogResult
            if (form.ShowDialog().Value)
            {
                //Make sure the user selected at least 1 sheet
                if (form.ViewSheetIds.Count >= 1)
                {
                    //Check to see if more than one sheet was selected and alert the user if so.
                    if (form.ViewSheetIds.Count > 1)
                    {
                        TaskDialog.Show("Information", "More than one Sheet was selected.\nThe first Sheet in the selection will be used.");
                    }

                    //Use this try to make sure Revit doesn't crash when trying to place or update the 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 Active View");
                            ElementId viewSheetId = form.ViewSheetIds[0];

                            //Get the ViewSheet (Sheet) for the Element Id in the Document
                            ViewSheet viewSheet = doc.GetElement(viewSheetId) as ViewSheet;

                            //Get the Title Block on the sheet to extract Height and Width for View Placement
                            FamilyInstance TitleBlock = new FilteredElementCollector(doc, viewSheetId).OfCategory(BuiltInCategory.OST_TitleBlocks).Cast <FamilyInstance>().FirstOrDefault();

                            //Use the built in parameters for Sheet Width and Height to get their values
                            double SheetWidth  = TitleBlock.get_Parameter(BuiltInParameter.SHEET_WIDTH).AsDouble();
                            double SheetHeight = TitleBlock.get_Parameter(BuiltInParameter.SHEET_HEIGHT).AsDouble();

                            //Check to see if the active view can be placed on the selected sheet
                            if (Viewport.CanAddViewToSheet(doc, viewSheetId, doc.ActiveView.Id))
                            {
                                //Create a viewport for the active view on the sheet selected.
                                //Viewport will be centered on the sheet based on the Height and Width parameters
                                Viewport.Create(doc, viewSheetId, doc.ActiveView.Id, new XYZ(SheetWidth / 2, SheetHeight / 2, 0));
                            }
                            else
                            {
                                TaskDialog.Show("Information", "Active View cannot be placed on the selected Sheet");
                                return(Result.Cancelled);
                            }

                            //Commit the Transaction to keep the changes
                            Trans.Commit();

                            //Check to see if the user would like to change views to the sheet after the viewport was created
                            if (TaskDialog.Show("Change View", "Would you like to go to Sheet:\n" + viewSheet.SheetNumber + " - " + viewSheet.Name + "?", TaskDialogCommonButtons.Yes | TaskDialogCommonButtons.No) == TaskDialogResult.Yes)
                            {
                                uiapp.ActiveUIDocument.ActiveView = viewSheet;
                            }

                            //Return a successful result to Revit so the changes are kept
                            return(Result.Succeeded);
                        }
                    }
                    //Catch an exceptions when adding or updating the Viewports. Tell the user and return a Failed Result so Revit does not keep any changes
                    catch (Exception ex)
                    {
                        TaskDialog.Show("Viewport 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);
            }
        }
        public static PData PDataFromRevit(Document currentDoc)
        {
            PData data = new PData();

            data.Date = DateTime.Now;

            //list all views
            FilteredElementCollector viewCollector = new FilteredElementCollector(currentDoc);

            viewCollector.OfCategory(BuiltInCategory.OST_Views);

            //list all sheets
            FilteredElementCollector sheetCollector = new FilteredElementCollector(currentDoc);

            sheetCollector.OfCategory(BuiltInCategory.OST_Sheets);

            //list all TextNoteTypes
            FilteredElementCollector textCollector = new FilteredElementCollector(currentDoc);
            ICollection <ElementId>  textstyles    = textCollector.OfClass(typeof(TextNoteType)).ToElementIds().ToList();

            //list all Materials
            FilteredElementCollector matCollector = new FilteredElementCollector(currentDoc);
            ICollection <ElementId>  materials    = matCollector.OfClass(typeof(Material)).ToElementIds().ToList();

            //list all Groups
            FilteredElementCollector GroupCollector = new FilteredElementCollector(currentDoc);
            ICollection <ElementId>  groups         = GroupCollector.OfClass(typeof(GroupType)).ToElementIds().ToList();

            //list all families
            FilteredElementCollector FamCollector = new FilteredElementCollector(currentDoc);
            ICollection <ElementId>  Fams         = FamCollector.OfClass(typeof(Family)).ToElementIds().ToList();

            //list all elements
            FilteredElementCollector eleCollector = new FilteredElementCollector(currentDoc);
            ICollection <Element>    eles         = eleCollector.OfClass(typeof(FamilyInstance)).ToList();

            FilteredElementCollector noteCollector = new FilteredElementCollector(currentDoc);
            ICollection <ElementId>  textnotes     = noteCollector.OfClass(typeof(TextNote)).ToElementIds().ToList();

            //crossreference lists and find unused views
            List <View>      unusedviews   = new List <View>();
            List <ViewSheet> projectsheets = new List <ViewSheet>();
            List <GroupType> pGroups       = new List <GroupType>();
            List <View>      totalviews    = new List <View>();

            //check if views are in use
            foreach (View currentView in viewCollector)
            {
                totalviews.Add(currentView);
                //check if current view is a legend
                if (currentView.ViewType != ViewType.Legend &&
                    currentView.IsTemplate == false &&
                    Viewport.CanAddViewToSheet(currentDoc, sheetCollector.FirstElement().Id, currentView.Id) != false)
                {
                    //add view to list of views to delete
                    unusedviews.Add(currentView);
                }
            }

            //determine if groups are purgeable
            foreach (GroupType curGroup in GroupCollector)
            {
                //check if group can be deleted)
                if (curGroup.Groups.Size == 0)
                {
                    pGroups.Add(curGroup);
                }
            }

            //create list of sheets
            foreach (ViewSheet currentSheet in sheetCollector)
            {
                projectsheets.Add(currentSheet);
            }

            data.ticks           = data.Date.Ticks;
            data.TotalViews      = viewCollector.Count();
            data.UnusedViews     = unusedviews.Count();
            data.TotalSheets     = projectsheets.Count();
            data.TextStyles      = textstyles.Count();
            data.Materials       = materials.Count();
            data.Groups          = groups.Count();
            data.PurgeableGroups = pGroups.Count();
            data.Families        = Fams.Count();
            data.FamInstances    = eles.Count();
            data.TextNotes       = textnotes.Count();
            return(data);
        }
Beispiel #17
0
        public static PreviewMap DuplicateView(PreviewMap previewMap, bool createSheet)
        {
            PreviewMap preview = previewMap;

            try
            {
                CopyPasteOptions options = new CopyPasteOptions();
                options.SetDuplicateTypeNamesHandler(new HideAndAcceptDuplicateTypeNamesHandler());

                Document         toDoc   = preview.RecipientModelInfo.Doc;
                List <ElementId> viewIds = new List <ElementId>();
                using (TransactionGroup tg = new TransactionGroup(toDoc, "Duplicate across documents with detailing"))
                {
                    tg.Start();

                    if (preview.IsEnabled)
                    {
                        ViewDrafting copiedView = null;
                        if (null != preview.SourceViewProperties.LinkedView) //already exist in recipient model
                        {
                            ViewDrafting            sourceView          = previewMap.SourceViewProperties.ViewDraftingObj;
                            ICollection <ElementId> referenceCalloutIds = sourceView.GetReferenceCallouts();

                            ElementId viewId = new ElementId(preview.SourceViewProperties.LinkedView.ViewId);
                            using (Transaction trans = new Transaction(preview.RecipientModelInfo.Doc, "Delete Existing Contents"))
                            {
                                trans.Start();
                                try
                                {
                                    FailureHandlingOptions failOpt = trans.GetFailureHandlingOptions();
                                    failOpt.SetFailuresPreprocessor(new WarningMessagePreprocessor());
                                    trans.SetFailureHandlingOptions(failOpt);

                                    FilteredElementCollector collector = new FilteredElementCollector(preview.RecipientModelInfo.Doc, viewId);
                                    collector.WherePasses(new ElementCategoryFilter(ElementId.InvalidElementId, true));
                                    ICollection <ElementId> toDelete   = collector.ToElementIds();
                                    ICollection <ElementId> deletedIds = preview.RecipientModelInfo.Doc.Delete(toDelete);
                                    trans.Commit();
                                }
                                catch (Exception ex)
                                {
                                    string message = ex.Message;
                                    trans.RollBack();
                                }
                            }

                            copiedView = preview.RecipientModelInfo.Doc.GetElement(viewId) as ViewDrafting;
                            if (null != copiedView)
                            {
                                int numOfCopied = DuplicateDetailingAcrossViews(preview.SourceViewProperties.ViewDraftingObj, copiedView);
                            }
                            if (referenceCalloutIds.Count > 0)
                            {
                                bool placedCallout = DuplicateReferenceCallouts(sourceView, copiedView);
                            }

                            if (createSheet)
                            {
                                //delete existing viewport
                                ElementClassFilter       filter    = new ElementClassFilter(typeof(Viewport));
                                FilteredElementCollector collector = new FilteredElementCollector(preview.RecipientModelInfo.Doc);
                                List <Viewport>          viewports = collector.WherePasses(filter).Cast <Viewport>().ToList <Viewport>();

                                var query = from element in viewports
                                            where element.ViewId == viewId
                                            select element;
                                if (query.Count() > 0)
                                {
                                    Viewport viewport = query.First();
                                    using (Transaction trans = new Transaction(preview.RecipientModelInfo.Doc, "Delete exisitng viewport"))
                                    {
                                        trans.Start();
                                        try
                                        {
                                            FailureHandlingOptions failOpt = trans.GetFailureHandlingOptions();
                                            failOpt.SetFailuresPreprocessor(new WarningMessagePreprocessor());
                                            trans.SetFailureHandlingOptions(failOpt);

                                            preview.RecipientModelInfo.Doc.Delete(viewport.Id);
                                            trans.Commit();
                                        }
                                        catch (Exception ex)
                                        {
                                            string message = ex.Message;
                                            trans.RollBack();
                                        }
                                    }
                                }
                                if (preview.SourceViewProperties.IsOnSheet && null != preview.SourceViewProperties.SheetObj)
                                {
                                    ViewSheet copiedSheet = DuplicateSheet(preview);
                                    if (null != copiedView && null != copiedSheet)
                                    {
                                        if (Viewport.CanAddViewToSheet(preview.RecipientModelInfo.Doc, copiedSheet.Id, copiedView.Id))
                                        {
                                            Viewport recipientViewport = DuplicateViewPort(preview, copiedSheet, copiedView);
                                        }
                                    }
                                }
                            }
                        }
                        else
                        {
                            if (preview.SourceViewProperties.IsOnSheet && createSheet)
                            {
                                ViewSheet copiedSheet = DuplicateSheet(preview);
                                copiedView = DuplicateDraftingViews(preview);

                                if (null != copiedSheet && null != copiedView)
                                {
                                    if (Viewport.CanAddViewToSheet(preview.RecipientModelInfo.Doc, copiedSheet.Id, copiedView.Id))
                                    {
                                        Viewport viewport = DuplicateViewPort(preview, copiedSheet, copiedView);
                                    }
                                }
                            }
                            else
                            {
                                copiedView = DuplicateDraftingViews(preview);
                            }
                        }
                        preview = UpdatePreviewMap(preview, copiedView);
                    }
                    tg.Assimilate();
                }
            }
            catch (Exception ex)
            {
                errorMessage.AppendLine(previewMap.SourceViewProperties.ViewName + ": errors in duplicating detailing across views\n" + ex.Message);
                //MessageBox.Show("Failed to duplicate drafiting views.\n" + ex.Message, "Duplicate Drafting Views", MessageBoxButton.OK, MessageBoxImage.Warning);
            }
            return(preview);
        }
Beispiel #18
0
        public Result Execute(ExternalCommandData commandData, ref string message, ElementSet elements)
        {
            var doc = commandData.Application.ActiveUIDocument.Document;

            try
            {
                var transaction = new Transaction(doc, "创建图纸");
                transaction.Start();

                #region 创建楼层平面
                var level        = Level.Create(doc, 1);
                var viewTypeList = from element in new FilteredElementCollector(doc).
                                   OfClass(typeof(ViewFamilyType))
                                   let type = element as ViewFamilyType
                                              where type.ViewFamily == ViewFamily.FloorPlan
                                              select type;
                var viewTypeId = viewTypeList?.FirstOrDefault()?.Id;
                if (viewTypeId == null)
                {
                    throw new Exception("没有找到楼层平面");
                }
                var viewPlan = ViewPlan.Create(doc, viewTypeId, level.Id);
                #endregion

                #region 添加文字

                #region 创建文字类型
                TextNoteType newTextNoteType;
                var          textFamilyName   = "3.5mm 宋体";
                var          textNoteTypeList = from element in new FilteredElementCollector(doc).
                                                OfClass(typeof(TextNoteType))
                                                let type = element as TextNoteType
                                                           where type.FamilyName == "文字" && type.Name == textFamilyName
                                                           select type;
                if (textNoteTypeList.Count() > 0)
                {
                    newTextNoteType = textNoteTypeList.FirstOrDefault();
                }
                else
                {
                    textNoteTypeList = from element in new FilteredElementCollector(doc).
                                       OfClass(typeof(TextNoteType))
                                       let type = element as TextNoteType
                                                  where type.FamilyName == "文字"
                                                  select type;
                    var textNoteType = textNoteTypeList.FirstOrDefault();
                    newTextNoteType = textNoteType.Duplicate(textFamilyName) as TextNoteType;
                    newTextNoteType.get_Parameter(BuiltInParameter.TEXT_SIZE).Set(3.5 / 304.8);//文字大小
                    newTextNoteType.get_Parameter(BuiltInParameter.TEXT_FONT).Set("宋体");
                    newTextNoteType.get_Parameter(BuiltInParameter.TEXT_BACKGROUND).Set(1);
                }
                #endregion

                #region 创建文字
                var option = new TextNoteOptions();
                option.HorizontalAlignment = HorizontalTextAlignment.Center;
                option.TypeId = newTextNoteType.Id;
                var textNote = TextNote.Create(doc, viewPlan.Id, new XYZ(0, 0, 0), viewPlan.Name, option);


                #endregion


                #endregion

                #region 应用视图样板
                var viewTemplateList = from element in new FilteredElementCollector(doc).
                                       OfClass(typeof(ViewPlan))
                                       let view = element as ViewPlan
                                                  where view.IsTemplate && view.Name == "Architectural Plan"
                                                  select view;
                var viewTemplate = viewTemplateList?.FirstOrDefault();
                if (viewTemplate == null)
                {
                    throw new Exception("没有找到视图样板");
                }
                viewPlan.ViewTemplateId = viewTemplate.Id;

                #endregion

                #region 添加标注
                var dimTypeList = from element in new FilteredElementCollector(doc).
                                  OfClass(typeof(DimensionType))
                                  let type = element as DimensionType
                                             where type.Name == "Feet & Inches"
                                             select type;
                var targetDimensionType = dimTypeList?.FirstOrDefault();

                var wall = doc.GetElement(new ElementId(1101836)) as Wall;
                var wallLocationCurve = (wall.Location as LocationCurve).Curve;
                var wallDirection     = (wallLocationCurve as Line).Direction;
                var options           = new Options();
                options.ComputeReferences = true;
                var wallSolid  = wall.GetGeometryObjects(options).FirstOrDefault() as Solid;
                var references = new ReferenceArray();
                foreach (Face face in wallSolid.Faces)
                {
                    if (face is PlanarFace pFace &&
                        pFace.FaceNormal.CrossProduct(wallDirection).IsAlmostEqualTo(XYZ.Zero)
                        )
                    {
                        references.Append(face.Reference);
                    }
                }
                var offset = 1000 / 304.8;
                var line   = Line.CreateBound(wallLocationCurve.GetEndPoint(0) + XYZ.BasisY * offset,
                                              wallLocationCurve.GetEndPoint(1) + XYZ.BasisY * offset);
                var dimension = doc.Create.NewDimension(viewPlan, line, references);
                dimension.DimensionType = targetDimensionType;


                #endregion
                #region 创建图纸
                var sheet = ViewSheet.Create(doc, new ElementId(382615));


                #endregion

                #region 添加视图到图纸
                if (Viewport.CanAddViewToSheet(doc, sheet.Id, viewPlan.Id))
                {
                    var uv       = new XYZ(698 / 304.8 / 2, 522 / 304.8 / 2, 0);
                    var viewPort = Viewport.Create(doc, sheet.Id, viewPlan.Id, uv);
                }

                #endregion

                transaction.Commit();
            }
            catch (Exception e)
            {
                return(Result.Failed);
            }

            return(Result.Succeeded);
        }
        private string DeleteViews(Document curDoc, string viewsToKeepPrefix)
        {
            //string functionReturnValue = null;
            //collect all views in current model file
            FilteredElementCollector viewCollector = new FilteredElementCollector(curDoc);

            viewCollector.OfCategory(BuiltInCategory.OST_Views);

            //collect all sheets in current model file
            FilteredElementCollector sheetCollector = new FilteredElementCollector(curDoc);

            sheetCollector.OfCategory(BuiltInCategory.OST_Sheets);

            //check if there are any sheets in this model file - if not then alert user
            if (sheetCollector.Count() < 1)
            {
                //alert user
                TaskDialog dialog = new TaskDialog("Error");
                dialog.MainInstruction = "This model file does not contain any sheets. At least one sheet is needed to delete unused views.";
                dialog.MainIcon        = TaskDialogIcon.TaskDialogIconWarning;
                dialog.Show();
                return(null);
                //return functionReturnValue;
            }

            //get sheet to test views against
            ViewSheet tempSheet = null;

            tempSheet = (ViewSheet)sheetCollector.FirstElement();

            //create list of views to delete
            List <View> viewDeleteList = new List <View>();

            //create string for list of views
            string viewDeleteString = "";

            //loop through each view and check if it can be put onto a sheet
            foreach (View curView in viewCollector)
            {
                //check if current view is a template - skip view if template
                if (curView.IsTemplate == false)
                {
                    //check if view has dependent views
                    if (curView.GetDependentViewIds().Count == 0)
                    {
                        //check if view can be put on sheet - if it can then put in list of views to delete
                        if (Viewport.CanAddViewToSheet(curDoc, tempSheet.Id, curView.Id) == true)
                        {
                            //check if view has prefix
                            if (!curView.Name.StartsWith(viewsToKeepPrefix))
                            {
                                //add view to delete list
                                viewDeleteList.Add(curView);
                            }
                        }
                    }
                }
            }

            //change the current view to the first sheet view
            ViewSheet curSheetView = getSheetView(curDoc);

            this.Application.ActiveUIDocument.ActiveView = curSheetView;

            //if there are views to delete then delete them
            if (viewDeleteList.Count > 0)
            {
                //create transaction and delete unused views
                using (Transaction curTrans = new Transaction(curDoc, "Delete views")) {
                    if (curTrans.Start() == TransactionStatus.Started)
                    {
                        //loop through views to delete list and delete views
                        foreach (View deleteView in viewDeleteList)
                        {
                            //add view to deleted view string
                            viewDeleteString = viewDeleteString + " " + deleteView.Name + ", ";
                            //delete view
                            try {
                                curDoc.Delete(deleteView.Id);
                            } catch (Exception ex) {
                                TaskDialog.Show("error", "Could not delete view " + deleteView.Name);
                            }
                        }
                    }

                    //commit changes to the model
                    curTrans.Commit();
                }
            }

            //return list of deleted views
            return(viewDeleteString);
            //return functionReturnValue;
        }
Beispiel #20
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();
                        }
                    }
                }
            }
        }
Beispiel #21
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);
        }