Exemple #1
0
        public void BeWorkset(string _wsName, ExternalCommandData commandData)
        {
            UIApplication _uiapp = commandData.Application;
            UIDocument    _uidoc = _uiapp.ActiveUIDocument;

            Autodesk.Revit.ApplicationServices.Application _app = _uiapp.Application;
            Autodesk.Revit.DB.Document _doc = _uidoc.Document;
            WorksetTable wst  = _doc.GetWorksetTable();
            WorksetId    wsID = FamilyUtils.WhatIsThisWorkSetIDByName(_wsName, _doc);

            if (wsID != null)
            {
                using (Transaction trans = new Transaction(_doc, "WillChangeWorkset")) {
                    trans.Start();
                    wst.SetActiveWorksetId(wsID);
                    trans.Commit();
                }
            }
            else
            {
                System.Windows.MessageBox.Show("Sorry but there is no workset "
                                               + _wsName + " to switch to.", "Smells So Bad It Has A Chain On It",
                                               System.Windows.MessageBoxButton.OK,
                                               System.Windows.MessageBoxImage.Exclamation);
            }
        }
Exemple #2
0
        private static Workset GetWorkSet(Document doc)
        {
            Workset workSet = null;

            if (doc.IsWorkshared)
            {
                string workSetName = "WorkSetName";
                if (WorksetTable.IsWorksetNameUnique(doc, workSetName))
                {
                    using (Transaction tran = new Transaction(doc, "[ToolSet] Create Work Set For ToolSet"))
                    {
                        tran.Start();
                        workSet = Workset.Create(doc, workSetName);
                        tran.Commit();
                    }
                }
                else
                {
                    IList <Workset> list = new FilteredWorksetCollector(doc).OfKind(WorksetKind.UserWorkset).ToWorksets();
                    foreach (var item in list)
                    {
                        if (item.Name.Contains(workSetName))
                        {
                            return(item);
                        }
                    }
                }
            }
            return(workSet);
        }
Exemple #3
0
        /// <summary>
        /// Determines whether a given name is already used in the document.
        /// </summary>
        /// <param name="name">A workset name</param>
        /// <returns name="bool">True if workset name is unique in the document, false if already used.</returns>
        public static bool IsWorksetNameUnique(string name)
        {
            //Get Revit Document object
            revitDoc doc = DocumentManager.Instance.CurrentDBDocument;

            return(WorksetTable.IsWorksetNameUnique(doc, name));
        }
Exemple #4
0
        public static Workset GetOrCreateWorkset(Document doc, string worksetName)
        {
            IList <Workset> userWorksets = new FilteredWorksetCollector(doc)
                                           .OfKind(WorksetKind.UserWorkset)
                                           .ToWorksets();

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

            if (!checkNotExists)
            {
                Debug.WriteLine("Workset exists: " + worksetName);
                Workset wset = new FilteredWorksetCollector(doc)
                               .OfKind(WorksetKind.UserWorkset)
                               .ToWorksets()
                               .Where(w => w.Name == worksetName)
                               .First();
                return(wset);
            }
            else
            {
                Debug.WriteLine("Create workset: " + worksetName);
                Workset wset = Workset.Create(doc, worksetName);
                return(wset);
            }
        }
Exemple #5
0
        /// <summary>
        /// 创建工作集
        /// </summary>
        /// <param name="doc">当前文档</param>
        /// <param name="worksetName">输入工作集名称</param>
        /// <returns>新的工作集</returns>
        public Workset CreateWorksets(Document doc, string worksetName)
        {
            Workset newWorksets = null;

            if (WorksetTable.IsWorksetNameUnique(doc, worksetName))
            {
                using (Transaction trans = new Transaction(doc, "创建工作集"))
                {
                    trans.Start();
                    newWorksets = Workset.Create(doc, worksetName);
                    trans.Commit();
                }
            }
            //判定是否有重名的工作集
            else
            {
                FilteredWorksetCollector worksetCollector = new FilteredWorksetCollector(doc);
                IList <Workset>          worksetsList     = worksetCollector.OfKind(WorksetKind.UserWorkset).ToWorksets();
                foreach (Workset workset in worksetsList)
                {
                    if (workset.Name.Contains(worksetName))
                    {
                        return(workset);
                    }
                }
            }
            return(newWorksets);
        }
        public static Workset GetActiveWorkset(Document doc)
        {
            WorksetTable table    = doc.GetWorksetTable();
            WorksetId    activeId = table.GetActiveWorksetId();
            Workset      workset  = table.GetWorkset(activeId);

            return(workset);
        }
