Esempio n. 1
0
        /// <summary>
        /// Adds the cad link.
        /// </summary>
        /// <param name="doc"></param>
        /// <param name="linkPath"></param>
        public static void AddCadLink(this Document doc, string linkPath)
        {
            var options = new DWGImportOptions {
                OrientToView = true
            };

            doc.Link(linkPath, options, doc.ActiveView, out _);
        }
Esempio n. 2
0
        public IExternalCommand.Result Execute(ExternalCommandData commandData, ref string message, ElementSet elements)
        {
            Document curDoc = commandData.Application.ActiveDocument;
            //创建一个默认的导入选项
            DWGImportOptions dwgOpt = new DWGImportOptions();
            Element elem = new Element();
            //导入指定目录下的一个dwg文件,导入前确保该dwg文件已存在
            curDoc.Import("c:\\a.dwg", dwgOpt, ref elem);

            return IExternalCommand.Result.Succeeded;
        }
Esempio n. 3
0
        void Createdrafting(Document doc, Selection sel, UIDocument uidoc, List <ElementId> list)
        {
            var list1 = HideIsolate(doc, list);

            uidoc.RefreshActiveView();
            string file  = null;
            string file2 = null;

            try
            {
                using (Transaction tr = new Transaction(doc, "Delete"))
                {
                    tr.Start();
                    bool             exported   = false;
                    ElementId        outid      = ElementId.InvalidElementId;
                    DWGExportOptions dwgOptions = new DWGExportOptions();
                    dwgOptions.FileVersion = ACADVersion.R2007;
                    View v      = null;
                    var  option = new CopyPasteOptions();
                    option.SetDuplicateTypeNamesHandler(new CopyHandler());
                    ICollection <ElementId> views = new List <ElementId>();
                    views.Add(doc.ActiveView.Id);
                    var fd = Environment.GetFolderPath(Environment.SpecialFolder.Desktop);
                    exported = doc.Export(fd, "234567", views, dwgOptions);
                    file     = Path.Combine(fd, "234567" + ".dwg");
                    file2    = Path.Combine(fd, "234567" + ".PCP");
                    var dwgimport = new DWGImportOptions();
                    dwgimport.ColorMode = ImportColorMode.BlackAndWhite;
                    if (exported)
                    {
                        v = CreateDrafting(doc);
                        doc.Import(file, dwgimport, v, out outid);
                        File.Delete(file);
                        File.Delete(file2);
                    }
                    if (doc.GetElement(outid).Pinned)
                    {
                        doc.GetElement(outid).Pinned = false;
                    }
                    ElementTransformUtils.CopyElements(v, new List <ElementId> {
                        outid
                    }, doc.ActiveView, Transform.Identity, option);
                    doc.ActiveView.UnhideElements(list1);
                    doc.Delete(v.Id);
                    tr.Commit();
                }
            }
            catch
            {
                File.Delete(file);
                File.Delete(file2);
            }
        }
Esempio n. 4
0
        /// <summary>
        /// Implement this method as an external command for Revit.
        /// </summary>
        /// <param name="commandData">An object that is passed to the external application
        /// which contains data related to the command,
        /// such as the application object and active view.</param>
        /// <param name="message">A message that can be set by the external application
        /// which will be displayed if a failure or cancellation is returned by
        /// the external command.</param>
        /// <param name="elements">A set of elements to which the external application
        /// can add elements that are to be highlighted in case of failure or cancellation.</param>
        /// <returns>Return the status of the external command.
        /// A result of Succeeded means that the API external method functioned as expected.
        /// Cancelled can be used to signify that the user cancelled the external operation
        /// at some point. Failure should be returned if the application is unable to proceed with
        /// the operation.</returns>
        public Autodesk.Revit.UI.Result Execute(ExternalCommandData commandData,
                                                ref string message, Autodesk.Revit.DB.ElementSet elements)
        {
            try
            {
                m_app = commandData.Application;
                m_doc = commandData.Application.ActiveUIDocument.Document;
                if (null == m_doc)
                {
                    message = "There is no active document.";
                    return(Autodesk.Revit.UI.Result.Failed);
                }

                if (!m_doc.IsFamilyDocument)
                {
                    message = "Current document is not a family document.";
                    return(Autodesk.Revit.UI.Result.Failed);
                }

                // Get the view where the dwg file will be imported
                View view = GetView();
                if (null == view)
                {
                    message = "Opened wrong template file, please use the provided family template file.";
                    return(Autodesk.Revit.UI.Result.Failed);
                }

                // The dwg file which will be imported
                string AssemblyDirectory = Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location);
                string DWGFile           = "Desk.dwg";
                string DWGFullPath       = Path.Combine(AssemblyDirectory, DWGFile);

                Transaction transaction = new Transaction(m_doc, "DWGFamilyCreation");
                transaction.Start();
                // Import the dwg file into current family document
                DWGImportOptions options = new DWGImportOptions();
                options.Placement    = Autodesk.Revit.DB.ImportPlacement.Origin;
                options.OrientToView = true;
                ElementId elementId = null;
                m_doc.Import(DWGFullPath, options, view, out elementId);

                // Add type parameters to the family
                AddParameters(DWGFile);
                transaction.Commit();
            }
            catch (Exception ex)
            {
                message = ex.ToString();
                return(Autodesk.Revit.UI.Result.Failed);
            }

            return(Autodesk.Revit.UI.Result.Succeeded);
        }
Esempio n. 5
0
        /// <summary>
        ///     Creates a cad link.
        /// </summary>
        /// <param name="doc"></param>
        /// <param name="linkPath"></param>
        public static void AddCadLink(this Document doc, string linkPath)
        {
            if (doc == null)
            {
                throw new ArgumentNullException(nameof(doc));
            }

            if (linkPath == null)
            {
                throw new ArgumentNullException(nameof(linkPath));
            }

            var options = new DWGImportOptions {
                OrientToView = true
            };

            doc.Link(linkPath, options, doc.ActiveView, out _);
        }
Esempio n. 6
0
        ImportDwg()
        {
            // get input file of type DWG
            System.Windows.Forms.OpenFileDialog dbox = new System.Windows.Forms.OpenFileDialog();
            dbox.CheckFileExists = true;
            dbox.Multiselect     = false;
            dbox.AddExtension    = true;
            dbox.DefaultExt      = "dwg";
            dbox.Filter          = "DWG Files (*.dwg)|*.dwg";
            dbox.Title           = "DWG file to import";

            if (dbox.ShowDialog() == DialogResult.OK)
            {
                DWGImportOptions opts = new DWGImportOptions();
                opts.Placement = ImportPlacement.Origin;

                ElementId newElementId;
                m_revitApp.ActiveUIDocument.Document.Import(dbox.FileName, opts, m_revitApp.ActiveUIDocument.ActiveView, out newElementId);
            }
        }
        public static ElementId Insert(View view, string fileNmae)
        {
            Document         doc     = view.Document;
            DWGImportOptions options = new DWGImportOptions();
            ElementId        linkId;

            using (Transaction t = new Transaction(doc, "InsertDWGLink"))
            {
                t.Start();
                if (doc.Link(fileNmae, options, view, out linkId))
                {
                    t.Commit();
                }
                else
                {
                    t.RollBack();
                    throw (new Exception("Не удалось вставить DWG файл"));
                }
            }
            return(linkId);
        }
Esempio n. 8
0
        /// <summary>
        /// Collect the parameters and export
        /// </summary>
        /// <returns></returns>
        public override bool Import()
        {
            bool imported = false;

            //parameter: DWGImportOptions
            DWGImportOptions dwgImportOption = new DWGImportOptions();

            dwgImportOption.ColorMode    = m_importColorMode;
            dwgImportOption.CustomScale  = m_importCustomScale;
            dwgImportOption.OrientToView = m_importOrientToView;
            dwgImportOption.Placement    = m_importPlacement;
            dwgImportOption.ThisViewOnly = m_importThisViewOnly;
            View view = null;

            if (!m_importThisViewOnly)
            {
                view = m_importView;
            }
            else
            {
                view = m_activeDoc.ActiveView;
            }
            dwgImportOption.Unit = m_importUnit;
            dwgImportOption.VisibleLayersOnly = m_importVisibleLayersOnly;

            //parameter: ElementId
            ElementId elementId = null;

            //Import
            Transaction t = new Transaction(m_activeDoc);

            t.SetName("Import");
            t.Start();
            imported = m_activeDoc.Import(m_importFileFullName, dwgImportOption, view, out elementId);
            t.Commit();

            return(imported);
        }
        Stream(ArrayList data, DWGImportOptions dwgImpOptions)
        {
            data.Add(new Snoop.Data.ClassSeparator(typeof(DWGImportOptions)));

            // No data at this level yet.
        }
