Exemple #1
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);
        }
Exemple #2
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 #3
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 #4
0
        private void BtnCreate_Click(object sender, EventArgs e)
        {
            // check if at least one item is selected
            if (LsvWorksets.CheckedItems.Count == 0)
            {
                UI.Info.Form_Info1.infoMsgMain = "Selection";
                UI.Info.Form_Info1.infoMsgBody = "Select one or more worksets from the list.";
                using (UI.Info.Form_Info1 thisForm = new Info.Form_Info1())
                {
                    thisForm.ShowDialog();
                }
            }
            else
            {
                // collect selected worksets
                List <string> selectedWorksets = new List <string>();
                foreach (ListViewItem item in LsvWorksets.CheckedItems)
                {
                    selectedWorksets.Add(item.Text);
                }

                // check if workset name is in use
                usedNames = GetUsedNames(m_doc, selectedWorksets);
                if (usedNames.Any())
                {
                    using (UI.Info.Form_Warning thisForm = new UI.Info.Form_Warning())
                    {
                        thisForm.ShowDialog();
                    }
                }
                // proceed if workset names are unique
                else
                {
                    using (TransactionGroup tg = new TransactionGroup(m_doc, "Transfer Worksets"))
                    {
                        tg.Start();
                        createdWorksets.Clear(); // clear results list for when running the command more than once.
                        foreach (string WorksetName in selectedWorksets)
                        {
                            using (Transaction t = new Transaction(m_doc, "Single Transaction"))
                            {
                                t.Start();
                                Workset newWorkset = null;
                                newWorkset = Workset.Create(m_doc, WorksetName);
                                createdWorksets.Add(WorksetName);
                                t.Commit();
                            }
                        }
                        tg.Assimilate();
                    }
                    // show Results Form
                    using (UI.Info.Form_Results thisForm = new Info.Form_Results())
                    {
                        thisForm.ShowDialog();
                    }
                    DialogResult = DialogResult.OK;
                }
            }
        }
Exemple #5
0
        /// <summary>
        /// Adds the workset.
        /// </summary>
        /// <param name="doc"></param>
        /// <param name="gridLvl"></param>
        /// <param name="worksetName"></param>
        /// <returns></returns>
        public static Workset AddWorkset(this Document doc, string gridLvl, string worksetName)
        {
            if (doc.IsWorkshared)
            {
                doc.EnableWorksharing(gridLvl, worksetName);
            }

            return(Workset.Create(doc, worksetName));
        }
 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();
 }
Exemple #7
0
 private void createWorksets(Document NewDoc, string templateType)
 {
     using (Transaction tx = new Transaction(NewDoc))
     {
         tx.Start("CreateWorkset");
         Workset.Create(NewDoc, "ELEC - Link");
         Workset.Create(NewDoc, "MECH - Link");
         Workset.Create(NewDoc, "MEP - Link");
         Workset.Create(NewDoc, "PLUMB - Link");
         Workset.Create(NewDoc, "STRUCT - Link");
         if (templateType == "INTERIOR")
         {
             Workset.Create(NewDoc, "CORE & SHELL - Link");
         }
         tx.Commit();
     }
 }
 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 #9
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 #10
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 #11
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 #12
0
        /// <summary>
        ///     Creates a workset.
        /// </summary>
        /// <param name="doc"></param>
        /// <param name="gridLvl"></param>
        /// <param name="worksetName"></param>
        /// <returns></returns>
        public static Workset AddWorkset(this Document doc, string gridLvl, string worksetName)
        {
            if (doc == null)
            {
                throw new ArgumentNullException(nameof(doc));
            }

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

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

            if (doc.IsWorkshared)
            {
                doc.EnableWorksharing(gridLvl, worksetName);
            }

            return(Workset.Create(doc, worksetName));
        }
