Exemplo n.º 1
0
        private void moveLinkedFiles(Document doc)
        {
            FilteredElementCollector collector = new FilteredElementCollector(doc);

            collector
            .OfCategory(BuiltInCategory.OST_RvtLinks)
            .OfClass(typeof(RevitLinkInstance));

            WorksetTable worksetTable = doc.GetWorksetTable();

            FilteredWorksetCollector coll = new FilteredWorksetCollector(doc);

            //StringBuilder worksetNames = new StringBuilder();
            //foreach (Workset workset in coll)
            //{
            //    worksetNames.AppendFormat("{0}: {1}\n", workset.Name, workset.Kind);
            //}
            //TaskDialog.Show("Worksets", worksetNames.ToString());

            foreach (Element ele in collector)
            {
                string    searchString = ele.Name;
                Match     result       = Regex.Match(searchString, @"^.*?(?=_)");
                Parameter wsparam      = ele.get_Parameter(BuiltInParameter.ELEM_PARTITION_PARAM);
                //Workset matchingWorkset = null;
                foreach (Workset workset in coll)
                {
                    string worksetName = workset.Name;
                    Match  result2     = Regex.Match(worksetName, @"^.*?(?=\s)");
                    if (result.ToString() == result2.ToString())
                    {
                        using (Transaction tx = new Transaction(doc))
                        {
                            tx.Start("Change workset id");
                            wsparam.Set(workset.Id.IntegerValue);
                            tx.Commit();
                        }
                    }
                }
            }
        }
Exemplo n.º 2
0
        /// <summary>
        /// Publishes Workset Open Data to database for onOpened/onSynched events.
        /// </summary>
        /// <param name="doc">Revit Document.</param>
        /// <param name="filePath">Revit Document central file path.</param>
        /// <param name="state">State of the Revit model.</param>
        public void PublishData(Document doc, string filePath, WorksetMonitorState state)
        {
            try
            {
                var worksets = new FilteredWorksetCollector(doc)
                               .OfKind(WorksetKind.UserWorkset)
                               .ToWorksets();

                var opened = 0;
                var closed = 0;
                foreach (var w in worksets)
                {
                    if (w.IsOpen)
                    {
                        opened++;
                    }
                    else
                    {
                        closed++;
                    }
                }

                var worksetInfo = new WorksetEvent
                {
                    CentralPath = filePath.ToLower(),
                    User        = Environment.UserName.ToLower(),
                    Opened      = opened,
                    Closed      = closed
                };

                var route = state == WorksetMonitorState.onopened ? "onopened" : "onsynched";
                if (!ServerUtilities.Post(worksetInfo, "worksets/" + route, out WorksetEvent unused))
                {
                    Log.AppendLog(LogMessageType.ERROR, "Failed to publish Worksets Data: " + state + ".");
                }
            }
            catch (Exception ex)
            {
                Log.AppendLog(LogMessageType.EXCEPTION, ex.Message);
            }
        }
Exemplo n.º 3
0
        /***************************************************/
        /****              Public methods               ****/
        /***************************************************/

        public static IEnumerable <WorksetId> OpenWorksetIds(this Document document)
        {
            if (document == null)
            {
                return(null);
            }

            FilteredWorksetCollector filteredWorksetCollector = new FilteredWorksetCollector(document).OfKind(WorksetKind.UserWorkset);

            List <WorksetId> result = new List <WorksetId>();

            foreach (Workset workset in filteredWorksetCollector)
            {
                if (workset.IsOpen)
                {
                    result.Add(workset.Id);
                }
            }

            return(result);
        }