Esempio n. 10
0
        CollectEvent(object sender, CollectorEventArgs e)
        {
            // cast the sender object to the SnoopCollector we are expecting
            Collector snoopCollector = sender as Collector;

            if (snoopCollector == null)
            {
                Debug.Assert(false); // why did someone else send us the message?
                return;
            }

            // see if it is a type we are responsible for
            Color color = e.ObjToSnoop as Color;

            if (color != null)
            {
                Stream(snoopCollector.Data(), color);
                return;
            }

            LayoutRule layoutRule = e.ObjToSnoop as LayoutRule;

            if (layoutRule != null)
            {
                Stream(snoopCollector.Data(), layoutRule);
                return;
            }

            FormatOptions formatOptions = e.ObjToSnoop as FormatOptions;

            if (formatOptions != null)
            {
                Stream(snoopCollector.Data(), formatOptions);
                return;
            }

            CurtainGrid curtainGrid = e.ObjToSnoop as CurtainGrid;

            if (curtainGrid != null)
            {
                Stream(snoopCollector.Data(), curtainGrid);
                return;
            }

            CurtainCell curtainCell = e.ObjToSnoop as CurtainCell;

            if (curtainCell != null)
            {
                Stream(snoopCollector.Data(), curtainCell);
                return;
            }

            RebarHostData rebarHostData = e.ObjToSnoop as RebarHostData;

            if (rebarHostData != null)
            {
                Stream(snoopCollector.Data(), rebarHostData);
                return;
            }

            Leader leader = e.ObjToSnoop as Leader;

            if (leader != null)
            {
                Stream(snoopCollector.Data(), leader);
                return;
            }

            AreaVolumeSettings areaSettings = e.ObjToSnoop as AreaVolumeSettings;

            if (areaSettings != null)
            {
                Stream(snoopCollector.Data(), areaSettings);
                return;
            }

            ViewSheetSetting viewSheetSetting = e.ObjToSnoop as ViewSheetSetting;

            if (viewSheetSetting != null)
            {
                Stream(snoopCollector.Data(), viewSheetSetting);
                return;
            }

            Autodesk.Revit.UI.Events.DialogBoxData dlgBoxData = e.ObjToSnoop as Autodesk.Revit.UI.Events.DialogBoxData;
            if (dlgBoxData != null)
            {
                Stream(snoopCollector.Data(), dlgBoxData);
                return;
            }

            Construction construct = e.ObjToSnoop as Construction;

            if (construct != null)
            {
                Stream(snoopCollector.Data(), construct);
                return;
            }

            FamilyElementVisibility famElemVisib = e.ObjToSnoop as FamilyElementVisibility;

            if (famElemVisib != null)
            {
                Stream(snoopCollector.Data(), famElemVisib);
                return;
            }

            FamilyManager famManager = e.ObjToSnoop as FamilyManager;

            if (famManager != null)
            {
                Stream(snoopCollector.Data(), famManager);
                return;
            }

            FamilyParameter famParam = e.ObjToSnoop as FamilyParameter;

            if (famParam != null)
            {
                Stream(snoopCollector.Data(), famParam);
                return;
            }

            FamilyType famType = e.ObjToSnoop as FamilyType;

            if (famType != null)
            {
                Stream(snoopCollector.Data(), famType);
                return;
            }

            MEPSpaceConstruction mepSpaceConstuct = e.ObjToSnoop as MEPSpaceConstruction;

            if (mepSpaceConstuct != null)
            {
                Stream(snoopCollector.Data(), mepSpaceConstuct);
                return;
            }

            BuildingSiteExportOptions bldSiteExpOptions = e.ObjToSnoop as BuildingSiteExportOptions;

            if (bldSiteExpOptions != null)
            {
                Stream(snoopCollector.Data(), bldSiteExpOptions);
                return;
            }

            DGNExportOptions dgnExpOptions = e.ObjToSnoop as DGNExportOptions;

            if (dgnExpOptions != null)
            {
                Stream(snoopCollector.Data(), dgnExpOptions);
                return;
            }

            DWFExportOptions dwfExpOptions = e.ObjToSnoop as DWFExportOptions;

            if (dwfExpOptions != null)
            {
                Stream(snoopCollector.Data(), dwfExpOptions);
                return;
            }

            DWGExportOptions dwgExpOptions = e.ObjToSnoop as DWGExportOptions;

            if (dwgExpOptions != null)
            {
                Stream(snoopCollector.Data(), dwgExpOptions);
                return;
            }

            DWGImportOptions dwgImpOptions = e.ObjToSnoop as DWGImportOptions;

            if (dwgImpOptions != null)
            {
                Stream(snoopCollector.Data(), dwgImpOptions);
                return;
            }

            FBXExportOptions fbxExpOptions = e.ObjToSnoop as FBXExportOptions;

            if (fbxExpOptions != null)
            {
                Stream(snoopCollector.Data(), fbxExpOptions);
                return;
            }

            TrussMemberInfo trussInfo = e.ObjToSnoop as TrussMemberInfo;

            if (trussInfo != null)
            {
                Stream(snoopCollector.Data(), trussInfo);
                return;
            }

            VertexIndexPair vertIndPair = e.ObjToSnoop as VertexIndexPair;

            if (vertIndPair != null)
            {
                Stream(snoopCollector.Data(), vertIndPair);
                return;
            }

            PointElementReference ptElemRef = e.ObjToSnoop as PointElementReference;

            if (ptElemRef != null)
            {
                Stream(snoopCollector.Data(), ptElemRef);
                return;
            }

            Autodesk.Revit.DB.Architecture.BoundarySegment boundSeg = e.ObjToSnoop as Autodesk.Revit.DB.Architecture.BoundarySegment;
            if (boundSeg != null)
            {
                Stream(snoopCollector.Data(), boundSeg);
                return;
            }

            PointLocationOnCurve ptLocOnCurve = e.ObjToSnoop as PointLocationOnCurve;

            if (ptLocOnCurve != null)
            {
                Stream(snoopCollector.Data(), ptLocOnCurve);
                return;
            }

            Entity entity = e.ObjToSnoop as Entity;

            if (entity != null)
            {
                Stream(snoopCollector.Data(), entity);
                return;
            }

            Field field = e.ObjToSnoop as Field;

            if (field != null)
            {
                Stream(snoopCollector.Data(), field);
                return;
            }

            ExtensibleStorageField storeagefield = e.ObjToSnoop as ExtensibleStorageField;

            if (storeagefield != null)
            {
                Stream(snoopCollector.Data(), storeagefield);
                return;
            }

            IList <Autodesk.Revit.DB.BoundarySegment> boundSegs = e.ObjToSnoop as
                                                                  IList <Autodesk.Revit.DB.BoundarySegment>;

            if (boundSegs != null)
            {
                Stream(snoopCollector.Data(), boundSegs);
                return;
            }

            if (e.ObjToSnoop is KeyValuePair <String, String> )
            {
                KeyValuePair <String, String> stringspair = (KeyValuePair <String, String>)e.ObjToSnoop;
                Stream(snoopCollector.Data(), stringspair);
                return;
            }

            Schema schema = e.ObjToSnoop as Schema;

            if (schema != null)
            {
                Stream(snoopCollector.Data(), schema);
                return;
            }

            ElementId elemId = e.ObjToSnoop as ElementId;

            if (elemId != null)
            {
                Stream(snoopCollector.Data(), elemId);
                return;
            }

            PlanViewRange plvr = e.ObjToSnoop as PlanViewRange;

            if (plvr != null)
            {
                Stream(snoopCollector.Data(), plvr);
                return;
            }
            //TF
            RebarConstraintsManager rbcm = e.ObjToSnoop as RebarConstraintsManager;

            if (rbcm != null)
            {
                Stream(snoopCollector.Data(), rbcm);
                return;
            }

            RebarConstrainedHandle rbch = e.ObjToSnoop as RebarConstrainedHandle;

            if (rbch != null)
            {
                Stream(snoopCollector.Data(), rbch);
                return;
            }

            RebarConstraint rbc = e.ObjToSnoop as RebarConstraint;

            if (rbc != null)
            {
                Stream(snoopCollector.Data(), rbc);
                return;
            }

            //TFEND

            if (Utils.IsSupportedType(e.ObjToSnoop) && e.ObjToSnoop != null)
            {
                Utils.StreamWithReflection(snoopCollector.Data(), e.ObjToSnoop.GetType(), e.ObjToSnoop);
            }
        }