Exemple #7
0
 public RevitManager(ExternalCommandData commandData)
 {
     uiApplication = commandData.Application;
     app           = uiApplication.Application;
     uiDoc         = uiApplication.ActiveUIDocument;
     doc           = uiDoc.Document;
     worksetTable  = doc.GetWorksetTable();
 }
        public ElementProps(Element el)
        {
            Document doc = el.Document;



            ID           = el.Id.IntegerValue;
            Name         = el.Name;
            ClassName    = el.GetType().ToString().Replace("Autodesk.Revit.DB.", string.Empty);
            CategoryName = (null != el.Category)
                    ? el.Category.Name
                    : ElementPropertiesWrapper.NullDescrip;
            LevelName = (ElementId.InvalidElementId == el.LevelId)
                ? ElementPropertiesWrapper.NullDescrip
                : doc.GetElement(el.LevelId).Name;
            IsWorkshared = doc.IsWorkshared;

            if (IsWorkshared)
            {
                WorksetTable wsTbl = doc.GetWorksetTable();
                WorksetName = (WorksetId.InvalidWorksetId != el.WorksetId)
                ? wsTbl.GetWorkset(el.WorksetId).Name
                : ElementPropertiesWrapper.NullDescrip;
            }
            else
            {
                WorksetName = ElementPropertiesWrapper.NullDescrip;
            }

            IsViewSpecific = el.ViewSpecific;
            if (IsViewSpecific)
            {
                OwnerViewId = el.OwnerViewId.IntegerValue;
            }
            else
            {
                OwnerViewId = null;
            }
            OwnerViewName = IsViewSpecific
                ? doc.GetElement(el.OwnerViewId).Name
                : string.Empty;

            if (null == el.DesignOption)
            {
                DesignOptionSet = DesignOptionName = string.Empty;
            }
            else
            {
                // Might need to parse this?..
                DesignOptionSet  = el.DesignOption.Name;
                DesignOptionName = el.DesignOption.Name;
            }

            PhaseName = (el.CreatedPhaseId == ElementId.InvalidElementId)
                ? ElementPropertiesWrapper.NullDescrip
                : doc.GetElement(el.CreatedPhaseId).Name;
        }
Exemple #9
0
        /***************************************************/
        /****              Public methods               ****/
        /***************************************************/

        public static WorksetId ActiveWorksetId(this Document document)
        {
            if (document == null)
            {
                return(null);
            }

            WorksetTable worksetTable = document.GetWorksetTable();

            return(worksetTable.GetActiveWorksetId());
        }
Exemple #10
0
        public static IDictionary ByName(
            string name,
            [DefaultArgument("true")] bool visible,
            [DefaultArgument("\"\"")] string alias
            )
        {
            //Get Revit Document object
            revitDoc doc = DocumentManager.Instance.CurrentDBDocument;

            Workset workset = null;
            bool    created = false;

            //Only create workset if it's name isn't an empty string
            if (name != null && name != "")
            {
                //Verify that each workset isn't already in the document
                //If the workset is unique, create it
                if (WorksetTable.IsWorksetNameUnique(doc, name))
                {
                    //If the alias is already in the document
                    if (alias != null && WorksetTable.IsWorksetNameUnique(doc, alias) == false)
                    {
                        workset = GetByName(alias);
                        Rename(workset, name);
                        created = true;
                    }
                    else
                    {
                        using (Autodesk.Revit.DB.Transaction trans = new Autodesk.Revit.DB.Transaction(doc))
                        {
                            trans.Start("Create Workset");

                            workset = new Workset(doc, revitWorkset.Create(doc, name));

                            trans.Commit();
                        }
                        SetDefaultVisibility(workset, visible);
                        created = true;
                    }
                }
                // If the workset is already in the document, retrieve the workset
                else
                {
                    workset = GetByName(name);
                    created = false;
                }
            }

            return(new Dictionary <string, object>
            {
                { "workset", workset },
                { "created", created }
            });
        }