Exemple #13
0
        /// <summary>
        /// Копирует все выбранные элементы в выбранные документы
        /// </summary>
        /// <param name="documentFrom">Документ из которого производится копирование</param>
        /// <param name="documentsTo">Список документов в которые осуществляется копирование</param>
        /// <param name="elements">Список элементов Revit</param>
        /// <param name="copyingOptions">Настройки копирования элементов</param>
        public async void CopyElements(
            RevitDocument documentFrom,
            IEnumerable <RevitDocument> documentsTo,
            List <BrowserItem> elements,
            CopyingOptions copyingOptions)
        {
            _uiApplication.Application.FailuresProcessing += Application_FailuresProcessing;

            var revitDocuments = documentsTo.ToList();

            Logger.Instance.Add(string.Format(
                                    ModPlusAPI.Language.GetItem(LangItem, "m5"),
                                    DateTime.Now.ToLocalTime(),
                                    documentFrom.Title,
                                    string.Join(", ", revitDocuments.Select(doc => doc.Title))));
            Logger.Instance.Add(string.Format(
                                    ModPlusAPI.Language.GetItem(LangItem, "m8"),
                                    GetCopyingOptionsName(copyingOptions)));

            var copyPasteOption = new CopyPasteOptions();

            switch (copyingOptions)
            {
            case CopyingOptions.AllowDuplicates:
                copyPasteOption.SetDuplicateTypeNamesHandler(new CustomCopyHandlerAllow());
                break;

            case CopyingOptions.RefuseDuplicate:
                copyPasteOption.SetDuplicateTypeNamesHandler(new CustomCopyHandlerAbort());
                break;
            }

            foreach (var documentTo in revitDocuments)
            {
                foreach (var element in elements)
                {
                    var succeed = true;
                    try
                    {
                        await Task.Delay(100).ConfigureAwait(true);

                        var elementId    = new ElementId(element.Id);
                        var revitElement = documentFrom.Document.GetElement(elementId);
                        ICollection <ElementId> elementIds = new List <ElementId> {
                            elementId
                        };

                        using (var transaction = new Transaction(
                                   documentTo.Document,
                                   ModPlusAPI.Language.GetItem(LangItem, "m27")))
                        {
                            transaction.Start();

                            try
                            {
                                if (revitElement.GetType() == typeof(Workset))
                                {
                                    if (documentTo.Document.IsWorkshared)
                                    {
                                        Workset.Create(documentTo.Document, revitElement.Name);
                                    }
                                    else
                                    {
                                        Logger.Instance.Add(string.Format(
                                                                ModPlusAPI.Language.GetItem(LangItem, "m9"),
                                                                DateTime.Now.ToLocalTime(),
                                                                documentTo.Title));
                                    }
                                }

                                if (_stopCopyingOperation)
                                {
                                    _stopCopyingOperation = false;
                                    OnPassedElementsCountChanged(true);
                                    return;
                                }

                                ElementTransformUtils.CopyElements(
                                    documentFrom.Document,
                                    elementIds,
                                    documentTo.Document,
                                    null,
                                    copyPasteOption);
                            }
                            catch (Exception e)
                            {
                                Logger.Instance.Add(string.Format(
                                                        ModPlusAPI.Language.GetItem(LangItem, "m7"),
                                                        DateTime.Now.ToLocalTime(),
                                                        element.Name,
                                                        element.Id,
                                                        element.CategoryName,
                                                        e.Message));

                                succeed = false;
                            }

                            transaction.Commit();
                        }
                    }
                    catch (Exception e)
                    {
                        Logger.Instance.Add(string.Format(
                                                ModPlusAPI.Language.GetItem(LangItem, "m7"),
                                                DateTime.Now.ToLocalTime(),
                                                element.Name,
                                                element.Id,
                                                element.CategoryName,
                                                e.Message));

                        succeed = false;
                    }

                    if (!succeed)
                    {
                        OnBrokenElementsCountChanged();
                    }

                    _passedElements++;
                    if (_passedElements == elements.Count * revitDocuments.Count)
                    {
                        OnPassedElementsCountChanged(true);
                        _passedElements = 0;
                        _uiApplication.Application.FailuresProcessing -= Application_FailuresProcessing;
                    }
                    else
                    {
                        OnPassedElementsCountChanged(false);
                    }
                }
            }

            Logger.Instance.Add(string.Format(
                                    ModPlusAPI.Language.GetItem(LangItem, "m6"),
                                    DateTime.Now.ToLocalTime(),
                                    documentFrom.Title,
                                    string.Join(", ", revitDocuments.Select(doc => doc.Title))));
            Logger.Instance.Add("---------");
        }
Exemple #14
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 #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");
            }
        }