Esempio n. 11
0
        public View ExportDWG(Document document, View view, out string file)
        {
            bool             exported   = false;
            ElementId        outid      = ElementId.InvalidElementId;
            DWGExportOptions dwgOptions = new DWGExportOptions();

            dwgOptions.FileVersion    = ACADVersion.R2007;
            dwgOptions.ExportOfSolids = SolidGeometry.Polymesh;
            dwgOptions.ACAPreference  = ACAObjectPreference.Geometry;
            dwgOptions.MergedViews    = true;
            dwgOptions.PropOverrides  = PropOverrideMode.ByEntity;
            View v = null;
            ICollection <ElementId> views = new List <ElementId>();

            views.Add(view.Id);
            var pathfile = SettingFreeze.Instance.GetFolderPath();

            if (view is View3D)
            {
                List <ElementId> vSet = new List <ElementId>();
                bool             flag = view != null;
                if (flag)
                {
                    View3D    tmp3D     = null;
                    ViewSheet viewSheet = null;
                    bool      proceed   = false;
                    try
                    {
                        FilteredElementCollector filteredElementCollector = new FilteredElementCollector(doc);
                        filteredElementCollector.OfClass(typeof(FamilySymbol));
                        filteredElementCollector.OfCategory(BuiltInCategory.OST_TitleBlocks);
                        IList <Element>     titleBlocks   = filteredElementCollector.ToElements();
                        List <FamilySymbol> familySymbols = new List <FamilySymbol>();
                        foreach (Element element in titleBlocks)
                        {
                            FamilySymbol f     = element as FamilySymbol;
                            bool         flag3 = f != null;
                            if (flag3)
                            {
                                familySymbols.Add(f);
                            }
                        }
                        bool flag4 = titleBlocks.Count != 0;
                        if (flag4)
                        {
                            FamilySymbol fs = null;
                            foreach (FamilySymbol f2 in familySymbols)
                            {
                                bool flag5 = f2 != null;
                                if (flag5)
                                {
                                    fs = f2;
                                    break;
                                }
                            }
                            viewSheet = ViewSheet.Create(doc, fs.Id);
                            bool flag6 = viewSheet != null;
                            if (flag6)
                            {
                                UV location = new UV((viewSheet.Outline.Max.U - viewSheet.Outline.Min.U) / 2.0, (viewSheet.Outline.Max.V - viewSheet.Outline.Min.V) / 2.0);
                                try
                                {
                                    Viewport.Create(doc, viewSheet.Id, view.Id, new XYZ(location.U, location.V, 0.0));
                                }
                                catch
                                {
                                    try
                                    {
                                        XYZ             tmpXYZ           = new XYZ(-view.ViewDirection.X, -view.ViewDirection.Y, -view.ViewDirection.Z);
                                        BoundingBoxXYZ  tmpBoundingBox   = view.CropBox;
                                        bool            tmpCropBoxActive = view.CropBoxActive;
                                        IList <Element> viewTypes        = new FilteredElementCollector(doc).OfClass(typeof(ViewFamilyType)).ToElements();
                                        ElementId       viewTypeid       = null;
                                        foreach (Element viewType in viewTypes)
                                        {
                                            ViewFamilyType famType = viewType as ViewFamilyType;
                                            bool           flag7   = famType != null && famType.ViewFamily == ViewFamily.ThreeDimensional;
                                            if (flag7)
                                            {
                                                viewTypeid = famType.Id;
                                                break;
                                            }
                                        }
                                        bool flag8 = viewTypeid != null;
                                        if (flag8)
                                        {
                                            tmp3D = View3D.CreateIsometric(doc, viewTypeid);
                                            tmp3D.ApplyViewTemplateParameters(view);
                                            tmp3D.CropBox = tmpBoundingBox;
                                            Viewport.Create(doc, viewSheet.Id, tmp3D.Id, new XYZ(location.U, location.V, 0.0));
                                        }
                                    }
                                    catch
                                    {
                                    }
                                }
                                vSet.Add(viewSheet.Id);
                                proceed = true;
                            }
                        }
                    }
                    catch
                    {
                    }
                    bool flag9 = proceed;
                    if (flag9)
                    {
                        exported = document.Export(pathfile, view.Name, vSet, dwgOptions);
                        bool flag10 = viewSheet != null;
                        if (flag10)
                        {
                            ElementId elementId = viewSheet.Id;
                            doc.Delete(elementId);
                        }
                        bool flag11 = tmp3D != null;
                        if (flag11)
                        {
                            ElementId elementId2 = tmp3D.Id;
                            doc.Delete(elementId2);
                        }
                    }
                }
            }
            else
            {
                exported = document.Export(pathfile, view.Name, views, dwgOptions);
            }
            if (tmp3D != null)
            {
                file = Path.Combine(pathfile, tmp3D.Name + ".dwg");
            }
            else
            {
                file = Path.Combine(pathfile, view.Name + ".dwg");
            }
            if (exported)
            {
                TaskDialog taskDialog = new TaskDialog("Freeze View");
                taskDialog.Id                = "Freeze";
                taskDialog.Title             = "Freeze Drawing";
                taskDialog.TitleAutoPrefix   = true;
                taskDialog.MainIcon          = TaskDialogIcon.TaskDialogIconInformation;
                taskDialog.AllowCancellation = true;
                taskDialog.MainInstruction   = ("Select View Type :");
                taskDialog.AddCommandLink((TaskDialogCommandLinkId)1001, "Drafting View");
                taskDialog.AddCommandLink((TaskDialogCommandLinkId)1002, "Legend");
                taskDialog.CommonButtons = TaskDialogCommonButtons.Cancel;
                taskDialog.DefaultButton = ((TaskDialogResult)2);
                TaskDialogResult taskDialogResult = taskDialog.Show();
                var dwgimport = new DWGImportOptions();
                dwgimport.ColorMode    = ImportColorMode.BlackAndWhite;
                dwgimport.ThisViewOnly = true;
                dwgimport.OrientToView = true;
                dwgimport.Placement    = ImportPlacement.Origin;
                if (taskDialogResult == TaskDialogResult.CommandLink2)
                {
                    v = GetLegend(document);
                }
                else if (taskDialogResult == TaskDialogResult.CommandLink1)
                {
                    v = CreateDrafting(document);
                }
                if (v != null)
                {
                    document.Import(file, dwgimport, v, out outid);
                }
                string strPost  = "(Forzen)";
                string newname  = this.ReplaceForbiddenSigns(doc.ActiveView.Name);
                string tempName = newname;
                if (v != null)
                {
                    int j = 1;
                    for (; ;)
                    {
                        try
                        {
                            v.Name = newname + strPost;
                            break;
                        }
                        catch
                        {
                            bool flag2 = j > 10;
                            if (flag2)
                            {
                                try
                                {
                                    v.Name += strPost;
                                }
                                catch
                                {
                                }
                                break;
                            }
                            newname = tempName + "-" + j.ToString();
                            j++;
                        }
                    }
                }
            }
            return(v);
        }