Exemple #11
0
        public static List <string> GetUsedNames(Document CurrentDoc, List <string> SelectedWorksets)
        {
            List <string> usedNames = new List <string>();

            foreach (string s in SelectedWorksets)
            {
                if (!WorksetTable.IsWorksetNameUnique(CurrentDoc, s))
                {
                    usedNames.Add(s);
                }
            }
            return(usedNames);
        }
Exemple #12
0
        public ElementProps(Element el)
        {
            Document doc = el.Document;

            RevitFilePath = doc.PathName;
            
            IsBim360Model = doc.IsModelInCloud;
            ProjectNumber = doc.ProjectInformation.Number;
            ProjectName = doc.ProjectInformation.Name;
            FileVersion = doc.Application.VersionNumber;

            ID = el.Id.IntegerValue;
            Name = el.Name;
            ClassName = el.GetType().ToString().Replace("Autodesk.Revit.DB.", string.Empty);
            CategoryName = (null != el.Category)
                    ? el.Category.Name
                    : ElementPropertiesWrapper.NullDescrip;
            LevelName = (ElementId.InvalidElementId == el.LevelId)
                ? ElementPropertiesWrapper.NullDescrip
                : doc.GetElement(el.LevelId).Name;
            IsWorkshared = doc.IsWorkshared;

            if (IsWorkshared)
            {
                WorksetTable wsTbl = doc.GetWorksetTable();
                WorksetName = (WorksetId.InvalidWorksetId != el.WorksetId)
                ? wsTbl.GetWorkset(el.WorksetId).Name
                : ElementPropertiesWrapper.NullDescrip;
            }
            else { WorksetName = ElementPropertiesWrapper.NullDescrip; }

            IsViewSpecific = el.ViewSpecific;
            OwnerViewName = IsViewSpecific
                ? doc.GetElement(el.OwnerViewId).Name
                : string.Empty;

            if (null == el.DesignOption)
                DesignOptionSet = DesignOptionName = string.Empty;
            else
            {
                // Might need to parse this?..
                DesignOptionSet = el.DesignOption.Name;
                DesignOptionName = el.DesignOption.Name;
            }

            PhaseName = (el.CreatedPhaseId == ElementId.InvalidElementId)
                ? ElementPropertiesWrapper.NullDescrip
                : doc.GetElement(el.CreatedPhaseId).Name;

        }
 private void button1_Click(object sender, EventArgs e)
 {
     if (selectedWorksetNames.Count == 0)
     {
         TaskDialog.Show("Error", "No worksets selected.");
         return;
     }
     // Document doc = extCommandData.Application.ActiveUIDocument.Document;
     using (Transaction t = new Transaction(doc, "Making Worksets"))
     {
         try
         {
             t.Start();
             // Workset workset1 = new FilteredWorksetCollector(doc).OfKind(WorksetKind.UserWorkset).Where(w => w.Name == "Workset1").FirstOrDefault();
             // WorksetId workset1Id = workset1?.Id;
             for (int i = 0; i < selectedWorksetNames.Count; i++)
             {
                 if (WorksetTable.IsWorksetNameUnique(doc, selectedWorksetNames[i].ToString()))
                 {
                     /*
                      * if (i == 0 && workset1Id != null)
                      * {
                      *  WorksetTable.RenameWorkset(doc, workset1Id, selectedWorksetNames[i].ToString());
                      * }
                      * else
                      * {
                      *  Workset.Create(doc, selectedWorksetNames[i].ToString());
                      * }
                      */
                     Workset.Create(doc, selectedWorksetNames[i].ToString());
                 }
                 else
                 {
                     TaskDialog.Show("Error", $"Duplicate workset name already exists in project: {selectedWorksetNames[i]}");
                 }
             }
             t.Commit();
             TaskDialog.Show("Success", $"{selectedWorksetNames.Count} worksets created.");
         }
         catch (Exception error)
         {
             t.RollBack();
             TaskDialog.Show("Error", error.ToString());
         }
     }
     this.Close();
 }
 public static void ApplyWorksetModifications(Document doc, List <WorksetParameter> worksets, ref TransactionLog log)
 {
     using (Transaction t = new Transaction(doc))
     {
         if (t.Start("Add Worksets to Model.") == TransactionStatus.Started)
         {
             foreach (var w in worksets)
             {
                 if (w.IsModified)
                 {
                     if (w.IsExisting && w.Id >= 0)
                     {
                         if (WorksetTable.IsWorksetNameUnique(doc, w.Name))
                         {
                             WorksetTable.RenameWorkset(doc, new WorksetId(w.Id), w.Name);
                         }
                         var defaultVisibilitySettings = WorksetDefaultVisibilitySettings.GetWorksetDefaultVisibilitySettings(doc);
                         defaultVisibilitySettings.SetWorksetVisibility(new WorksetId(w.Id), w.VisibleInAllViews);
                         log.AddSuccess(w.ToString());
                     }
                     else
                     {
                         Workset newWorkset = null;
                         if (WorksetTable.IsWorksetNameUnique(doc, w.Name))
                         {
                             newWorkset = Workset.Create(doc, w.Name);
                         }
                         else
                         {
                             log.AddFailure(w.ToString());
                             continue;
                         }
                         if (newWorkset != null)
                         {
                             var defaultVisibilitySettings = WorksetDefaultVisibilitySettings.GetWorksetDefaultVisibilitySettings(doc);
                             defaultVisibilitySettings.SetWorksetVisibility(newWorkset.Id, w.VisibleInAllViews);
                             log.AddSuccess(w.ToString());
                         }
                     }
                 }
             }
             t.Commit();
         }
     }
 }