Exemplo n.º 4
0
        /// <summary>
        /// Retrieves the workset with the given name.
        /// </summary>
        /// <param name="name">A workset name</param>
        /// <returns name="workset">Returns a workset.  Returns null if workset does not exist.</returns>
        public static Workset GetByName(string name)
        {
            Workset foundWorkset = null;

            if (name != null)
            {
                //Get Revit Document object
                revitDoc doc = DocumentManager.Instance.CurrentDBDocument;
                FilteredWorksetCollector fwCollector = new FilteredWorksetCollector(doc);

                foreach (revitWorkset workset in fwCollector)
                {
                    if (workset.Name == name)
                    {
                        foundWorkset = new Workset(doc, workset);
                    }
                }
                fwCollector.Dispose();
            }
            return(foundWorkset);
        }
        private void GetWorksets()
        {
            try
            {
                if (sModelInfo.ModelDoc.IsWorkshared)
                {
                    var collector = new FilteredWorksetCollector(sModelInfo.ModelDoc);
                    var wsFilter  = new WorksetKindFilter(WorksetKind.UserWorkset);
                    var worksets  = collector.WherePasses(wsFilter).ToWorksets().ToList();
                    foreach (var ws in worksets)
                    {
                        var iInfo = new ItemInfo(ws, MapType.Workset);
                        if (!sourceItems.ContainsKey(iInfo.ItemId))
                        {
                            sourceItems.Add(iInfo.ItemId, iInfo);
                        }
                    }
                }

                if (rModelInfo.ModelDoc.IsWorkshared)
                {
                    var collector = new FilteredWorksetCollector(rModelInfo.ModelDoc);
                    var wsFilter  = new WorksetKindFilter(WorksetKind.UserWorkset);
                    var worksets  = collector.WherePasses(wsFilter).ToWorksets().ToList();
                    foreach (var ws in worksets)
                    {
                        var iInfo = new ItemInfo(ws, MapType.Workset);
                        if (!recipientItems.ContainsKey(iInfo.ItemId))
                        {
                            recipientItems.Add(iInfo.ItemId, iInfo);
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show("Failed to get worksets.\n" + ex.Message, "Get Worksets", MessageBoxButton.OK, MessageBoxImage.Warning);
            }
        }
Exemplo n.º 6
0
        public void Execute(UpdaterData data)
        {
            Document doc = data.GetDocument();

            foreach (ElementId addedElementId in data.GetAddedElementIds())
            {
                Element   elem    = doc.GetElement(addedElementId);
                Parameter wsparam = elem.get_Parameter(BuiltInParameter.ELEM_PARTITION_PARAM);

                //find all user's workset
                FilteredWorksetCollector worksets = new FilteredWorksetCollector(doc).OfKind(WorksetKind.UserWorkset);
                if (worksets != null)
                {
                    foreach (Workset ws in worksets)
                    {
                        if (ws.Name == "共享标高和轴网" || ws.Name == "Shared Levels and Grids")
                        {
                            wsparam.Set(ws.Id.IntegerValue);
                        }
                    }
                }
            }
        }
Exemplo n.º 7
0
        public Workset GetWorkset(Document doc)
        {
            IList <Workset> userWorksets = new FilteredWorksetCollector(doc)
                                           .OfKind(WorksetKind.UserWorkset)
                                           .ToWorksets();

            bool checkNotExists = WorksetTable.IsWorksetNameUnique(doc, WorksetName);

            if (!checkNotExists)
            {
                Workset wset = new FilteredWorksetCollector(doc)
                               .OfKind(WorksetKind.UserWorkset)
                               .ToWorksets()
                               .Where(w => w.Name == WorksetName)
                               .First();
                return(wset);
            }
            else
            {
                Workset wset = Workset.Create(doc, WorksetName);
                return(wset);
            }
        }
Exemplo n.º 8
0
        private void MyWorksetExplorer(UIDocument UIdoc)
        {
            Document _doc = UIdoc.Document;

            // Выборка всех элементов в проекте
            IList <Element> allElements = new FilteredElementCollector(_doc).WhereElementIsNotElementType().ToElements();

            if (_doc.IsWorkshared)
            {
                WorksetTable           worksetTable = _doc.GetWorksetTable();
                IList <Workset>        worksets     = new FilteredWorksetCollector(_doc).OfKind(WorksetKind.UserWorkset).ToWorksets();
                List <List <Element> > allElsEls    = new List <List <Element> >(worksets.Count);
                foreach (Workset ws in worksets)
                {
                    allElsEls.Add(new List <Element>());
                }

                foreach (Element element in allElements)
                {
                    Workset workset = worksetTable.GetWorkset(element.WorksetId); // Get's the Workset Table of the document. Then return the workset from the input WorksetId
                    if (element.Category != null &&
                        (element.Category.Id.IntegerValue != (int)BuiltInCategory.OST_Grids &&
                         element.Category.Id.IntegerValue != (int)BuiltInCategory.OST_Levels &&
                         element.Category.Id.IntegerValue != (int)BuiltInCategory.OST_PreviewLegendComponents))
                    {
                        Parameter param = element.get_Parameter(BuiltInParameter.ELEM_PARTITION_PARAM);
                        if (param != null && !param.IsReadOnly)
                        {
                            bool flag  = false;
                            int  index = -1;
                            foreach (Workset ws in worksets)
                            {
                                ++index;
                                if (Equals(ws.Id, workset.Id))
                                {
                                    flag = true;
                                    break;
                                }
                            }
                            if (flag)
                            {
                                if (index != -1)
                                {
                                    allElsEls[index].Add(element);
                                }
                            }
                        }
                    }
                }


                var infoWorksetForm = new PRSPKT_Apps.ElementsOnWorkset.WorksetExplorerForm(allElsEls, _doc, ((IEnumerable <Workset>)worksets).ToArray());
                if (DialogResult.OK == infoWorksetForm.ShowDialog())
                {
                    List <Element> selectedElements = infoWorksetForm.GetSelectedElements();
                    UIdoc.Selection.SetElementIds(selectedElements.Select(q => q.Id).ToList());
                }
            }
            else
            {
                TaskDialog.Show("Ошибка", "Проект не переведён в режим совместной работы");
            }
        }
Exemplo n.º 9
0
        public static ViewPlan CreateWorksetFloorPlan(Document doc, ItemInfo itemInfo, ViewFamilyType viewPlanFamilyType, Level planLevel, bool overwrite)
        {
            ViewPlan viewPlan = null;
            string   viewName = planLevel.Name + " - " + itemInfo.ItemName;

            using (TransactionGroup tg = new TransactionGroup(doc))
            {
                tg.Start("Create Floor Plan");
                try
                {
                    FilteredElementCollector collector = new FilteredElementCollector(doc);
                    List <ViewPlan>          viewPlans = collector.OfClass(typeof(ViewPlan)).ToElements().Cast <ViewPlan>().ToList();
                    var views = from view in viewPlans where view.Name == viewName select view;
                    if (views.Count() > 0)
                    {
                        if (overwrite)
                        {
                            viewPlan = views.First();
                        }
                        else
                        {
                            return(viewPlan);
                        }
                    }

                    if (null == viewPlan)
                    {
                        using (Transaction trans = new Transaction(doc))
                        {
                            trans.Start("Create Plan View");
                            try
                            {
                                viewPlan      = ViewPlan.Create(doc, viewPlanFamilyType.Id, planLevel.Id);
                                viewPlan.Name = viewName;
                                trans.Commit();
                            }
                            catch (Exception ex)
                            {
                                trans.RollBack();
                                MessageBox.Show("Failed to create plan view.\n" + ex.Message, "Create Plan View", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                            }
                        }
                    }


                    using (Transaction trans = new Transaction(doc))
                    {
                        trans.Start("Set Visibility");
                        try
                        {
                            FilteredWorksetCollector worksetCollector = new FilteredWorksetCollector(doc);
                            IList <Workset>          worksetList      = worksetCollector.ToWorksets();
                            var worksets = from workset in worksetList where workset.Kind == WorksetKind.UserWorkset select workset;
                            foreach (Workset ws in worksets)
                            {
                                if (ws.Kind == WorksetKind.UserWorkset)
                                {
                                    if (ws.Id.IntegerValue == itemInfo.ItemId)
                                    {
                                        viewPlan.SetWorksetVisibility(ws.Id, WorksetVisibility.Visible);
                                    }
                                    else
                                    {
                                        viewPlan.SetWorksetVisibility(ws.Id, WorksetVisibility.Hidden);
                                    }
                                }
                            }
                            trans.Commit();
                        }
                        catch (Exception ex)
                        {
                            trans.RollBack();
                            MessageBox.Show("Failed to set visibility.\n" + ex.Message, "Set Visibility", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                        }
                    }
                }
                catch (Exception ex)
                {
                    tg.RollBack();
                    MessageBox.Show("Failed to create floor plans by worksets.\n" + ex.Message, "Create Floor Plans by Worksets", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                }
                tg.Assimilate();
            }
            return(viewPlan);
        }
Exemplo n.º 10
0
        public static View3D CreateWorkset3DView(Document doc, ItemInfo itemInfo, ViewFamilyType view3dFamilyType, bool overwrite)
        {
            View3D view3D = null;

            try
            {
                string viewName = "WS - 3D - " + itemInfo.ItemName;
                using (TransactionGroup tg = new TransactionGroup(doc))
                {
                    tg.Start("Create 3D View");
                    try
                    {
                        FilteredElementCollector collector = new FilteredElementCollector(doc);
                        List <View3D>            view3ds   = collector.OfClass(typeof(View3D)).ToElements().Cast <View3D>().ToList();
                        var views = from view in view3ds where view.Name == viewName select view;
                        if (views.Count() > 0)
                        {
                            if (overwrite)
                            {
                                view3D = views.First();
                            }
                            else
                            {
                                return(view3D);
                            }
                        }
                        if (null == view3D)
                        {
                            using (Transaction trans = new Transaction(doc))
                            {
                                trans.Start("Create Isometric");
                                try
                                {
                                    view3D      = View3D.CreateIsometric(doc, view3dFamilyType.Id);
                                    view3D.Name = viewName;
                                    if (view3D.CanModifyViewDiscipline())
                                    {
                                        view3D.Discipline = ViewDiscipline.Coordination;
                                    }
                                    trans.Commit();
                                }
                                catch (Exception ex)
                                {
                                    trans.RollBack();
                                    MessageBox.Show("Failed to create Isometric.\n" + ex.Message, "Create Isometric", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                                }
                            }
                        }

                        using (Transaction trans = new Transaction(doc))
                        {
                            trans.Start("Set Visibility");
                            try
                            {
                                FilteredWorksetCollector worksetCollector = new FilteredWorksetCollector(doc);
                                IList <Workset>          worksetList      = worksetCollector.ToWorksets();
                                var worksets = from workset in worksetList where workset.Kind == WorksetKind.UserWorkset select workset;
                                foreach (Workset ws in worksets)
                                {
                                    if (ws.Kind == WorksetKind.UserWorkset)
                                    {
                                        if (ws.Id.IntegerValue == itemInfo.ItemId)
                                        {
                                            view3D.SetWorksetVisibility(ws.Id, WorksetVisibility.Visible);
                                        }
                                        else
                                        {
                                            view3D.SetWorksetVisibility(ws.Id, WorksetVisibility.Hidden);
                                        }
                                    }
                                }
                                trans.Commit();
                            }
                            catch (Exception ex)
                            {
                                trans.RollBack();
                                MessageBox.Show("Failed to set visibility.\n" + ex.Message, "Set Visibility", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                            }
                        }

                        using (Transaction trans = new Transaction(doc))
                        {
                            trans.Start("Set SectionBox");
                            try
                            {
                                collector = new FilteredElementCollector(doc, view3D.Id);
                                List <Element> elements = collector.ToElements().ToList();
                                if (elements.Count > 0)
                                {
                                    BoundingBoxXYZ boundingBox = GetBoundingBox(elements);
                                    if (null != boundingBox)
                                    {
                                        view3D.SetSectionBox(boundingBox);
                                    }
                                }
                                trans.Commit();
                            }
                            catch (Exception ex)
                            {
                                trans.RollBack();
                                MessageBox.Show("Failed to set sectionbox.\n" + ex.Message, "Set Sectionbox", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                            }
                        }
                    }
                    catch (Exception ex)
                    {
                        MessageBox.Show("Failed to create 3d views by worksets.\n" + ex.Message, "Create 3D Views by Worksets", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                        tg.RollBack();
                    }
                    tg.Assimilate();
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show("Failed to create workset views.\n" + ex.Message, "Create Workset 3D View", MessageBoxButtons.OK, MessageBoxIcon.Warning);
            }
            return(view3D);
        }
Exemplo n.º 11
0
        public Result Execute(
            ExternalCommandData commandData,
            ref string message,
            ElementSet elements)
        {
            UIApplication uiapp = commandData.Application;
            Application   app   = uiapp.Application;

            int check             = 0;
            int sheetsNumber      = 0;
            int viewsNumber       = 0;
            int schedulesNumber   = 0;
            int furnitureElements = 0;



            using (var formOpen = new FormOpenFile())
            {
                formOpen.ShowDialog();

                string fileName = formOpen.filePath;

                ModelPath modelP = ModelPathUtils.ConvertUserVisiblePathToModelPath(fileName);


                if (formOpen.DialogResult == winForms.DialogResult.OK)
                {
                    OpenOptions optionDetach = new OpenOptions();

                    optionDetach.DetachFromCentralOption = DetachFromCentralOption.DetachAndPreserveWorksets;

                    optionDetach.Audit = true;

                    openDoc = app.OpenDocumentFile(modelP, optionDetach);

                    IEnumerable <ViewFamilyType> viewFamilyTypes = from elem in new FilteredElementCollector(openDoc).OfClass(typeof(ViewFamilyType))
                                                                   let type = elem as ViewFamilyType
                                                                              where type.ViewFamily == ViewFamily.ThreeDimensional
                                                                              select type;

                    IEnumerable <ElementId> sheetIds = from elem in new FilteredElementCollector(openDoc).OfCategory(BuiltInCategory.OST_Sheets) select elem.Id;

                    IEnumerable <ElementId> viewsIds = from elem in new FilteredElementCollector(openDoc).OfCategory(BuiltInCategory.OST_Views) where elem.Name != "Clarity_IFC _3D" select elem.Id;

#if REVIT2019
                    IEnumerable <ElementId> schedulesIds = from elem in new FilteredElementCollector(openDoc).OfCategory(BuiltInCategory.OST_Schedules) select elem.Id;
#elif REVIT2017
#endif

                    List <BuiltInCategory> builtInCats = new List <BuiltInCategory>();

                    builtInCats.Add(BuiltInCategory.OST_Furniture);
                    builtInCats.Add(BuiltInCategory.OST_Casework);
                    builtInCats.Add(BuiltInCategory.OST_Planting);
                    builtInCats.Add(BuiltInCategory.OST_Entourage);
                    builtInCats.Add(BuiltInCategory.OST_Railings);
                    builtInCats.Add(BuiltInCategory.OST_StairsRailing);

                    ElementMulticategoryFilter filter1 = new ElementMulticategoryFilter(builtInCats);


                    View3D view3d = null;

                    using (Transaction tran = new Transaction(openDoc))
                    {
                        tran.Start("Clarity Setup");

                        FilteredWorksetCollector worksetCollector = new FilteredWorksetCollector(openDoc).OfKind(WorksetKind.UserWorkset);

                        try
                        {
                            view3d = View3D.CreateIsometric(openDoc, viewFamilyTypes.First().Id);

                            view3d.Name = "Clarity_IFC _3D";

                            //uiapp.ActiveUIDocument.ActiveView = view3d;

                            foreach (Workset e in worksetCollector)
                            {
                                view3d.SetWorksetVisibility(e.Id, WorksetVisibility.Visible);
                            }
                        }
                        catch (Exception ex)
                        {
                            TaskDialog.Show("Error", "Name already taken" + "\n" + ex.Message);
                        }


                        try
                        {
                            sheetsNumber += sheetIds.Count();

                            if (sheetIds.Count() > 0)
                            {
                                openDoc.Delete(sheetIds.ToList());
                            }
                        }
                        catch (Exception ex)
                        {
                            TaskDialog.Show("Sheets Error", ex.Message);
                        }
                        try
                        {
                            viewsNumber += viewsIds.Count();

                            if (viewsIds.Count() > 0)
                            {
                                openDoc.Delete(viewsIds.ToList());
                            }
                        }
                        catch (Exception ex)
                        {
                            TaskDialog.Show("Views Error", ex.Message);
                        }
#if REVIT2019
                        try
                        {
                            if (schedulesIds.Count() > 0)
                            {
                                openDoc.Delete(schedulesIds.ToList());
                                schedulesNumber += schedulesIds.Count();
                            }
                        }
                        catch (Exception ex)
                        {
                            TaskDialog.Show("Schedule Error", ex.Message);
                        }
#elif REVIT2017
#endif

                        if (formOpen.cleanArchModel)
                        {
                            int furnitureError = 0;

                            ICollection <ElementId> toDelete = new FilteredElementCollector(openDoc).WherePasses(filter1).ToElementIds();


                            if (toDelete.Count() > 0)
                            {
                                string lastEx = "";
                                foreach (ElementId id in toDelete)
                                {
                                    try
                                    {
                                        openDoc.Delete(id);
                                        furnitureElements += 1;
                                    }
                                    catch (Exception ex)
                                    {
                                        lastEx = $"{ex.Message}\n";
                                    }
                                }
                                //Debug.WriteLine(lastEx.Message);
                                TaskDialog.Show("Error", $"{furnitureElements} elements deleted. {furnitureError} cannot be deleted. Errors:\n{lastEx}");
                            }
                        }

                        if (formOpen.purgeModel)
                        {
                            ICollection <ElementId> purgeableElements = null;

                            PurgeTool.GetPurgeableElements(openDoc, ref purgeableElements);
                            try
                            {
                                while (purgeableElements.Count > 0)
                                {
                                    //TaskDialog.Show("Purge Count", purgeableElements.Count().ToString());
                                    PurgeTool.GetPurgeableElements(openDoc, ref purgeableElements);
                                    openDoc.Delete(purgeableElements);
                                }
                            }
                            catch (Exception ex)
                            {
                                TaskDialog.Show("Purge Error", ex.Message);
                            }
                        }

                        tran.Commit();
                    }

                    SaveAsOptions            saveOpt = new SaveAsOptions();
                    WorksharingSaveAsOptions wos     = new WorksharingSaveAsOptions();
                    wos.SaveAsCentral = true;
                    saveOpt.Compact   = true;
                    saveOpt.SetWorksharingOptions(wos);
                    saveOpt.OverwriteExistingFile = true;

                    openDoc.SaveAs(modelP, saveOpt);


                    check += 1;
                }
                else
                {
                    TaskDialog.Show("Result", "Command aborted.");
                }

                if (check > 0)
                {
                    ICollection <ElementId> viewsId = new FilteredElementCollector(openDoc).OfCategory(BuiltInCategory.OST_Views).ToElementIds();

                    string viewsNames = "";

                    foreach (ElementId eid in viewsId)
                    {
                        viewsNames += openDoc.GetElement(eid).Name + Environment.NewLine;
                    }

                    TaskDialog.Show("Result", String.Format("Sheets deleted {0} \nViews deleted {1} \nSchedules deleted {2} \nViews in the model {3}",

                                                            sheetsNumber, viewsNumber, furnitureElements, viewsNames));
                }

                //PurgeMaterials(openDoc); too slooooooow
            }//close using

            return(Result.Succeeded);
        }
Exemplo n.º 12
0
        public Result Execute(ExternalCommandData commandData, ref string message, ElementSet elements)
        {
            Document doc = commandData.Application.ActiveUIDocument.Document;

            if (!doc.IsWorkshared)
            {
                message = "Файл не является файлом совместной работы";
                return(Result.Failed);;
            }

            //считываю список рабочих наборов
            string dllPath = System.Reflection.Assembly.GetExecutingAssembly().Location;
            string folder  = System.IO.Path.GetDirectoryName(dllPath);

            System.Windows.Forms.OpenFileDialog dialog = new System.Windows.Forms.OpenFileDialog();
            dialog.InitialDirectory = folder;
            dialog.Multiselect      = false;
            dialog.Filter           = "xml files (*.xml)|*.xml|All files (*.*)|*.*";
            if (dialog.ShowDialog() != System.Windows.Forms.DialogResult.OK)
            {
                return(Result.Cancelled);
            }
            string xmlFilePath = dialog.FileName;

            InfosStorage storage = new InfosStorage();

            System.Xml.Serialization.XmlSerializer serializer =
                new System.Xml.Serialization.XmlSerializer(typeof(InfosStorage));
            using (StreamReader r = new StreamReader(xmlFilePath))
            {
                storage = (InfosStorage)serializer.Deserialize(r);
            }
            if (storage.LinkedFilesPrefix == null)
            {
                storage.LinkedFilesPrefix = "#";
            }

            using (Transaction t = new Transaction(doc))
            {
                t.Start("Создание рабочих наборов");

                //назначаю рабочие наборы в случае, если указана категория
                foreach (WorksetByCategory wb in storage.worksetsByCategory)
                {
                    Workset wset = wb.GetWorkset(doc);
                    List <BuiltInCategory> cats = wb.revitCategories;
                    if (cats == null)
                    {
                        continue;
                    }
                    if (cats.Count == 0)
                    {
                        continue;
                    }

                    foreach (BuiltInCategory bic in cats)
                    {
                        List <Element> elems = new FilteredElementCollector(doc)
                                               .OfCategory(bic)
                                               .WhereElementIsNotElementType()
                                               .ToElements()
                                               .ToList();

                        foreach (Element elem in elems)
                        {
                            WorksetBy.SetWorkset(elem, wset);
                        }
                    }
                }

                //назначаю рабочие наборы по именам семейств
                List <FamilyInstance> famIns = new FilteredElementCollector(doc)
                                               .WhereElementIsNotElementType()
                                               .OfClass(typeof(FamilyInstance))
                                               .Cast <FamilyInstance>()
                                               .ToList();
                foreach (WorksetByFamily wb in storage.worksetsByFamily)
                {
                    Workset wset = wb.GetWorkset(doc);

                    List <string> families = wb.FamilyNames;
                    if (families == null)
                    {
                        continue;
                    }
                    if (families.Count == 0)
                    {
                        continue;
                    }



                    foreach (string familyName in families)
                    {
                        List <FamilyInstance> curFamIns = famIns
                                                          .Where(f => f.Symbol.FamilyName.StartsWith(familyName))
                                                          .ToList();

                        foreach (FamilyInstance fi in curFamIns)
                        {
                            WorksetBy.SetWorkset(fi, wset);
                        }
                    }
                }

                //назначаю рабочие наборы по именам типов
                List <Element> allElems = new FilteredElementCollector(doc)
                                          .WhereElementIsNotElementType()
                                          .Cast <Element>()
                                          .ToList();

                foreach (WorksetByType wb in storage.worksetsByType)
                {
                    Workset       wset      = wb.GetWorkset(doc);
                    List <string> typeNames = wb.TypeNames;
                    if (typeNames == null)
                    {
                        continue;
                    }
                    if (typeNames.Count == 0)
                    {
                        continue;
                    }

                    foreach (string typeName in typeNames)
                    {
                        foreach (Element elem in allElems)
                        {
                            ElementId typeId = elem.GetTypeId();
                            if (typeId == null || typeId == ElementId.InvalidElementId)
                            {
                                continue;
                            }
                            ElementType elemType = doc.GetElement(typeId) as ElementType;
                            if (elemType == null)
                            {
                                continue;
                            }

                            if (elemType.Name.StartsWith(typeName))
                            {
                                WorksetBy.SetWorkset(elem, wset);
                            }
                        }
                    }
                }

                //назначаю рабочие наборы по значению параметров
                foreach (WorksetByParameter wb in storage.worksetsByParameter)
                {
                    Workset wset       = wb.GetWorkset(doc);
                    string  paramName  = wb.ParameterName;
                    string  paramValue = wb.ParameterValue;

                    List <Element> elemsFilterByParam = allElems
                                                        .Where(e => e.LookupParameter(paramName).AsString().Equals(paramValue)).ToList();

                    foreach (Element elem in elemsFilterByParam)
                    {
                        WorksetBy.SetWorkset(elem, wset);
                    }
                }


                //назначаю рабочие наборы для связанных файлов
                List <RevitLinkInstance> links = new FilteredElementCollector(doc)
                                                 .OfClass(typeof(RevitLinkInstance))
                                                 .Cast <RevitLinkInstance>()
                                                 .ToList();

                foreach (RevitLinkInstance rli in links)
                {
                    RevitLinkType linkFileType = doc.GetElement(rli.GetTypeId()) as RevitLinkType;
                    if (linkFileType == null)
                    {
                        continue;
                    }
                    if (linkFileType.IsNestedLink)
                    {
                        continue;
                    }

                    string linkWorksetName1 = rli.Name.Split(':')[0];
                    string linkWorksetName2 = linkWorksetName1.Substring(0, linkWorksetName1.Length - 5);
                    string linkWorksetName  = storage.LinkedFilesPrefix + linkWorksetName2;
                    bool   checkExists      = WorksetTable.IsWorksetNameUnique(doc, linkWorksetName);
                    if (!checkExists)
                    {
                        continue;
                    }

                    Workset.Create(doc, linkWorksetName);

                    Workset linkWorkset = new FilteredWorksetCollector(doc)
                                          .OfKind(WorksetKind.UserWorkset)
                                          .ToWorksets()
                                          .Where(w => w.Name == linkWorksetName)
                                          .First();

                    WorksetBy.SetWorkset(rli, linkWorkset);
                    WorksetBy.SetWorkset(linkFileType, linkWorkset);
                }

                t.Commit();
            }

            List <string> emptyWorksetsNames = WorksetTool.GetEmptyWorksets(doc);

            if (emptyWorksetsNames.Count > 0)
            {
                string msg = "Обнаружены пустые рабочие наборы! Их можно удалить вручную:\n";
                foreach (string s in emptyWorksetsNames)
                {
                    msg += s + "\n";
                }
                TaskDialog.Show("Отчёт", msg);
            }

            return(Result.Succeeded);
        }
Exemplo n.º 13
0
        public Result Execute(ExternalCommandData commandData, ref string message, ElementSet elements)
        {
            UIDocument uidoc = commandData.Application.ActiveUIDocument;
            Document   doc   = uidoc.Document;

            View activeview = uidoc.ActiveView;

            FilteredWorksetCollector collector = new FilteredWorksetCollector(doc);

            collector.OfKind(WorksetKind.UserWorkset);

            List <Workset> list_visible   = new List <Workset>();
            List <Workset> list_invisible = new List <Workset>();

            foreach (Workset ws in collector)
            {
                if (activeview.IsWorksetVisible(ws.Id))
                {
                    list_visible.Add(ws);
                }
                else
                {
                    list_invisible.Add(ws);
                }
            }


            //window
            Window1 window = new Window1();

            window.listbox_visible.ItemsSource   = list_visible;
            window.listbox_invisible.ItemsSource = list_invisible;

            //selected
            List <Workset> seleted_visible   = new List <Workset>();
            List <Workset> seleted_invisible = new List <Workset>();

            if (window.ShowDialog() == true)
            {
                var objs1 = window.listbox_visible.SelectedItems;
                foreach (Object obj in objs1)
                {
                    seleted_visible.Add(obj as Workset);
                }

                var objs2 = window.listbox_invisible.SelectedItems;
                foreach (Object obj in objs2)
                {
                    seleted_invisible.Add(obj as Workset);
                }
            }

            //change visible
            using (Transaction transaction = new Transaction(doc))
            {
                transaction.Start("改变工作集可见性");

                foreach (Workset ws in seleted_visible)
                {
                    activeview.SetWorksetVisibility(ws.Id, WorksetVisibility.Hidden);
                }

                foreach (Workset ws in seleted_invisible)
                {
                    activeview.SetWorksetVisibility(ws.Id, WorksetVisibility.Visible);
                }

                transaction.Commit();
            }


            return(Result.Succeeded);
        }
Exemplo n.º 14
0
        /// <summary>
        /// Collects model metrics and returns a dictionary
        /// </summary>
        /// <param name="doc">The active document</param>
        /// <returns>Dictionary</returns>
        public Dictionary <string, object> CollectModelData(Document doc, Application app)
        {
            /*
             * the basic strategy is to use filtered element collectors to collect the relevant data.
             * some helper functions are defined in order to collect more complicated metrics that require the use of several element collectors.
             * examples: unused elements and redundant elements require helper functions
             */

            IList <FailureMessage> warnings  = doc.GetWarnings();
            IList <Element>        linkedRVT = new FilteredElementCollector(doc).OfCategory(BuiltInCategory.OST_RvtLinks).WhereElementIsNotElementType().ToList();
            Dictionary <string, IList <Element> > nonRvtLinks = RevitMethods.NonRVTLinkCollector(doc);
            IList <Element>        linkedCAD            = nonRvtLinks[RevitConstants.Strings.linkedCAD];
            IList <Element>        importedCAD          = nonRvtLinks[RevitConstants.Strings.importedCAD];
            IList <Element>        importedSKP          = nonRvtLinks[RevitConstants.Strings.importedSKP];
            IList <Element>        raster               = new FilteredElementCollector(doc).OfCategory(BuiltInCategory.OST_RasterImages).WhereElementIsNotElementType().ToList();
            IList <Element>        sheets               = new FilteredElementCollector(doc).OfCategory(BuiltInCategory.OST_Sheets).WhereElementIsNotElementType().ToList();
            IList <View>           views                = new FilteredElementCollector(doc).OfCategory(BuiltInCategory.OST_Views).Cast <View>().Where(v => !v.IsTemplate).ToList();
            IList <View>           unplacedViews        = RevitMethods.UnplacedViewCollector(doc, sheets);
            IList <Element>        modelGroups          = new FilteredElementCollector(doc).OfCategory(BuiltInCategory.OST_IOSModelGroups).WhereElementIsNotElementType().ToList();
            IList <Element>        detailGroups         = new FilteredElementCollector(doc).OfCategory(BuiltInCategory.OST_IOSDetailGroups).WhereElementIsNotElementType().ToList();
            IList <Family>         inPlaceFamilies      = new FilteredElementCollector(doc).OfClass(typeof(Family)).Cast <Family>().Where(f => f.IsInPlace).ToList();
            IList <Element>        designOptionElements = new FilteredElementCollector(doc).WhereElementIsNotElementType().Where(e => e.DesignOption != null).ToList();
            IList <Workset>        worksets             = new FilteredWorksetCollector(doc).OfKind(WorksetKind.UserWorkset).ToList();
            IList <Element>        rooms                = new FilteredElementCollector(doc).OfCategory(BuiltInCategory.OST_Rooms).WhereElementIsNotElementType().ToList();
            IList <SpatialElement> unplacedRooms        = new FilteredElementCollector(doc).OfCategory(BuiltInCategory.OST_Rooms).WhereElementIsNotElementType().Cast <SpatialElement>().Where(r => r.Area == 0 && r.Location == null).ToList();
            IList <SpatialElement> redundantRooms       = new FilteredElementCollector(doc).OfCategory(BuiltInCategory.OST_Rooms).WhereElementIsNotElementType().Cast <SpatialElement>().Where(r => r.Area == 0 && r.Location != null).ToList();
            IList <Element>        redundantElements    = RevitMethods.RedundantElementsCollector(warnings, doc);
            int unusedElements = unplacedViews.Count + unplacedRooms.Count + RevitMethods.UnusedFamiliesCollector(doc).Count;

            // collect model specific information
            (string writeDate, string writeTime) = UtilityMethods.FormatDateTime();
            (string modelPath, string modelName, string modelSize) = RevitMethods.GetModelInfo(doc);
            string versionBuild = app.VersionBuild;

            // save collected data in a dictionary
            Dictionary <string, object> modelMetrics = new Dictionary <string, object>()
            {
                { "Model Name", modelName },
                { "Model Path", modelPath },
                { "Model Size", modelSize },
                { "Warnings", warnings },
                { "Linked RVT Files", linkedRVT },
                { "Linked CAD Files", linkedCAD },
                { "Imported CAD Files", importedCAD },
                { "Imported SKP Files", importedSKP },
                { "Raster Images", raster },
                { "Sheets", sheets },
                { "Views", views },
                { "Unplaced Views", unplacedViews },
                { "Model Groups", modelGroups },
                { "Detail Groups", detailGroups },
                { "In-place Families", inPlaceFamilies },
                { "Elements in Design Options", designOptionElements },
                { "Worksets", worksets },
                { "Rooms", rooms },
                { "Unplaced Rooms", unplacedRooms },
                { "Redundant and Unenclosed Rooms", redundantRooms },
                { "Redundant Elements", redundantElements },
                { "Unused Elements", unusedElements },
                { "Write Date", writeDate },
                { "Write Time", writeTime },
                { "Version Build", versionBuild },
            };

            return(modelMetrics);
        }
Exemplo n.º 15
0
        public SetupCWSRequest(UIApplication uiApp, String text)
        {
            MainUI      uiForm = BARevitTools.Application.thisApp.newMainUi;
            RVTDocument doc    = uiApp.ActiveUIDocument.Document;

            //Make the transaction options
            TransactWithCentralOptions TWCOptions = new TransactWithCentralOptions();
            //Make the relinquish options
            RelinquishOptions relinquishOptions = new RelinquishOptions(true);
            //Make the synchronization options
            SynchronizeWithCentralOptions SWCOptions = new SynchronizeWithCentralOptions();

            SWCOptions.Compact = true;
            SWCOptions.SetRelinquishOptions(relinquishOptions);
            //Make the worksharing SaveAs options
            WorksharingSaveAsOptions worksharingSaveOptions = new WorksharingSaveAsOptions();

            worksharingSaveOptions.SaveAsCentral       = true;
            worksharingSaveOptions.OpenWorksetsDefault = SimpleWorksetConfiguration.AllWorksets;
            //Make the save options
            SaveOptions projectSaveOptions = new SaveOptions();

            projectSaveOptions.Compact = true;
            //Finally, make the SaveAs options
            SaveAsOptions projectSaveAsOptions = new SaveAsOptions();

            projectSaveAsOptions.Compact = true;
            projectSaveAsOptions.OverwriteExistingFile = true;
            projectSaveAsOptions.SetWorksharingOptions(worksharingSaveOptions);

            //The worksetsToAdd list will the names of the worksets to create
            List <string> worksetsToAdd = new List <string>();

            //Collect the names of the worksets from the defaults
            foreach (string item in uiForm.setupCWSDefaultListBox.Items)
            {
                worksetsToAdd.Add(item);
            }
            //Collect any names selected in the extended list
            foreach (string item in uiForm.setupCWSExtendedListBox.CheckedItems)
            {
                worksetsToAdd.Add(item);
            }
            //Collect the names of any user defined worksets
            foreach (DataGridViewRow row in uiForm.setupCWSUserDataGridView.Rows)
            {
                try
                {
                    if (row.Cells[0].Value.ToString() != "")
                    {
                        worksetsToAdd.Add(row.Cells[0].Value.ToString());
                    }
                }
                catch { continue; }
            }

            //Collect all worksets in the current project
            List <Workset> worksets     = new FilteredWorksetCollector(doc).Cast <Workset>().ToList();
            List <string>  worksetNames = new List <string>();

            //Cycle through the worksets in the project
            if (worksets.Count > 0)
            {
                foreach (Workset workset in worksets)
                {
                    //If Workset1 exists, rename it Arch
                    if (workset.Name == "Workset1")
                    {
                        try
                        {
                            WorksetTable.RenameWorkset(doc, workset.Id, "Arch");
                            worksetNames.Add("Arch");
                            break;
                        }
                        catch { continue; }
                    }
                    else
                    {
                        worksetNames.Add(workset.Name);
                    }
                }
            }

            //If the file has been saved and is workshared, continue
            if (doc.IsWorkshared && doc.PathName != "")
            {
                //Start a transaction
                Transaction t1 = new Transaction(doc, "CreateWorksets");
                t1.Start();
                //For each workset name in the list of worksets to add, continue
                foreach (string worksetName in worksetsToAdd)
                {
                    //If the list of existing worksets does not contain the workset to make, continue
                    if (!worksetNames.Contains(worksetName))
                    {
                        //Create the new workset
                        Workset.Create(doc, worksetName);
                    }
                }
                t1.Commit();

                try
                {
                    //Save the project with the save options, then synchronize
                    doc.Save(projectSaveOptions);
                    doc.SynchronizeWithCentral(TWCOptions, SWCOptions);
                }
                catch
                {
                    //Else, try using the SaveAs method, then synchronize
                    doc.SaveAs(doc.PathName, projectSaveAsOptions);
                    doc.SynchronizeWithCentral(TWCOptions, SWCOptions);
                }
            }

            //If the project has been saved and the document is not workshared, continue
            else if (!doc.IsWorkshared && doc.PathName != "")
            {
                //Make the document workshared and set the default worksets
                doc.EnableWorksharing("Shared Levels and Grids", "Arch");
                //Add the default worksets to the list of pre-existing worksets
                worksetNames.Add("Shared Levels and Grids");
                worksetNames.Add("Arch");

                //Start the transaction
                Transaction t1 = new Transaction(doc, "MakeWorksets");
                t1.Start();
                foreach (string worksetName in worksetsToAdd)
                {
                    //Create the workset if it does not exist in the list of pre-existing worksets
                    if (!worksetNames.Contains(worksetName))
                    {
                        Workset.Create(doc, worksetName);
                    }
                }
                t1.Commit();
                //Use the SaveAs method for saving the file, then synchronize
                doc.SaveAs(doc.PathName, projectSaveAsOptions);
                doc.SynchronizeWithCentral(TWCOptions, SWCOptions);
            }
            else
            {
                //If the project has not been saved, let the user know to save it first somewhere
                MessageBox.Show("Project file needs to be saved somewhere before it can be made a central model");
            }
        }