Esempio n. 12
0
        public Result Execute(ExternalCommandData commandData, ref string message, ElementSet elements)
        {
            if (null == commandData)
            {
                throw new ArgumentNullException("commandData");
            }

            Initilize c       = new Initilize();
            bool      success = c.IsAppInitialized();

            if (!success)
            {
                return(Result.Cancelled);
            }


            UIApplication uiapp = commandData.Application;
            UIDocument    uidoc = uiapp.ActiveUIDocument;

            Autodesk.Revit.ApplicationServices.Application app = uiapp.Application;
            Document doc = uidoc.Document;


            //Set counter
            int counter = 0;


            //Open the form
            using (frmRevitize curForm = new frmRevitize(commandData))
            {
                //Show the form
                curForm.ShowDialog();

                if (curForm.DialogResult == System.Windows.Forms.DialogResult.Cancel)
                {
                    //The user canceled
                    return(Result.Cancelled);
                }
                else
                {
                    //Get the selected DWG files
                    List <string> drawingList = curForm.getSelectedDWGs();

                    using (Transaction tx = new Transaction(doc, "Import DWGs to Drafting Views"))
                    {
                        if (tx.Start() == TransactionStatus.Started)
                        {
                            //Loop through DWGs, create Drafting View and insert
                            foreach (string curDWG in drawingList)
                            {
                                //get family type for drafting view
                                ElementId curVFT = getDraftingViewFamilyType(doc);

                                //create drafting view
                                Autodesk.Revit.DB.View curView = ViewDrafting.Create(doc, curVFT);

                                //add the view to the list to be passed out of this
                                createdViewList.Insert(curView);


                                //rename the view to the DWG filename
                                string tmpName  = getFilenameFromPath(curDWG);
                                string viewName = tmpName.Substring(0, tmpName.Length - 4);

                                try
                                {
                                    curView.Name = viewName;
                                }
                                catch (Exception ex)
                                {
                                    TaskDialog.Show("Error", "These is already a Drafting View named " + viewName + "in this project file. The view will be named " + curView.Name + " instead.");
                                    throw;
                                }

                                //set insert settings
                                DWGImportOptions curImportOptions = new DWGImportOptions();



                                switch (curForm.getColorSetting())
                                {
                                case "Invert":
                                    curImportOptions.ColorMode = ImportColorMode.Inverted;
                                    break;

                                case "Preserve":
                                    curImportOptions.ColorMode = ImportColorMode.Preserved;
                                    break;

                                default:
                                    curImportOptions.ColorMode = ImportColorMode.BlackAndWhite;
                                    break;
                                }

                                switch (curForm.getPosSetting())
                                {
                                case "Origin to Origin":
                                    curImportOptions.Placement = ImportPlacement.Origin;
                                    break;

                                case "Center to Center":
                                    curImportOptions.Placement = ImportPlacement.Centered;
                                    break;
                                }

                                //import / link current DWG to current view
                                ElementId curLinkID = null;


                                if (curForm.getInsertType() == "Link")
                                {
                                    doc.Link(curDWG, curImportOptions, curView, out curLinkID);
                                    counter = counter + 1;
                                }
                                else
                                {
                                    doc.Import(curDWG, curImportOptions, curView, out curLinkID);

                                    counter = counter + 1;
                                }
                            }
                        }


                        //commit changes
                        tx.Commit();
                    }
                }
            }



            //ask user if they want to create a sheet
            string      summeryMessage = " Inserted " + counter + " DWG Files.";
            bool        createSheet    = createSheetYesNo(summeryMessage);
            frmRevitize f1             = new frmRevitize(commandData);

            f1.Close();

            if (createSheet)
            {
                cmdSheetsFromViews cmd = new cmdSheetsFromViews();
                cmd.Execute(commandData, ref message, elements, createdViewList);
            }

            return(Result.Succeeded);
        }
Esempio n. 13
0
        //******************************************************************************************
        /// <summary>
        /// this function imports all views from the list and create new draft views for them based on m_path
        /// </summary>
        public void Import(bool argCopy, string argBrowse, string argBaseName, Autodesk.Revit.DB.DWGImportOptions argOpt, List <ViewPath> argViewList, IREXProgress argProgress)
        {
            ViewDrafting     draftView;
            DWGImportOptions setDwgImp;
            IREXProgress     Progress = argProgress;

            DialogMessageExists dlgMsg = new DialogMessageExists(ThisExtension);

            dlgMsg.Text = Resources.Strings.Texts.REX_ModuleDescription;

            //getting file list from the directory
            string[] FileList = Directory.GetFiles(m_path, "*.dwg");

            List <string> SelectFileList = new List <string>();

            string newname;
            string strPost = " (" + Resources.Strings.Texts.Freezed + ")";

            Progress.Position = 0;
            Progress.Steps    = 2 * argViewList.Count;
            Progress.Header   = Resources.Strings.Texts.FreezeInProgress + " - " + Resources.Strings.Texts.Import;

            ViewFamilyType           viewFamilyType = null;
            FilteredElementCollector collector      = new FilteredElementCollector(m_CommandData.Application.ActiveUIDocument.Document);
            var viewFamilyTypes = collector.OfClass(typeof(ViewFamilyType)).ToElements();

            foreach (Element e in viewFamilyTypes)
            {
                ViewFamilyType v = e as ViewFamilyType;
                if (v.ViewFamily == ViewFamily.Drafting)
                {
                    viewFamilyType = v;
                    break;
                }
            }

            //importing files to Revit
            foreach (ViewPath v in argViewList)
            {
                draftView = ViewDrafting.Create(m_CommandData.Application.ActiveUIDocument.Document, viewFamilyType.Id);

                newname = ReplaceForbiddenSigns(v.fullViewName);

                string tempName = newname;
                int    i        = 1;
                for (;;)
                {
                    try
                    {
                        draftView.Name = newname + strPost;
                        break;
                    }
                    catch
                    {
                        if (i > 10)
                        {
                            try
                            {
                                draftView.Name = draftView.Name + strPost;
                            }
                            catch
                            {
                            }
                            break;
                        }
                        newname = tempName + "-" + i.ToString();
                        i++;
                    }
                }

                draftView.Scale = v.ViewRevit.Scale;

                Progress.Step(draftView.Name);

                //properties
                setDwgImp              = new DWGImportOptions();
                setDwgImp.ColorMode    = argOpt.ColorMode;
                setDwgImp.OrientToView = argOpt.OrientToView;
                setDwgImp.Unit         = argOpt.Unit;
                setDwgImp.CustomScale  = argOpt.CustomScale;

                //import
                RevitElement el = (RevitElement)draftView;
                if (File.Exists(v.path))
                {
                    ElementId id;
                    m_CommandData.Application.ActiveUIDocument.Document.Import(v.path, setDwgImp, draftView, out id);
                    v.DraftingName = draftView.Name;

                    //copying to user directory
                    if (argCopy)
                    {
                        CopyToUserDirViewPath(v, argBaseName, argBrowse, dlgMsg);
                    }
                }
                Progress.Step(draftView.Name);
            }
            dlgMsg.Dispose();
        }
Esempio n. 14
0
        public static ExternalEvent LibraryAction(UIApplication revit)
        {
            // get the UIApplication object, which opens the Revit API for you...
            UIDocument  uidoc = revit.ActiveUIDocument;
            Document    doc   = revit.ActiveUIDocument.Document;
            Transaction trans = new Transaction(revit.ActiveUIDocument.Document, "Part Library");

            if (MessageHandler.LibraryToAppActions.Count > 0)
            {
                string action = MessageHandler.LibraryToAppActions.Dequeue();
                //MessageBox.Show(action);
                Dictionary <string, string> actionD = JsonConvert.DeserializeObject <Dictionary <string, string> >(action);

                //####################################################
                //#"Start" the transaction
                //trans.Start();
                if (actionD["option"] == "OPEN")
                {
                    try
                    {
                        ElementId     pElementId;
                        List <string> files = Directory.GetFiles(actionD["hyperlink"]).ToList();
                        string        rfa   = "";
                        string        dwg   = "";
                        foreach (string file in files)
                        {
                            if (file.Contains(".rfa"))
                            {
                                rfa = file;
                            }
                            else if (file.Contains(".dwg"))
                            {
                                dwg = file;
                            }
                            else
                            {
                            }
                        }
                        if (rfa != "")
                        {
                            try
                            {
                                revit.OpenAndActivateDocument(rfa);
                            }
                            catch (Exception ex)
                            {
                                MessageBox.Show(ex.Message);
                            }
                        }
                        else if (dwg != "")
                        {
                            Document                 famDoc          = revit.Application.NewFamilyDocument(doc.Application.FamilyTemplatePath + "\\Detail Item.rft");
                            DWGImportOptions         dwgImportOption = new DWGImportOptions();
                            FilteredElementCollector col             = new FilteredElementCollector(famDoc).OfCategory(BuiltInCategory.OST_Views);
                            Autodesk.Revit.DB.View   view            = col.First() as Autodesk.Revit.DB.View;
                            Transaction              famTrans        = new Transaction(famDoc, "Import CAD");
                            famTrans.Start();
                            famDoc.Import(dwg, dwgImportOption, view, out pElementId);
                            famTrans.Commit();

                            SaveAsOptions saveOpt        = new SaveAsOptions();
                            string        familyfilename = dwg.Remove(dwg.Length - 4, 4) + ".rfa";
                            famDoc.SaveAs(familyfilename, saveOpt);
                            famDoc.Close();
                            revit.Application.OpenDocumentFile(familyfilename);
                        }
                    }
                    catch (Exception ex)
                    {
                        MessageBox.Show(ex.Message);
                    }
                }
                else if (actionD["option"] == "LOAD")
                {
                    try
                    {
                        ElementId     pElementId;
                        List <string> files = Directory.GetFiles(actionD["hyperlink"]).ToList();
                        string        rfa   = "";
                        string        dwg   = "";
                        foreach (string file in files)
                        {
                            if (file.Contains(".rfa"))
                            {
                                rfa = file;
                            }
                            else if (file.Contains(".dwg"))
                            {
                                dwg = file;
                            }
                            else
                            {
                            }
                        }
                        if (rfa != "")
                        {
                            Transaction famLoad = new Transaction(doc, "Load Family");
                            famLoad.Start();
                            doc.LoadFamily(rfa);
                            famLoad.Commit();
                        }
                        else if (dwg != "")
                        {
                            Document                 famDoc          = revit.Application.NewFamilyDocument(doc.Application.FamilyTemplatePath + "\\Detail Item.rft");
                            DWGImportOptions         dwgImportOption = new DWGImportOptions();
                            FilteredElementCollector col             = new FilteredElementCollector(famDoc).OfCategory(BuiltInCategory.OST_Views);
                            Autodesk.Revit.DB.View   view            = col.First() as Autodesk.Revit.DB.View;
                            Transaction              famTrans        = new Transaction(famDoc, "Import CAD");
                            famTrans.Start();
                            famDoc.Import(dwg, dwgImportOption, view, out pElementId);
                            famTrans.Commit();

                            SaveAsOptions saveOpt        = new SaveAsOptions();
                            string        familyfilename = dwg.Remove(dwg.Length - 4, 4) + ".rfa";
                            famDoc.SaveAs(familyfilename, saveOpt);
                            famDoc.Close();

                            Transaction famLoad = new Transaction(doc, "Load Family");
                            famLoad.Start();
                            doc.LoadFamily(familyfilename);
                            famLoad.Commit();
                        }
                    }
                    catch (Exception ex)
                    {
                        MessageBox.Show(ex.Message);
                    }
                }
                else if (actionD["option"] == "VIEW")
                {
                    try
                    {
                        ElementId     pElementId;
                        List <string> files = Directory.GetFiles(actionD["hyperlink"]).ToList();
                        string        rfa   = "";
                        string        dwg   = "";
                        foreach (string file in files)
                        {
                            if (file.Contains(".dwg"))
                            {
                                dwg = file;
                            }
                            else
                            {
                            }
                        }
                        if (dwg != "")
                        {
                            string  progId = "AutoCAD.Application";
                            dynamic cadApp = null;


                            try
                            {
                                cadApp = Marshal.GetActiveObject(progId);
                            }
                            catch
                            {
                                try
                                {
                                    Type t = Type.GetTypeFromProgID(progId);
                                    cadApp = Activator.CreateInstance(t);
                                }
                                catch
                                {
                                }
                            }

                            if (cadApp != null)
                            {
                                dynamic cadFile = cadApp.Documents.Open(dwg, false);
                                cadApp.Visible = true;
                            }
                        }
                    }
                    catch (Exception ex)
                    {
                        MessageBox.Show(ex.Message);
                    }
                }

                //# "End" the transaction
                //trans.Commit();
                //####################################################

                // do your Revit tasks here
                //MessageBox.Show("Text received from the Library window: " + actionD);

                // reply something back
                MessageHandler.AppToLibraryActions.Enqueue("A message from the Revit plugin - " + DateTime.Now.ToString());
            }

            return(m_ExEvent);
        }