Exemple #15
0
        public Result Execute(ExternalCommandData commandData, ref string message, ElementSet elements)
        {
            UIApplication uiapp        = commandData.Application;
            UIDocument    uidoc        = uiapp.ActiveUIDocument;
            Document      doc          = uidoc.Document;
            WorksetTable  worksetTable = doc.GetWorksetTable();

            // Build hashmap out of all selected elements and store their filterable properties
            Selection selection = uidoc.Selection;

            allElements = selection.GetElementIds().Select(id =>
            {
                Element element = doc.GetElement(id);

                FilterableElement filterableElement;
                filterableElement.id       = id;
                filterableElement.category = element.Category.Name;
                filterableElement.family   = element.get_Parameter(BuiltInParameter.ELEM_FAMILY_PARAM).AsValueString();
                filterableElement.type     = element.get_Parameter(BuiltInParameter.ELEM_TYPE_PARAM).AsValueString();
                filterableElement.workset  = worksetTable.GetWorkset(element.WorksetId).Name;

                return(filterableElement);
            }).ToList();
            filteredElements = allElements;

            // Determine the values we can filter
            determineAvailableFilters();
            allFilters      = availableFilters;
            selectedFilters = availableFilters;

            // Show the form
            FilterForm   filterForm = new FilterForm(this, availableFilters);
            DialogResult result     = filterForm.ShowDialog();

            if (DialogResult.Cancel == result)
            {
                filteredElements = allElements;
            }

            // Select the filtered elements in Revit
            selection.SetElementIds(filteredElements.Select(filterableElement => filterableElement.id).ToList());

            return(Result.Succeeded);
        }
Exemple #16
0
        public static bool SetWorksetName(int WorksetId, string Name)
        {
            var doc = DocumentManager.Instance.CurrentDBDocument;

            if (doc.IsWorkshared)
            {
                try
                {
                    WorksetId id = null;
                    FilteredWorksetCollector worksets = new FilteredWorksetCollector(doc).OfKind(WorksetKind.UserWorkset);
                    foreach (Autodesk.Revit.DB.Workset w in worksets)
                    {
                        if (w.Id.IntegerValue == WorksetId)
                        {
                            id = w.Id;
                            break;
                        }
                    }
                    if (id != null)
                    {
                        using (Autodesk.Revit.DB.Transaction t = new Autodesk.Revit.DB.Transaction(doc, "Dynamo_SetProjectNumber"))
                        {
                            t.Start();
                            WorksetTable.RenameWorkset(doc, id, Name);
                            t.Commit();
                            return(true);
                        }
                    }
                    else
                    {
                        throw new Exception("Workset is not available in this document.");
                    }
                }
                catch (Exception ex)
                {
                    throw new Exception(ex.ToString());
                }
            }
            else
            {
                throw new Exception("The current file is not workshared.");
            }
        }