Esempio n. 15
0
        public Result Execute(ExternalCommandData commandData, ref string messages, ElementSet elements)
        {
            UIApplication uiapp = commandData.Application;
            UIDocument    uidoc = uiapp.ActiveUIDocument;
            Application   app   = uiapp.Application;
            Document      doc   = uidoc.Document;
            Selection     sel   = uidoc.Selection;
            Transaction   trans = new Transaction(doc, "ExComm");

            trans.Start();

            DWGExportOptions options = new DWGExportOptions();
            //SUPPORT.PARAMETER.PARAMETER Para = new SUPPORT.PARAMETER.PARAMETER();
            View      view  = doc.ActiveView;
            ElementId eleid = view.Id;

            ICollection <ElementId>  views    = new List <ElementId>();
            FilteredElementCollector filter   = new FilteredElementCollector(doc);
            FilteredElementCollector Filter   = filter.OfCategory(BuiltInCategory.OST_Views).WhereElementIsNotElementType();
            IList <Element>          list     = Filter.ToElements();
            IList <Element>          lishname = new List <Element>();
            ViewDrafting             drafting = null;
            ElementId newlegend   = null;
            string    currentview = doc.ActiveView.ViewName;
            string    test        = "Zz_" + currentview + "##";
            ElementId id          = null;
            View      viewlegend  = null;

            foreach (var ele1 in list)
            {
                Parameter      parameter = ele1.get_Parameter(BuiltInParameter.VIEW_NAME);
                string         viewname  = parameter.AsString();
                ViewFamilyType vd        = new FilteredElementCollector(doc).OfClass(typeof(ViewFamilyType)).Cast <ViewFamilyType>()
                                           .FirstOrDefault(q => q.ViewFamily == ViewFamily.Drafting);
                views.Add(doc.ActiveView.Id);
                doc.Export(@"C:\Autodesk", "exportdwg.dwg", views, options);
                drafting = ViewDrafting.Create(doc, vd.Id);
                doc.Regenerate();

                DWGImportOptions importOptions = new DWGImportOptions();
                importOptions.ColorMode = ImportColorMode.BlackAndWhite;
                doc.Import(@"C:\Autodesk\\exportdwg.dwg", importOptions, drafting, out id);
                try
                {
                    drafting.Name = test;
                    trans.Commit();
                    commandData.Application.ActiveUIDocument.ActiveView = drafting;
                }
                catch
                {
                    TaskDialog.Show("ERROR", "SECTION NÀY ĐÃ ĐƯỢC TẠO FROZEN");

                    trans.RollBack();
                    break;
                }
                break;
            }

            using (Transaction tx = new Transaction(doc))
            {
                tx.Start("Transaction Name");

                Element               curElem     = doc.GetElement(id);
                ImportInstance        curLink     = (ImportInstance)curElem;
                List <GeometryObject> curveobject = GetLinkedDWGCurves(curLink, doc);

                foreach (GeometryObject curGeom in curveobject)
                {
                    if (curGeom.GetType() == typeof(PolyLine))
                    {
                        // create polyline in current view
                        PolyLine curPolyline = (PolyLine)curGeom;

                        // get polyline coordinate points
                        IList <XYZ> ptsList = curPolyline.GetCoordinates();

                        for (var i = 0; i <= ptsList.Count - 2; i++)
                        {
                            // create detail curve from polyline coordinates
                            try
                            {
                                DetailCurve newDetailLine = doc.Create.NewDetailCurve(doc.ActiveView, Line.CreateBound(ptsList[i], ptsList[i + 1]));
                            }
                            catch
                            {
                            }
                        }
                    }
                    else
                    {
                        try { DetailCurve newDetailLine = doc.Create.NewDetailCurve(doc.ActiveView, (Curve)curGeom); }
                        catch { }
                    }
                }

                FilteredElementCollector legCollector = new FilteredElementCollector(doc).OfClass(typeof(View)).WhereElementIsNotElementType();
                List <View> alllegends = new List <View>();
                foreach (ElementId eid in legCollector.ToElementIds())
                {
                    View v = doc.GetElement(eid) as View;
                    if (v.ViewType == ViewType.Legend)
                    {
                        alllegends.Add(v);
                    }
                }

                newlegend  = alllegends.Last().Duplicate(ViewDuplicateOption.WithDetailing);
                viewlegend = doc.GetElement(newlegend) as View;
                tx.Commit();
            }

            using (Form_FrozenSection form = new Form_FrozenSection(doc, uiapp))
            {
                form.ShowDialog();

                if (form.DialogResult == System.Windows.Forms.DialogResult.Cancel)
                {
                    return(Result.Cancelled);
                }

                if (form.DialogResult == System.Windows.Forms.DialogResult.OK)
                {
                    using (Transaction tx1 = new Transaction(doc))
                    {
                        tx1.Start("Transaction Name");



                        tx1.Commit();
                        uiapp.ActiveUIDocument.ActiveView = form.vsheet();
                    }
                }
                using (Transaction tx2 = new Transaction(doc))
                {
                    tx2.Start("Transaction Name");

                    XYZ pos = uidoc.Selection.PickPoint(ObjectSnapTypes.None, "Chon diem dat legend");
                    Viewport.Create(doc, form.vsheet().Id, newlegend, pos);

                    FilteredElementCollector allElementsInView = new FilteredElementCollector(doc, viewlegend.Id).WhereElementIsNotElementType();
                    ICollection <ElementId>  elementsInView    = allElementsInView.WhereElementIsNotElementType().Where(x => x.Category != null).Select(x => x.Id).ToList();
                    doc.Delete(elementsInView);

                    FilteredElementCollector detailine     = new FilteredElementCollector(doc, drafting.Id);
                    IList <ElementId>        listdetailine = detailine.OfCategory(BuiltInCategory.OST_Lines).WhereElementIsNotElementType().ToElementIds().ToList();

                    Transform tranform = ElementTransformUtils.GetTransformFromViewToView(viewlegend, doc.ActiveView);
                    ElementTransformUtils.CopyElements(drafting, listdetailine, viewlegend, tranform, new CopyPasteOptions());

                    viewlegend.Scale = 16;
                    Parameter viewname = viewlegend.LookupParameter("View Name");
                    string    name     = form.Viewname();
                    viewname.Set(name);
                    doc.Delete(drafting.Id);
                    tx2.Commit();
                }
            }
            return(Result.Succeeded);
        }
Esempio n. 16
0
        public Result Execute(ExternalCommandData commandData, ref string message, ElementSet elements)
        {
            _uiapp = commandData.Application;
            _uidoc = _uiapp.ActiveUIDocument;
            _doc   = _uidoc.Document;

            try
            {
                // Get list of all structural view plans
                IList <ViewPlan> viewPlanList = GetAllStructuralPlans(_doc, true);
                if (viewPlanList.Count == 0)
                {
                    return(Result.Cancelled);
                }

                Dictionary <string, ViewPlan> viewDic = new Dictionary <string, ViewPlan>();
                foreach (ViewPlan vp in viewPlanList)
                {
                    // filter structural view plan
                    Regex regex = new Regex(@"r\+\d+|rdc|ss\d|ss\-\d");
                    Match match = regex.Match(vp.Name.ToLower());
                    // TODO : to be improved
                    if (match.Success && vp.Name.Contains("PH"))
                    {
                        if (!viewDic.ContainsKey(match.Value))
                        {
                            viewDic.Add(match.Value.ToLower(), vp);
                        }
                    }
                }

                CADLinkForm form = new CADLinkForm(viewDic);

                if (form.ShowDialog() == DialogResult.OK)
                {
                    DWGImportOptions opt = new DWGImportOptions
                    {
                        Placement = ImportPlacement.Origin,
                        AutoCorrectAlmostVHLines = true,
                        ThisViewOnly             = false,
                        Unit = form.Unit,
                    };

                    ElementId linkId = ElementId.InvalidElementId;
                    // add links
                    foreach (DataGridViewRow row in form.DataGridView.Rows)
                    {
                        string keyword = row.Cells[0].Value.ToString();
                        if (!string.IsNullOrEmpty(keyword))
                        {
                            ViewPlan view     = viewDic[keyword];
                            string   filePath = row.Cells[2].Value.ToString();
                            using (Transaction tran = new Transaction(_doc, "Quick Link"))
                            {
                                tran.Start();
                                _doc.Link(filePath, opt, view, out linkId);
                                tran.Commit();
                            }
                        }
                    }
                    return(Result.Succeeded);
                }
                else
                {
                    return(Result.Cancelled);
                }
            }
            catch (Exception e)
            {
                message = e.Message;
                return(Result.Failed);
            }
        }