Exemple #17
0
        /// <summary>
        /// 创建工作集
        /// </summary>
        /// <param name="doc"></param>
        /// <returns></returns>
        public Workset CreateWorkset(Document doc)
        {
            Workset workset = null;

            if (doc.IsWorkshared)
            {
                string worksetName = "New Workset";
                if (WorksetTable.IsWorksetNameUnique(doc, worksetName))
                {
                    using (Transaction worksetTransaction = new Transaction(doc, "Set preview view id"))
                    {
                        worksetTransaction.Start();
                        workset = Workset.Create(doc, worksetName);
                        worksetTransaction.Commit();
                    }
                }
            }
            return(workset);
        }
Exemple #18
0
        private Workset CreateWorkset(Document document)
        {
            Workset newWorkset = null;

            // Worksets can only be created in a document with worksharing enabled
            if (document.IsWorkshared)
            {
                string worksetName  = "Workset4";
                string worksetName1 = "Workset5";
                string worksetName2 = "Workset6";
                // Workset name must not be in use by another workset
                if (WorksetTable.IsWorksetNameUnique(document, worksetName))
                {
                    using (Transaction worksetTransaction = new Transaction(document, "Set preview view id"))
                    {
                        worksetTransaction.Start();
                        newWorkset = Workset.Create(document, worksetName);
                        worksetTransaction.Commit();
                    }
                }
                if (WorksetTable.IsWorksetNameUnique(document, worksetName1))
                {
                    using (Transaction worksetTransaction = new Transaction(document, "Set preview view id"))
                    {
                        worksetTransaction.Start();
                        newWorkset = Workset.Create(document, worksetName1);
                        worksetTransaction.Commit();
                    }
                }
                if (WorksetTable.IsWorksetNameUnique(document, worksetName2))
                {
                    using (Transaction worksetTransaction = new Transaction(document, "Set preview view id"))
                    {
                        worksetTransaction.Start();
                        newWorkset = Workset.Create(document, worksetName2);
                        worksetTransaction.Commit();
                    }
                }
            }

            return(newWorkset);
        }
Exemple #19
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();
                        }
                    }
                }
            }
        }
Exemple #20
0
        public static IDictionary Rename(Workset workset, string name)
        {
            //Get Revit Document object
            revitDoc doc            = DocumentManager.Instance.CurrentDBDocument;
            Workset  renamedWorkset = null;
            bool     renamed        = false;

            if (name != null && workset != null)
            {
                //Verify that the existing workset is in the document.
                //If the workset is unique, create it
                if (WorksetTable.IsWorksetNameUnique(doc, workset.internalWorkset.Name) == false)
                {
                    // Verify that the new name doesn't already exist
                    if (WorksetTable.IsWorksetNameUnique(doc, name) == true)
                    {
                        //Only rename workset if it's name isn't an empty string
                        if (name != "")
                        {
                            using (Autodesk.Revit.DB.Transaction trans = new Autodesk.Revit.DB.Transaction(doc))
                            {
                                trans.Start("Rename Workset");

                                WorksetTable.RenameWorkset(doc, workset.internalId, name);
                                workset.internalName = workset.internalWorkset.Name;
                                renamedWorkset       = workset;
                                renamed = true;

                                trans.Commit();
                            }
                        }
                    }
                }
            }

            return(new Dictionary <string, object>
            {
                { "workset", renamedWorkset },
                { "renamed", renamed }
            });
        }
Exemple #21
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);
            }
        }
Exemple #22
0
        public Result Execute(
            ExternalCommandData commandData,
            ref string message,
            ElementSet elements)
        {
            UIDocument uidoc = commandData.Application.ActiveUIDocument;
            Document   doc   = uidoc.Document;

            // Access current selection
            ICollection <ElementId>    selected          = uidoc.Selection.GetElementIds();
            UserWorksetSelectionFilter userWorksetFilter = new UserWorksetSelectionFilter(doc);

            try
            {
                ElementId selectionId;

                selectionId = selected.FirstOrDefault(id => userWorksetFilter.IsUserWorksetElement(id));

                while (selectionId == null)
                {
                    Reference elRef = uidoc.Selection.PickObject(ObjectType.Element, userWorksetFilter, "Select an element");
                    selectionId = doc.GetElement(elRef).Id;
                }

                Element      element = doc.GetElement(selectionId);
                WorksetTable wsTable = doc.GetWorksetTable();
                Workset      workset = wsTable.GetWorkset(element.WorksetId);
                wsTable.SetActiveWorksetId(element.WorksetId);

                TaskDialog.Show("Workset By Element", $"Active workset changed to '{workset.Name}'");
                return(Result.Succeeded);
            }
            catch (Exception)
            {
                return(Result.Failed);
            }
        }
Exemple #23
0
 private Result CreateWorksets(Document document, List <string> worksets)
 {
     if (document.IsWorkshared && !document.IsModifiable)
     {
         using (TransactionGroup worksetGroup = new TransactionGroup(document))
         {
             try
             {
                 worksetGroup.Start("Create Worksets");
                 IList <Autodesk.Revit.DB.Workset> userWork = UserWorksets(document);
                 foreach (Autodesk.Revit.DB.Workset k in userWork)
                 {
                     if (k.Name == "Workset1")
                     {
                         using (Transaction worksetTransaction = new Transaction(document))
                         {
                             worksetTransaction.Start("Create Workset: New Name");
                             WorksetTable.RenameWorkset(document, k.Id, "Your New Name as a String!");
                             worksetTransaction.Commit();
                         }
                     }
                 }
                 worksetGroup.Assimilate();
                 return(Result.Succeeded);
             }
             catch (Autodesk.Revit.Exceptions.InvalidOperationException ex)
             {
                 return(Result.Failed);
             }
         }
     }
     else
     {
         return(Result.Cancelled);
     }
 }
        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("Ошибка", "Проект не переведён в режим совместной работы");
            }
        }
Exemple #25
0
        private static bool SetValue_Integer(this Parameter parameter, object value)
        {
            if (parameter == null || value == null)
            {
                return(false);
            }

            if (value is int)
            {
                //Check if parameter is Workset parameter -> If Workset parameter then change only if Workset with Id exists
                if (parameter.Id.IntegerValue == (int)BuiltInParameter.ELEM_PARTITION_PARAM)
                {
                    WorksetTable worksetTable = parameter.Element?.Document?.GetWorksetTable();
                    if (worksetTable == null)
                    {
                        return(false);
                    }

                    WorksetId worksetId = new WorksetId((int)value);
                    if (WorksetId.InvalidWorksetId == worksetId)
                    {
                        return(false);
                    }

                    //TODO: Double check if workset is valid!
                    Workset workset = worksetTable.GetWorkset(worksetId);
                    if (workset == null || workset.Kind != WorksetKind.UserWorkset)
                    {
                        return(false);
                    }
                }

                parameter.Set((int)value);
                return(true);
            }
            else if (value is string)
            {
                string value_Temp = (string)value;
                int    @int;
                if (int.TryParse(value_Temp, out @int))
                {
                    parameter.Set(@int);
                    return(true);
                }

                //YesNo Type parameter
                if (parameter.Definition.ParameterType == Autodesk.Revit.DB.ParameterType.YesNo)
                {
                    value_Temp = value_Temp.ToUpper().Trim();

                    if (value_Temp.Equals("Y") || value_Temp.Equals("YES") || value_Temp.Equals("+") || value_Temp.Equals("TRUE"))
                    {
                        parameter.Set(1);
                        return(true);
                    }

                    if (value_Temp.Equals("N") || value_Temp.Equals("NO") || value_Temp.Equals("-") || value_Temp.Equals("FALSE"))
                    {
                        parameter.Set(0);
                        return(true);
                    }

                    return(false);
                }
            }
            else if (value is bool)
            {
                if ((bool)value)
                {
                    parameter.Set(1);
                }
                else
                {
                    parameter.Set(0);
                }

                return(true);
            }
            else if (value is IntegerId)
            {
                parameter.Set(((IntegerId)value).Id);
                return(true);
            }

            return(false);
        }
Exemple #26
0
            /// <summary>
            /// Find the WorksetKind for an element
            /// </summary>
            /// <param name="elem">the Element to check</param>
            /// <returns>The WorksetKind of the Element</returns>
            WorksetKind GetWorksetKind(Element elem)
            {
                WorksetTable wksetTbl = elem.Document.GetWorksetTable();

                return(wksetTbl.GetWorkset(elem.WorksetId).Kind);
            }
Exemple #27
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);
        }
Exemple #28
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");
            }
        }