Esempio n. 17
0
        /// <summary>
        /// Implement this method as an external command for Revit.
        /// </summary>
        /// <param name="commandData">An object that is passed to the external application 
        /// which contains data related to the command, 
        /// such as the application object and active view.</param>
        /// <param name="message">A message that can be set by the external application 
        /// which will be displayed if a failure or cancellation is returned by 
        /// the external command.</param>
        /// <param name="elements">A set of elements to which the external application 
        /// can add elements that are to be highlighted in case of failure or cancellation.</param>
        /// <returns>Return the status of the external command. 
        /// A result of Succeeded means that the API external method functioned as expected. 
        /// Cancelled can be used to signify that the user cancelled the external operation 
        /// at some point. Failure should be returned if the application is unable to proceed with 
        /// the operation.</returns>
        public Autodesk.Revit.UI.Result Execute(ExternalCommandData commandData,
        ref string message, Autodesk.Revit.DB.ElementSet elements)
        {
            try
            {
                m_app = commandData.Application;
                m_doc = commandData.Application.ActiveUIDocument.Document;
                if (null == m_doc)
                {
                    message = "There is no active document.";
                    return Autodesk.Revit.UI.Result.Failed;
                }

                if (!m_doc.IsFamilyDocument)
                {
                    message = "Current document is not a family document.";
                    return Autodesk.Revit.UI.Result.Failed;
                }

                // Get the view where the dwg file will be imported
                View view = GetView();
                if (null == view)
                {
                    message = "Opened wrong template file, please use the provided family template file.";
                    return Autodesk.Revit.UI.Result.Failed;
                }

                // The dwg file which will be imported
                string AssemblyDirectory = Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location);
                string DWGFile = "Desk.dwg";
                string DWGFullPath = Path.Combine(AssemblyDirectory, DWGFile);

                Transaction transaction = new Transaction(m_doc, "DWGFamilyCreation");
                transaction.Start();
                // Import the dwg file into current family document
                DWGImportOptions options = new DWGImportOptions();
                options.Placement = Autodesk.Revit.DB.ImportPlacement.Origin;
                options.OrientToView = true;
                ElementId elementId = null;
                m_doc.Import(DWGFullPath, options, view, out elementId);

                // Add type parameters to the family
                AddParameters(DWGFile);
                transaction.Commit();
            }
            catch (Exception ex)
            {
                message = ex.ToString();
                return Autodesk.Revit.UI.Result.Failed;
            }

            return Autodesk.Revit.UI.Result.Succeeded;
        }
        private void ImportAutoCADFile(int id)
        {
            if (uidoc.Document != null)
            {
                preCurveElementIds.Clear();
                FilteredElementCollector preElementDocFilter = new FilteredElementCollector(doc);
                if (preElementDocFilter != null)
                {
                    FilteredElementIdIterator preElementsIdsIterator = preElementDocFilter.OfClass(typeof(CurveElement)).GetElementIdIterator();
                    while (preElementsIdsIterator.MoveNext())
                    {
                        preCurveElementIds.Add(preElementsIdsIterator.Current);
                    }
                }

                preTextNotesIds.Clear();
                FilteredElementCollector preTextNoteDocFilter = new FilteredElementCollector(doc);
                if (preTextNoteDocFilter != null)
                {
                    FilteredElementIdIterator preElementsIdsIterator = preTextNoteDocFilter.OfClass(typeof(TextNote)).GetElementIdIterator();
                    while (preElementsIdsIterator.MoveNext())
                    {
                        preTextNotesIds.Add(preElementsIdsIterator.Current);
                    }
                }

                preTextNoteTypesIds.Clear();
                FilteredElementCollector preTextNoteTypeDocFilter = new FilteredElementCollector(doc);
                if (preTextNoteTypeDocFilter != null)
                {
                    FilteredElementIdIterator preElementsIdsIterator = preTextNoteTypeDocFilter.OfClass(typeof(TextNoteType)).GetElementIdIterator();
                    while (preElementsIdsIterator.MoveNext())
                    {
                        preTextNoteTypesIds.Add(preElementsIdsIterator.Current);

                        TextNoteType preTextNodeType = doc.GetElement(preElementsIdsIterator.Current) as TextNoteType;
                        if (preTextNodeType != null)
                        {
                            this.revitTextNoteTypesDict.Add(preTextNodeType.Name, preTextNodeType);
                        }
                    }
                }

                Category preLinesStyles = doc.Settings.Categories.get_Item(BuiltInCategory.OST_Lines);
                foreach (Category preLineCategory in preLinesStyles.SubCategories)
                {
                    preLineCategoriesIds.Add(preLineCategory.Id);
                    this.revitCategoriesDict.Add(preLineCategory.Name, preLineCategory);
                }


                preGraphycStyleIds.Clear();
                FilteredElementCollector preGraphycsStyleDocFilter = new FilteredElementCollector(doc);
                if (preGraphycsStyleDocFilter != null)
                {
                    FilteredElementIdIterator preElementsIdsIterator = preGraphycsStyleDocFilter.OfClass(typeof(GraphicsStyle)).GetElementIdIterator();
                    while (preElementsIdsIterator.MoveNext())
                    {
                        GraphicsStyle preGraphicsStyle = doc.GetElement(preElementsIdsIterator.Current) as GraphicsStyle;
                        if (preGraphicsStyle != null)
                        {
                            if (preLineCategoriesIds.Contains(preGraphicsStyle.GraphicsStyleCategory.Id))
                            {
                                preGraphycStyleIds.Add(preElementsIdsIterator.Current);

                                revitLineStylesDict.Add(preGraphicsStyle.Name, preGraphicsStyle);
                            }
                        }
                    }
                }

                #region
                deleteImportInstances();
                DWGImportOptions importOptions = new DWGImportOptions();
                importOptions.OrientToView = true;
                importOptions.Placement    = ImportPlacement.Origin;
                doc.Import(fileName, importOptions, importView, out importInstanceId);
                if (importInstanceId != null)
                {
                    explodeImportInstance();
                }
                uidoc.RefreshActiveView();


                curCurveElementIds.Clear();
                FilteredElementCollector curElementDocFilter = new FilteredElementCollector(doc);
                if (curElementDocFilter != null)
                {
                    FilteredElementIdIterator curElementsIdsIterator = curElementDocFilter.OfClass(typeof(CurveElement)).GetElementIdIterator();
                    while (curElementsIdsIterator.MoveNext())
                    {
                        curCurveElementIds.Add(curElementsIdsIterator.Current);
                    }
                }

                curTextNotesIds.Clear();
                FilteredElementCollector curDocFilter = new FilteredElementCollector(doc);
                if (curDocFilter != null)
                {
                    FilteredElementIdIterator curElementsIdsIterator = curDocFilter.OfClass(typeof(TextNote)).GetElementIdIterator();
                    while (curElementsIdsIterator.MoveNext())
                    {
                        curTextNotesIds.Add(curElementsIdsIterator.Current);
                    }
                }

                curTextNoteTypesIds.Clear();
                FilteredElementCollector curTextNoteTypeDocFilter = new FilteredElementCollector(doc);
                if (curTextNoteTypeDocFilter != null)
                {
                    FilteredElementIdIterator curElementsIdsIterator = curTextNoteTypeDocFilter.OfClass(typeof(TextNoteType)).GetElementIdIterator();
                    while (curElementsIdsIterator.MoveNext())
                    {
                        curTextNoteTypesIds.Add(curElementsIdsIterator.Current);
                    }
                }

                Category curLinesStyles = doc.Settings.Categories.get_Item(BuiltInCategory.OST_Lines);
                foreach (Category curLineCategory in curLinesStyles.SubCategories)
                {
                    curLineCategoriesIds.Add(curLineCategory.Id);
                }


                curGraphycStyleIds.Clear();
                FilteredElementCollector curGraphycsStyleDocFilter = new FilteredElementCollector(doc);
                if (curGraphycsStyleDocFilter != null)
                {
                    FilteredElementIdIterator curElementsIdsIterator = curGraphycsStyleDocFilter.OfClass(typeof(GraphicsStyle)).GetElementIdIterator();
                    while (curElementsIdsIterator.MoveNext())
                    {
                        GraphicsStyle curGraphicsStyle = doc.GetElement(curElementsIdsIterator.Current) as GraphicsStyle;
                        if (curGraphicsStyle != null)
                        {
                            if (curLineCategoriesIds.Contains(curGraphicsStyle.GraphicsStyleCategory.Id))
                            {
                                curGraphycStyleIds.Add(curElementsIdsIterator.Current);
                            }
                        }
                    }
                }
                #endregion

                difCurveElementIds.Clear();
                difCurveElementIds.UnionWith(curCurveElementIds);
                difCurveElementIds.ExceptWith(preCurveElementIds);

                difTextNotesIds.Clear();
                difTextNotesIds.UnionWith(curTextNotesIds);
                difTextNotesIds.ExceptWith(preTextNotesIds);

                difTextNoteTypesIds.Clear();
                difTextNoteTypesIds.UnionWith(curTextNoteTypesIds);
                difTextNoteTypesIds.ExceptWith(preTextNoteTypesIds);

                difLineCategoriesIds.Clear();
                difLineCategoriesIds.UnionWith(curLineCategoriesIds);
                difLineCategoriesIds.ExceptWith(preLineCategoriesIds);

                difGraphycStyleIds.Clear();
                difGraphycStyleIds.UnionWith(curGraphycStyleIds);
                difGraphycStyleIds.ExceptWith(preGraphycStyleIds);


                foreach (Category curLineCategory in curLinesStyles.SubCategories)
                {
                    if (difLineCategoriesIds.Contains(curLineCategory.Id))
                    {
                        Color curColor = curLineCategory.LineColor;
                        Tuple <byte, byte, byte> curColorTuple = new Tuple <byte, byte, byte>(curColor.Red, curColor.Green, curColor.Blue);

                        if (autocadColorLineStylesDict.ContainsKey(curColorTuple))
                        {
                            autocadColorLineStylesDict[curColorTuple].Add(curLineCategory);
                        }
                        else
                        {
                            List <Category> norList = new List <Category>();
                            norList.Add(curLineCategory);
                            autocadColorLineStylesDict.Add(curColorTuple, norList);
                        }
                    }
                }

                #region
                Autodesk.Revit.DB.Options geoOptions = uiapp.Application.Create.NewGeometryOptions();
                geoOptions.ComputeReferences = true;
                FilteredElementCollector curElementsDocFilter = new FilteredElementCollector(doc);
                if (curElementsDocFilter != null)
                {
                    FilteredElementIdIterator curElementsIdsIterator = curElementsDocFilter.WhereElementIsNotElementType().GetElementIdIterator();
                    while (curElementsIdsIterator.MoveNext())
                    {
                        ElementId curElementId = curElementsIdsIterator.Current;
                        if (curElementId != null)
                        {
                            Element curElement = doc.GetElement(curElementId);
                            if (curElement != null)
                            {
                                GeometryElement curGeometryElement = curElement.get_Geometry(geoOptions);
                                if (curGeometryElement != null)
                                {
                                    foreach (GeometryObject curGeometryObject in curGeometryElement)
                                    {
                                        ElementId curGraphicsStyleId = curGeometryObject.GraphicsStyleId;
                                        if (curGraphicsStyleId != null)
                                        {
                                            GraphicsStyle curGraphicsStyle = doc.GetElement(curGraphicsStyleId) as GraphicsStyle;
                                            if (curGraphicsStyle != null)
                                            {
                                                string curGraphicsStyleName = curGraphicsStyle.Name;

                                                Category curGraphicsStyleCategory = curGraphicsStyle.GraphicsStyleCategory;
                                                if (curGraphicsStyleCategory != null)
                                                {
                                                    string curGraphicsStyleCategoryName = curGraphicsStyleCategory.Name;

                                                    if (this.curGraphicsStylesNamesCount.ContainsKey(curGraphicsStyleCategoryName))
                                                    {
                                                        this.curGraphicsStylesNamesCount[curGraphicsStyleCategoryName]++;
                                                    }
                                                    else
                                                    {
                                                        this.curGraphicsStylesNamesCount.Add(curGraphicsStyleCategoryName, 1);
                                                    }
                                                }
                                            }
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
                #endregion


                CadDetailConverterOutputForm outputForm = new CadDetailConverterOutputForm(this);
                outputForm.ShowDialog();

                uiapp.Idling += uiapp_Idling;
            }
        }
Esempio n. 19
0
        public void ImportDWGsToDraftingViews()
        {
            //Get the current document
            Document curDoc  = this.Application.ActiveUIDocument.Document;
            int      counter = 0;

            //open form
            using (frmImportDWG curForm = new frmImportDWG()) {
                //show form
                curForm.ShowDialog();

                if (curForm.DialogResult == System.Windows.Forms.DialogResult.Cancel)
                {
                    //Result.Cancelled
                }
                else
                {
                    //get selected DWG files
                    List <string> drawingList = curForm.getSelectedDWGs();

                    using (Transaction curTrans = new Transaction(curDoc, "Import DWGs to Drafting View")) {
                        if (curTrans.Start() == TransactionStatus.Started)
                        {
                            //loop through DWGs, create drafting view and insert
                            foreach (string curDWG in drawingList)
                            {
                                //get view family type for drafting view
                                ElementId curVFT = getDraftingViewFamilyType(curDoc);

                                //create drafting view
                                View curView = ViewDrafting.Create(curDoc, curVFT);

                                //rename drafting view to DWG filename
                                string tmpName  = getFilenameFromPath(curDWG);
                                string viewName = tmpName.Substring(0, tmpName.Length - 4);

                                try {
                                    curView.Name = viewName;
                                } catch (Exception ex) {
                                    TaskDialog.Show("Error", "There is already a drafting view named " + viewName + " in this project file. The view will be named " + curView.Name + " instead.");
                                }

                                //set insert settings
                                DWGImportOptions curImportOptions = new DWGImportOptions();

                                switch (curForm.getColorSetting())
                                {
                                case "Invert":
                                    curImportOptions.ColorMode = ImportColorMode.Inverted;
                                    break;

                                case "Preserve":
                                    curImportOptions.ColorMode = ImportColorMode.Preserved;
                                    break;

                                default:
                                    curImportOptions.ColorMode = ImportColorMode.BlackAndWhite;
                                    break;
                                }

                                switch (curForm.getPosSetting())
                                {
                                case "Origin to Origin":
                                    curImportOptions.Placement = ImportPlacement.Origin;
                                    break;

                                case "Center to Center":
                                    curImportOptions.Placement = ImportPlacement.Centered;
                                    break;
                                }

                                //import / link current DWG to current view
                                ElementId curLinkID = null;

                                if (curForm.getInsertType() == "Link")
                                {
                                    curDoc.Link(curDWG, curImportOptions, curView, out curLinkID);
                                    counter = counter + 1;
                                }
                                else
                                {
                                    curDoc.Import(curDWG, curImportOptions, curView, out curLinkID);
                                    counter = counter + 1;
                                }
                            }
                        }

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

            //alert user
            TaskDialog.Show("Complete", "Inserted " + counter + " DWG files.");
        }
Esempio n. 20
0
      Stream(ArrayList data, DWGImportOptions dwgImpOptions)
      {
         data.Add(new Snoop.Data.ClassSeparator(typeof(DWGImportOptions)));

         // No data at this level yet.
      }
Esempio n. 21
0
        /// <summary>
        /// Collect the parameters and export
        /// </summary>
        /// <returns></returns>
        public override bool Import()
        {
            bool imported = false;

            //parameter: DWGImportOptions
            DWGImportOptions dwgImportOption = new DWGImportOptions();
            dwgImportOption.ColorMode = m_importColorMode;
            dwgImportOption.CustomScale = m_importCustomScale;
            dwgImportOption.OrientToView = m_importOrientToView;
            dwgImportOption.Placement = m_importPlacement;
            dwgImportOption.ThisViewOnly = m_importThisViewOnly;
            View view = null;
            if (!m_importThisViewOnly)
            {
                view = m_importView;
            }
            else
            {
                view = m_activeDoc.ActiveView;
            }
            dwgImportOption.Unit = m_importUnit;
            dwgImportOption.VisibleLayersOnly = m_importVisibleLayersOnly;

            //parameter: ElementId
            ElementId elementId = null;

            //Import
            Transaction t = new Transaction(m_activeDoc);
            t.SetName("Import");
            t.Start();
            imported = m_activeDoc.Import(m_importFileFullName, dwgImportOption, view, out elementId);
            t.Commit();

            return imported;
        }
Esempio n. 22
0
        public View ExportDWG(Document document, View view, out string file)
        {
            bool             exported   = false;
            ElementId        outid      = ElementId.InvalidElementId;
            DWGExportOptions dwgOptions = new DWGExportOptions();

            dwgOptions.FileVersion    = ACADVersion.R2007;
            dwgOptions.ExportOfSolids = SolidGeometry.Polymesh;
            View v = null;
            ICollection <ElementId> views = new List <ElementId>();

            views.Add(view.Id);
            var pathfile = SettingFreeze.Instance.GetFolderPath();

            exported = document.Export(pathfile, "Forzen view", views, dwgOptions);
            file     = Path.Combine(pathfile, "Forzen view" + ".dwg");
            if (exported)
            {
                TaskDialog taskDialog = new TaskDialog("Freeze View");
                taskDialog.Id                = "Freeze";
                taskDialog.Title             = "Freeze Drawing";
                taskDialog.TitleAutoPrefix   = true;
                taskDialog.MainIcon          = TaskDialogIcon.TaskDialogIconInformation;
                taskDialog.AllowCancellation = true;
                taskDialog.MainInstruction   = ("Select View Type :");
                taskDialog.AddCommandLink((TaskDialogCommandLinkId)1001, "Drafting View");
                taskDialog.AddCommandLink((TaskDialogCommandLinkId)1002, "Legend");
                taskDialog.CommonButtons = TaskDialogCommonButtons.Cancel;
                taskDialog.DefaultButton = ((TaskDialogResult)2);
                TaskDialogResult taskDialogResult = taskDialog.Show();
                var dwgimport = new DWGImportOptions();
                dwgimport.ColorMode = ImportColorMode.BlackAndWhite;
                if (taskDialogResult == TaskDialogResult.CommandLink2)
                {
                    v = GetLegend(document);
                }
                else if (taskDialogResult == TaskDialogResult.CommandLink1)
                {
                    v = CreateDrafting(document);
                }
                if (v != null)
                {
                    document.Import(file, dwgimport, v, out outid);
                }
                string strPost  = "(Forzen)";
                string newname  = this.ReplaceForbiddenSigns(doc.ActiveView.Name);
                string tempName = newname;
                if (v != null)
                {
                    int j = 1;
                    for (; ;)
                    {
                        try
                        {
                            v.Name = newname + strPost;
                            break;
                        }
                        catch
                        {
                            bool flag2 = j > 10;
                            if (flag2)
                            {
                                try
                                {
                                    v.Name += strPost;
                                }
                                catch
                                {
                                }
                                break;
                            }
                            newname = tempName + "-" + j.ToString();
                            j++;
                        }
                    }
                }
            }
            return(v);
        }
Esempio n. 23
0
        public void ImportDwg()
        {
            // get input file of type DWG
             System.Windows.Forms.OpenFileDialog dbox = new System.Windows.Forms.OpenFileDialog();
             dbox.CheckFileExists = true;
             dbox.Multiselect = false;
             dbox.AddExtension = true;
             dbox.DefaultExt = "dwg";
             dbox.Filter = "DWG Files (*.dwg)|*.dwg";
             dbox.Title = "DWG file to import";

             if (dbox.ShowDialog() == DialogResult.OK)
             {
            DWGImportOptions opts = new DWGImportOptions();
            opts.Placement = ImportPlacement.Origin;

            ElementId newElementId;
            m_revitApp.ActiveUIDocument.Document.Import(dbox.FileName, opts, m_revitApp.ActiveUIDocument.ActiveView, out newElementId);
             }
        }
Esempio n. 24
0
        public void LinkDWGsFromCSV()
        {
            //set the current document
            Document curDoc  = this.Application.ActiveUIDocument.Document;
            int      counter = 0;

            //open form
            using (frmSelectFiles curForm = new frmSelectFiles()) {
                //show form
                curForm.ShowDialog();

                if (curForm.DialogResult == System.Windows.Forms.DialogResult.Cancel)
                {
                    //Result.Cancelled
                    curForm.Close();
                }
                else
                {
                    //close form
                    curForm.Close();

                    //set CSV file
                    string CSVFile = curForm.getCSVFile();

                    //set import options
                    DWGImportOptions curOptions = new DWGImportOptions();
                    curOptions.ThisViewOnly = false;
                    curOptions.ColorMode    = ImportColorMode.BlackAndWhite;
                    curOptions.Placement    = ImportPlacement.Origin;
                    curOptions.Unit         = ImportUnit.Default;

                    //set current link ID
                    ElementId curLinkID = null;

                    //read CSV file and create sheet based on info
                    IList <structDWG> fileList = default(IList <structDWG>);
                    fileList = ReadCSV(CSVFile, true);

                    using (Transaction t = new Transaction(curDoc, "Link - Import DWGs")) {
                        if (t.Start() == TransactionStatus.Started)
                        {
                            //loop through DWG files and insert at correct level
                            foreach (structDWG curDWG in fileList)
                            {
                                //get level
                                View curView = getViewByName(curDWG.linkView, curDoc);

                                //check if file exists
                                string curFile = curDWG.fileName;
                                if (File.Exists(curFile) == true)
                                {
                                    //check if link or insert
                                    if (curForm.GetLinkInsert() == "link")
                                    {
                                        //insert DWG to specified level
                                        try {
                                            if (curDoc.Link(curFile, curOptions, curView, out curLinkID) == true)
                                            {
                                                Debug.Print("Created link for " + curDWG.fileName);
                                                counter = counter + 1;
                                            }
                                        } catch (Exception ex) {
                                            TaskDialog.Show("Error", "Could not create link for file " + curDWG.fileName + ".");
                                        }
                                    }
                                    else
                                    {
                                        //insert DWG to specified level
                                        try {
                                            if (curDoc.Import(curFile, curOptions, curView, out curLinkID) == true)
                                            {
                                                Debug.Print("Imported " + curDWG.fileName);
                                                counter = counter + 1;
                                            }
                                        } catch (Exception ex) {
                                            TaskDialog.Show("Error", "Could not import file " + curDWG.fileName);
                                        }
                                    }
                                }
                                else
                                {
                                    //alert user file cannot be found
                                    TaskDialog.Show("Alert", "Cannot find file - " + curFile);
                                }
                            }
                        }

                        //commit changes
                        t.Commit();
                    }

                    //alert user
                    if (curForm.GetLinkInsert() == "import")
                    {
                        TaskDialog.Show("Import DWGs", "Imported " + counter + "DWG files.");
                    }
                    else
                    {
                        //alert user
                        TaskDialog.Show("Link DWG from CSV", "Linked " + counter + " DWG files.");
                    }
                }
            }
        }