Example #1
0
        public Result Execute(ExternalCommandData commandData, ref string message, ElementSet elements)
        {
            UIDocument UIdoc = commandData.Application.ActiveUIDocument;
            Document   doc   = UIdoc.Document;

            var selection = doc.GetElement(UIdoc.Selection.GetElementIds().FirstOrDefault());

            try
            {
                if (doc.IsWorkshared)
                {
                    var wti = WorksharingUtils.GetWorksharingTooltipInfo(doc, selection.Id);
                    TaskDialog.Show(Tools.GetResourceManager("element_info"),
                                    $"Создал: {wti.Creator}\n" + $"Текущий владелец: {wti.Owner}\n" +
                                    $"Последний раз изменен: {wti.LastChangedBy}");
                    return(Result.Succeeded);
                }
                else
                {
                    TaskDialog.Show(Tools.GetResourceManager("element_info"), "Модель не совместная");
                    return(Result.Failed);
                }
            }
            catch (Exception)
            {
                return(Result.Cancelled);
            }
        }
Example #2
0
        // In the example below, a document is opened with two worksets specified to be opened.
        // Note that the WorksharingUtils.GetUserWorksetInfo() method can be used to access workset
        // information from a closed Revit document.

        Document OpenDocumentWithWorksets(ModelPath projectPath)
        {
            Document doc = null;

            try {
                // Get info on all the user worksets in the project prior to opening
                IList <WorksetPreview> worksets   = WorksharingUtils.GetUserWorksetInfo(projectPath);
                IList <WorksetId>      worksetIds = new List <WorksetId>();
                // Find two predetermined worksets
                foreach (WorksetPreview worksetPrev in worksets)
                {
                    if (worksetPrev.Name.CompareTo("Workset1") == 0 ||
                        worksetPrev.Name.CompareTo("Workset2") == 0)
                    {
                        worksetIds.Add(worksetPrev.Id);
                    }
                }

                OpenOptions openOptions = new OpenOptions();
                // Setup config to close all worksets by default
                WorksetConfiguration openConfig = new WorksetConfiguration(WorksetConfigurationOption.CloseAllWorksets);
                // Set list of worksets for opening
                openConfig.Open(worksetIds);
                openOptions.SetOpenWorksetsConfiguration(openConfig);
                doc = _app.OpenDocumentFile(projectPath, openOptions);
            } catch (Exception e) {
                TaskDialog.Show("Open File Failed", e.Message);
            }

            return(doc);
        }
Example #3
0
        private void ListInfo(Element elem, Document doc)
        {
            var message = string.Empty;

            message += "Element Id: " + elem.Id;

            // The workset the element belongs to
            WorksetId worksetId = elem.WorksetId;

            message += "\nWorkset Id : " + worksetId.ToString();

            // Model Updates Status of the element
            ModelUpdatesStatus updateStatus = WorksharingUtils.GetModelUpdatesStatus(doc, elem.Id);

            message += "\nUpdate status : " + updateStatus.ToString();

            // Checkout Status of the element
            CheckoutStatus checkoutStatus = WorksharingUtils.GetCheckoutStatus(doc, elem.Id);

            message += "\nCheckout status : " + checkoutStatus.ToString();

            // Getting WorksharingTooltipInfo of a given element Id
            WorksharingTooltipInfo tooltipInfo = WorksharingUtils.GetWorksharingTooltipInfo(doc, elem.Id);

            message += "\nCreator : " + tooltipInfo.Creator;
            message += "\nCurrent Owner : " + tooltipInfo.Owner;
            message += "\nLast Changed by : " + tooltipInfo.LastChangedBy;

            SCaddinsApp.WindowManager.ShowMessageBox("Additional Element Information", message);
        }
Example #4
0
        /// <summary>
        ///     Opens the central file.
        /// </summary>
        /// <param name="app"></param>
        /// <param name="serverPath"></param>
        /// <param name="localPath"></param>
        public static Document OpenCentralFile(this Application app, string serverPath, string localPath)
        {
            if (app == null)
            {
                throw new ArgumentNullException(nameof(app));
            }

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

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

            var serverPathl = new FilePath(serverPath);
            var localPathl  = new FilePath(localPath);

            WorksharingUtils.CreateNewLocal(serverPathl, localPathl);

            var option = new OpenOptions
            {
                DetachFromCentralOption = DetachFromCentralOption.DoNotDetach,
                Audit = false
            };

            return(app.OpenDocumentFile(localPathl, option));
        }
        /// <summary>
        ///   Checks the out elements.
        /// </summary>
        /// <returns>ICollection&lt;ElementId&gt;.</returns>
        private ICollection <ElementId> CheckOutElements()
        {
            ICollection <ElementId> m_collection = new Collection <ElementId> {
                Wall.Id
            };

            return(WorksharingUtils.CheckoutElements(_Doc, m_collection));
        }
Example #6
0
        public CEG_Element(Document doc, Element ele)
        {
            Name = ele.Name;
            Id   = ele.Id.IntegerValue;
            WorksharingTooltipInfo worksharingTooltipInfo = WorksharingUtils.GetWorksharingTooltipInfo(doc, ele.Id);

            LastChangeBy = worksharingTooltipInfo.LastChangedBy;
            Owner        = worksharingTooltipInfo.Owner;
            Creater      = worksharingTooltipInfo.Creator;
        }
Example #7
0
        public UIDocument DoOpenNewLocalFromModelPath(ModelPath centralPath, ModelPath localPath)
        {
            List <WorksetId> worksetsToOpen = new List <WorksetId>();
            // First set to close all worksets
            WorksetConfiguration worksetConfig  = new WorksetConfiguration(WorksetConfigurationOption.CloseAllWorksets);
            OpenOptions          theOpenOptions = new OpenOptions();

            try {
                // Create the new local at the given path
                WorksharingUtils.CreateNewLocal(centralPath, localPath);
                // Select specific worksets to open
                // Get a list of worksets from the unopened document
                IList <WorksetPreview> worksets = WorksharingUtils.GetUserWorksetInfo(localPath);
                foreach (WorksetPreview preview in worksets)
                {
                    bool Include = true;
                    ////// The inverse list is the inverse of the worksets checked. In other
                    ////// words an exclusion list.
                    //////foreach (string ws in InverseWorksetList) {
                    //////    if (ws == "") { continue; }
                    //////    if (preview.Name.StartsWith(ws)) {
                    //////        Include = false;
                    //////        continue;
                    //////    } else {
                    //////    }
                    //////}
                    if (Include)
                    {
                        worksetsToOpen.Add(preview.Id);
                    }
                    else
                    {
                        //System.Windows.MessageBox.Show("Excluding " + preview.Name);
                    }
                }
                // Setup option to open the target worksets
                // then set specific ones to open
                worksetConfig.Open(worksetsToOpen);
                theOpenOptions.SetOpenWorksetsConfiguration(worksetConfig);
                // Now open the new local
                UIDocument openedDoc = _uiApp.OpenAndActivateDocument(localPath, theOpenOptions, false);
                return(openedDoc);
            } catch (Exception ex) {
                System.Windows.MessageBox.Show("Opening the file from its location.\n\n" + ex.Message, "This Is Not A Workshared File");
            }
            // If here then not a workshared file.
            string     fname      = ModelPathUtils.ConvertModelPathToUserVisiblePath(centralPath);
            UIDocument openedDocN = _uiApp.OpenAndActivateDocument(fname);

            return(openedDocN);
        }
Example #8
0
        /// <summary>
        /// Opens the central file.
        /// </summary>
        /// <param name="app"></param>
        /// <param name="serverPath"></param>
        /// <param name="localPath"></param>
        public static Document OpenCentralFile(this Application app, string serverPath, string localPath)
        {
            var serverPathl = new FilePath(serverPath);
            var localPathl  = new FilePath(localPath);

            WorksharingUtils.CreateNewLocal(serverPathl, localPathl);

            var option = new OpenOptions
            {
                DetachFromCentralOption = DetachFromCentralOption.DoNotDetach,
                Audit = false
            };

            return(app.OpenDocumentFile(localPathl, option));
        }
Example #9
0
        /// <summary>
        /// This node will output the username of the person who last changed the element if it is available. Keep in mind this only works with workshared documents!
        /// </summary>
        /// <param name="element">The element to check.</param>
        /// <returns name="lastChangedBy">The username of the person who last changed the element.</returns>
        public static string LastChangedBy(global::Revit.Elements.Element element)
        {
            Autodesk.Revit.DB.Document doc;
            try
            {
                doc = element.InternalElement.Document;
            }
            catch (Exception)
            {
                doc = DocumentManager.Instance.CurrentDBDocument;
            }

            WorksharingTooltipInfo tooltipInfo = WorksharingUtils.GetWorksharingTooltipInfo(doc, element.InternalElement.Id);

            return(tooltipInfo.LastChangedBy);
        }
Example #10
0
        public GroupInstanceItem(Element group)
        {
            var doc     = group.Document;
            var created = VerifyUsername(WorksharingUtils.GetWorksharingTooltipInfo(doc, group.Id).LastChangedBy);
            var levelId = group.LevelId == null
                ? ElementId.InvalidElementId
                : group.LevelId;
            var levelName = string.Empty;

            if (levelId != ElementId.InvalidElementId)
            {
                levelName = doc.GetElement(levelId).Name;
            }
            CreatedBy   = created;
            Level       = levelName;
            OwnerViewId = group.OwnerViewId == null
                ? -1
                : group.OwnerViewId.IntegerValue;
        }
Example #11
0
        private Document CreateLocal(UIApplication uiapp, string path)
        {
            string modelname = Path.GetFileNameWithoutExtension(path);

            ModelPath modelpath = ModelPathUtils.ConvertUserVisiblePathToModelPath(path);

            Directory.CreateDirectory(TempPath);

            ModelPath targetpath = ModelPathUtils.ConvertUserVisiblePathToModelPath(TempPath + modelname);

            WorksharingUtils.CreateNewLocal(modelpath, targetpath);

            OpenOptions openoptions = new OpenOptions
            {
                DetachFromCentralOption = DetachFromCentralOption.DoNotDetach
            };

            Document doc = uiapp.Application.OpenDocumentFile(targetpath, openoptions);

            return(doc);
        }
Example #12
0
        public CEG_Product(Document doc, FamilyInstance familyInstance)
        {
            FamilyInstance = familyInstance;
            Id             = familyInstance.Id.IntegerValue;
            Parameter PA_CONTROL_MARK = familyInstance.LookupParameter("CONTROL_MARK");

            if (PA_CONTROL_MARK != null)
            {
                CONTROL_MARK = PA_CONTROL_MARK.AsString();
            }
            Parameter PA_CONTROL_NUMBER = familyInstance.LookupParameter("CONTROL_NUMBER");

            if (PA_CONTROL_NUMBER != null)
            {
                CONTROL_NUMBER = PA_CONTROL_NUMBER.AsString();
            }
            Parameter PA_WORKSET = familyInstance.LookupParameter("Workset");

            if (PA_WORKSET != null)
            {
                WORKSET = PA_WORKSET.AsValueString();
            }
            Parameter PA_DIM_LENGTH = familyInstance.LookupParameter("DIM_LENGTH");

            if (PA_DIM_LENGTH != null)
            {
                DIM_LENGTH = PA_DIM_LENGTH.AsValueString();
            }
            Parameter PA_DIM_WIDTH = familyInstance.LookupParameter("DIM_WIDTH");

            if (PA_DIM_WIDTH != null)
            {
                DIM_WIDTH = PA_DIM_WIDTH.AsValueString();
            }
            WorksharingTooltipInfo worksharingTooltipInfo = WorksharingUtils.GetWorksharingTooltipInfo(doc, familyInstance.Id);

            LastChangeBy = worksharingTooltipInfo.LastChangedBy;
            Owner        = worksharingTooltipInfo.Owner;
            Creater      = worksharingTooltipInfo.Creator;
        }
Example #13
0
        public Result Execute(ExternalCommandData commandData, ref string message, ElementSet elementSet)
        {
            Document   doc   = commandData.Application.ActiveUIDocument.Document;
            UIDocument uidoc = commandData.Application.ActiveUIDocument;

            if (doc.IsWorkshared)
            {
                try
                {
                    Reference reference = uidoc.Selection.PickObject(ObjectType.Element, "Select an element to get info about who created and last edited it:");
                    Element   element   = doc.GetElement(reference);
                    ElementId elementId = element.Id;

                    WorksharingTooltipInfo worksharingTooltipInfo = WorksharingUtils.GetWorksharingTooltipInfo(doc, elementId);

                    TaskDialog taskDialog = new TaskDialog("Element Created and Last Edited By");
                    taskDialog.MainInstruction = "Element: " + element.Name + "\n"
                                                 + "ElementId: " + elementId.ToString() + "\n\n"
                                                 + "Created by: " + worksharingTooltipInfo.Creator + "\n"
                                                 + "Last Edited by: " + worksharingTooltipInfo.LastChangedBy;
                    taskDialog.MainIcon      = TaskDialogIcon.TaskDialogIconInformation;
                    taskDialog.CommonButtons = TaskDialogCommonButtons.Close;
                    taskDialog.DefaultButton = TaskDialogResult.Close;

                    TaskDialogResult taskDialogResult = taskDialog.Show();

                    return(Result.Succeeded);
                }
                catch
                {
                    return(Result.Failed);
                }
            }
            else
            {
                TaskDialog.Show("Workshare Info", "This tool only works with Workshare Enabled Models.");
                return(Result.Succeeded);
            }
        }
Example #14
0
        /// <summary>
        /// Submits edits to a sheet.
        /// </summary>
        /// <param name="app"></param>
        private void UpdateSheet(UIApplication app)
        {
            var doc = app.ActiveUIDocument.Document;

            CentralPath = FileInfoUtil.GetCentralFilePath(doc);

            IsUpdatingSheet = true;
            app.Application.FailuresProcessing += FailureProcessing;

            var view = doc.GetElement(SheetItem.UniqueId) as ViewSheet;

            if (view != null)
            {
                if (WorksharingUtils.GetCheckoutStatus(doc, view.Id) == CheckoutStatus.OwnedByOtherUser)
                {
                    IsUpdatingSheet = false;
                    Messenger.Default.Send(new SheetTaskCompletedMessage
                    {
                        Completed   = false,
                        Message     = "Element owned by another user. Try reloading latest.",
                        CentralPath = CentralPath
                    });
                    return;
                }
                using (var trans = new Transaction(doc, "UpdateSheet"))
                {
                    trans.Start();
                    var action = "update";
                    try
                    {
                        if (SheetTask.IsDeleted)
                        {
                            action = "delete";
                            doc.Delete(view.Id);
                        }
                        else
                        {
                            view.get_Parameter(BuiltInParameter.SHEET_NUMBER)?.Set(SheetTask.Number);
                            view.get_Parameter(BuiltInParameter.SHEET_NAME)?.Set(SheetTask.Name);
                        }

                        trans.Commit();
                        IsUpdatingSheet = false;
                    }
                    catch (Exception e)
                    {
                        trans.RollBack();
                        IsUpdatingSheet = false;

                        Log.AppendLog(LogMessageType.EXCEPTION, "Failed to " + action + " sheet.");
                        Messenger.Default.Send(new SheetTaskCompletedMessage
                        {
                            Completed   = false,
                            Message     = e.Message,
                            CentralPath = CentralPath
                        });
                    }
                }
            }

            // (Konrad) We don't want Revit to keep triggering this even when we are not processing updates.
            app.Application.FailuresProcessing -= FailureProcessing;
        }
Example #15
0
        //This is the primary method for gathering the Warning information from the Document
        private void SetData(Document doc)
        {
            //Create a new List to hold the Warning Type names
            List <string> warningType = new List <string>();

            //Add the first item to the list so it can be controlled
            warningType.Add("--NONE--");

            //Check to see if the DataTable has had columns created not. If not (first time) then create olumns with the correct type of storage element
            if (dtWarnings.Columns.Count == 0)
            {
                //This is a bit redundent because they are all "warnings" as "errors" can't be ignored, but if you use custom error handlers, this may be more useful
                dtWarnings.Columns.Add(new DataColumn("Severity", typeof(FailureSeverity)));
                dtWarnings.Columns.Add(new DataColumn("Description", typeof(string)));
                dtWarnings.Columns.Add(new DataColumn("Element Ids", typeof(ICollection <ElementId>)));
                dtWarnings.Columns.Add(new DataColumn("Name", typeof(string)));
                dtWarnings.Columns.Add(new DataColumn("Creator", typeof(string)));
                dtWarnings.Columns.Add(new DataColumn("Phase Created", typeof(string)));
                dtWarnings.Columns.Add(new DataColumn("Phase Demo'd", typeof(string)));
            }
            //Use these two parameters in case it is not a workshared project
            string elemName = "None";
            string userId   = "None";

            //Loop through every warning in the document
            foreach (FailureMessage warning in doc.GetWarnings())
            {
                //Use these two parameters when the elements cannot have a phase create / demolished
                string pCreate = "";
                string pDemo   = "";

                //Set Issue Description to a string variable
                string description = warning.GetDescriptionText();

                //Check to see if the Warning Type list already has this Warning Type in it, and add it if not
                if (!warningType.Contains(description))
                {
                    warningType.Add(description);
                }

                //Get all of the Element Ids of the elements associated with the warning
                ICollection <ElementId> failingElements = warning.GetFailingElements();

                //This is a bit redundent because they are all "warnings" as "errors" can't be ignored, but if you use custom error handlers, this may be more useful
                FailureSeverity severity = warning.GetSeverity();

                //Check to make sure there are Element Ids for the elements. Some warning types (MECH Systems) do not always provide Element Ids
                if (failingElements.OfType <ElementId>().FirstOrDefault() is ElementId first)
                {
                    //Get the First element of the warning elements in the Document
                    Element elem = doc.GetElement(first);
                    //Set the parameter to the actual name instead of "None" from above
                    elemName = elem.Name;
                    //Checks to see if the Element has any phases associated with it and sets the pCreate and pDemo variables previousy defined
                    if (elem.HasPhases())
                    {
                        if (elem.CreatedPhaseId != ElementId.InvalidElementId)
                        {
                            pCreate = doc.GetElement(elem.CreatedPhaseId).Name;
                        }
                        if (elem.DemolishedPhaseId != ElementId.InvalidElementId)
                        {
                            pDemo = doc.GetElement(elem.DemolishedPhaseId).Name;
                        }
                    }
                    //Checks to see if the Document has Worksharing enables and gets the User informaiton associated with the creation of the element for refernce
                    if (doc.IsWorkshared)
                    {
                        userId = WorksharingUtils.GetWorksharingTooltipInfo(doc, first).Creator;
                    }
                }

                //Add a reow to the DataTable with all of the informaiton for the warning
                dtWarnings.Rows.Add(severity, description, failingElements, elemName, userId, pCreate, pDemo);
            }

            //Set the DataGridView's data source to the DataTable
            dgWarnings.DataSource = dtWarnings;
            //Change the AutoSize mode to fill the width of the DataGridView as it resizes
            dgWarnings.Columns[0].AutoSizeMode = DataGridViewAutoSizeColumnMode.AllCells;
            //Changes the text to include the number of Wanrings for reference to the User
            dgWarnings.Columns[1].HeaderText   = "Description (" + dtWarnings.Rows.Count.ToString() + ")";
            dgWarnings.Columns[1].AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill;
            //Hides the column that contains the Element Ids to keep the DataGridView clean
            dgWarnings.Columns[2].Visible      = false;
            dgWarnings.Columns[3].AutoSizeMode = DataGridViewAutoSizeColumnMode.AllCells;
            dgWarnings.Columns[4].AutoSizeMode = DataGridViewAutoSizeColumnMode.AllCells;
            dgWarnings.Columns[5].AutoSizeMode = DataGridViewAutoSizeColumnMode.AllCells;
            dgWarnings.Columns[6].AutoSizeMode = DataGridViewAutoSizeColumnMode.AllCells;
            //Set the DataGridView to sort based on the Description
            dgWarnings.Sort(dgWarnings.Columns[1], System.ComponentModel.ListSortDirection.Ascending);
            //Clears the auto selection of any rows in the DataGridivew so no elements are selected initially
            dgWarnings.ClearSelection();

            //Clears the Warning Type combo box of all items
            cboWarningType.DataSource = null;
            //Reset the Warning Type combo box with the List of warnings Types
            cboWarningType.DataSource = warningType.ToList();
        }
        public bool UpgradeRevitProject(Document document, string revitFileName)
        {
            bool upgraded = false;

            try
            {
                BasicFileInfo     basicFileInfo     = BasicFileInfo.Extract(revitFileName);
                FileSaveAsOptions fileSaveAsOptions = projectSettings.UpgradeOptions.UpgradeVersionSaveAsOptions;

                LogFileManager.AppendLog("Upgrade Revit Project: " + revitFileName);
                LogFileManager.AppendLog("The Original Revit file was saved in " + basicFileInfo.SavedInVersion);

                SaveAsOptions saveAsOptions = new SaveAsOptions();
                saveAsOptions.OverwriteExistingFile = true;

                if (basicFileInfo.IsWorkshared)
                {
                    WorksharingSaveAsOptions worksharingSaveAsOptions = new WorksharingSaveAsOptions();
                    worksharingSaveAsOptions.OpenWorksetsDefault = FindWorksetOption(fileSaveAsOptions.WorksetConfiguration);
                    worksharingSaveAsOptions.SaveAsCentral       = fileSaveAsOptions.MakeCentral;

                    saveAsOptions.MaximumBackups = fileSaveAsOptions.NumOfBackups;
                    saveAsOptions.SetWorksharingOptions(worksharingSaveAsOptions);
                }

                bool isFinalUpgrade = projectSettings.UpgradeOptions.IsFinalUpgrade;
                if (isFinalUpgrade)
                {
                    string backupDirectory = FindBackupDirectory(revitFileName);
                    if (!string.IsNullOrEmpty(backupDirectory))
                    {
                        string fileName    = Path.GetFileName(revitFileName);
                        string newFilePath = Path.Combine(backupDirectory, fileName);
                        File.Copy(revitFileName, newFilePath, true);
                        if (File.Exists(newFilePath))
                        {
                            document.SaveAs(revitFileName, saveAsOptions);
                            LogFileManager.AppendLog("Backup Saved: " + newFilePath);
                            if (fileSaveAsOptions.Relinquish)
                            {
                                RelinquishOptions roptions = new RelinquishOptions(false);
                                roptions.UserWorksets = true;
                                TransactWithCentralOptions coptions = new TransactWithCentralOptions();
                                WorksharingUtils.RelinquishOwnership(document, roptions, coptions);
                                LogFileManager.AppendLog("Relinquish all worksets created by the current user.");
                            }
                            upgraded = true;
                        }
                    }
                    else
                    {
                        LogFileManager.AppendLog("File Not Saved", "The backup directory cannot be found.");
                        upgraded = false;
                    }
                }
                else
                {
                    string reviewDirectory = FindReviewDirectory(revitFileName);
                    if (string.IsNullOrEmpty(reviewDirectory))
                    {
                        reviewDirectory = fileSaveAsOptions.ReviewLocation;
                    }
                    string fileName = Path.GetFileName(revitFileName);
                    if (!string.IsNullOrEmpty(reviewDirectory))
                    {
                        revitFileName = Path.Combine(reviewDirectory, fileName);
                        document.SaveAs(revitFileName, saveAsOptions);
                        LogFileManager.AppendLog("File Saved: " + revitFileName);
                        if (fileSaveAsOptions.Relinquish)
                        {
                            RelinquishOptions roptions = new RelinquishOptions(false);
                            roptions.UserWorksets = true;
                            TransactWithCentralOptions coptions = new TransactWithCentralOptions();
                            WorksharingUtils.RelinquishOwnership(document, roptions, coptions);
                            LogFileManager.AppendLog("Relinquish all worksets created by the current user.");
                        }
                        upgraded = true;
                    }
                    else
                    {
                        LogFileManager.AppendLog("File Not Saved", "The review directory cannot be found.");
                        upgraded = false;
                    }
                }
            }
            catch (Exception ex)
            {
                string message = ex.Message;
                LogFileManager.AppendLog("[Error] Upgrade Revit Project", message);
            }
            return(upgraded);
        }
        public Document OpenRevitDocument(string revitFileName)
        {
            Document doc = null;

            try
            {
                LogFileManager.AppendLog("Open Revit Document: " + revitFileName);
                BasicFileInfo   basicFileInfo   = BasicFileInfo.Extract(revitFileName);
                FileOpenOptions fileOpenOptions = projectSettings.UpgradeOptions.UpgradeVersionOpenOptions;

                if (basicFileInfo.IsWorkshared)
                {
                    ModelPath   modelPath   = ModelPathUtils.ConvertUserVisiblePathToModelPath(revitFileName);
                    OpenOptions openOptions = new OpenOptions();
                    openOptions.Audit = fileOpenOptions.Audit;
                    if (fileOpenOptions.DetachAndPreserveWorksets)
                    {
                        openOptions.DetachFromCentralOption = DetachFromCentralOption.DetachAndPreserveWorksets;
                    }

                    IList <WorksetPreview> wsPreviews      = new List <WorksetPreview>();
                    IList <WorksetId>      worksetIds      = new List <WorksetId>();
                    WorksetConfiguration   wsConfiguration = new WorksetConfiguration();

                    try
                    {
                        wsPreviews = WorksharingUtils.GetUserWorksetInfo(modelPath);
                        if (wsPreviews.Count > 0)
                        {
                            foreach (WorksetPreview wsPreview in wsPreviews)
                            {
                                worksetIds.Add(wsPreview.Id);
                            }

                            if (fileOpenOptions.OpenAllWorkset)
                            {
                                wsConfiguration.Open(worksetIds);
                            }
                            else
                            {
                                wsConfiguration.Close(worksetIds);
                            }
                            openOptions.SetOpenWorksetsConfiguration(wsConfiguration);
                        }
                    }
                    catch (Exception ex)
                    {
                        LogFileManager.AppendLog("[Warning] Open Worksets", ex.Message);
                    }
                    doc = uiApp.Application.OpenDocumentFile(modelPath, openOptions);
                }
                else
                {
                    doc = uiApp.Application.OpenDocumentFile(revitFileName);
                }
            }
            catch (Exception ex)
            {
                string message = ex.Message;
                LogFileManager.AppendLog("[Error] Open Revit Document", message);
            }
            return(doc);
        }
Example #18
0
        private void LoadData(Document doc)
        {
            this.Doc = doc;
            List <ViewSheet> list  = this.AllViewSheets(doc);
            List <View>      list2 = new List <View>();

            foreach (ViewSheet viewSheet in list)
            {
                List <View> list3 = this.AllLegendInSheet(viewSheet, doc);
                bool        flag  = list3.Count < 1;
                if (!flag)
                {
                    foreach (View view in list3)
                    {
                        bool flag2 = this.Dic.ContainsKey(view.Id.IntegerValue);
                        if (flag2)
                        {
                            string str = string.Concat(new string[]
                            {
                                "  + [",
                                viewSheet.SheetNumber,
                                "_",
                                viewSheet.Name,
                                "]"
                            });
                            LegendExtension legendExtension = this.Dic[view.Id.IntegerValue];
                            legendExtension.ListSheets += str;
                        }
                        else
                        {
                            LegendExtension        legendExtension2       = new LegendExtension();
                            WorksharingTooltipInfo worksharingTooltipInfo = WorksharingUtils.GetWorksharingTooltipInfo(doc, view.Id);
                            legendExtension2.Name          = view.Name;
                            legendExtension2.Id            = view.Id.IntegerValue;
                            legendExtension2.Creator       = worksharingTooltipInfo.Creator;
                            legendExtension2.LastChangedBy = worksharingTooltipInfo.LastChangedBy;
                            legendExtension2.ListSheets    = string.Concat(new string[]
                            {
                                "[",
                                viewSheet.SheetNumber,
                                "_",
                                viewSheet.Name,
                                "]"
                            });
                            list2.Add(view);
                            this.Dic.Add(view.Id.IntegerValue, legendExtension2);
                        }
                    }
                }
            }
            foreach (View view2 in this.AllLegends(doc))
            {
                foreach (View view3 in list2)
                {
                    bool flag3 = view2.Id.IntegerValue == view3.Id.IntegerValue;
                    if (!flag3)
                    {
                        bool flag4 = this.Dic.ContainsKey(view2.Id.IntegerValue);
                        if (!flag4)
                        {
                            LegendExtension        legendExtension3        = new LegendExtension();
                            WorksharingTooltipInfo worksharingTooltipInfo2 = WorksharingUtils.GetWorksharingTooltipInfo(doc, view2.Id);
                            legendExtension3.Name          = view2.Name;
                            legendExtension3.Id            = view2.Id.IntegerValue;
                            legendExtension3.Creator       = worksharingTooltipInfo2.Creator;
                            legendExtension3.LastChangedBy = worksharingTooltipInfo2.LastChangedBy;
                            legendExtension3.ListSheets    = "";
                            this.Dic.Add(view2.Id.IntegerValue, legendExtension3);
                        }
                    }
                }
            }
        }
Example #19
0
        public void DocumentOpened(object sender, DocumentOpenedEventArgs e)
        {
            Document doc = e.Document;

            if (doc.IsFamilyDocument)
            {
                return;
            }

            Schema schema = Schema.Lookup(schemaGUID);

            if (schema == null || !schema.IsValidObject)
            {
                return;
            }

            // Check to see if there is out-dated data stored in ProjectInformation
            Entity entity = null;

            entity = doc.ProjectInformation.GetEntity(schema);
            if (entity != null && entity.IsValid())
            {
                // Need to transition the data to a datastorage object.
                // First make sure this isn't a workshared document with the ProjectInfo already checked out by another user
                // If it's checked out by another person, we'll just skip this since we can't fix it now.
                if (doc.IsWorkshared && WorksharingUtils.GetCheckoutStatus(doc, doc.ProjectInformation.Id) == CheckoutStatus.OwnedByOtherUser)
                {
                    return;
                }

                // Otherwise, lets transition the data from the old to the new.
                if (entity.Get <IList <ElementId> >("ScheduleId") != null)
                {
                    // Get the information from the ProjectInformation entity
                    var schedIds = entity.Get <IList <ElementId> >("ScheduleId").ToList();
                    var paths    = entity.Get <IList <string> >("ExcelFilePath").ToList();
                    var wsNames  = entity.Get <IList <string> >("WorksheetName").ToList();
                    var dts      = entity.Get <IList <string> >("DateTime").ToList();
                    var pTypes   = entity.Get <IList <int> >("PathType")?.ToList() ?? new List <int>();

                    // Purge the old Schema and Entity, then assign the data to a new Schema and DataStorage element
                    RebuildSchema(doc, schema, schedIds, paths, wsNames, dts, pTypes);
                }
            }

            // Find if a datstorage element exists now and update as needed.
            DataStorage ds = new FilteredElementCollector(doc).OfClass(typeof(DataStorage)).Where(x => x.Name.Equals(dsName)).Cast <DataStorage>().FirstOrDefault();

            // Get the ExcelScheduleEntity from the data storage and verify its valid
            ExcelScheduleEntity ent = ds?.GetEntity <ExcelScheduleEntity>();

            if (ent == null)
            {
                return;
            }

            // Check if any schedules need to be updated
            List <int>      modifyIndices = new List <int>();
            List <DateTime> modDateTimes  = new List <DateTime>();

            for (int i = 0; i < ent.ScheduleId.Count; i++)
            {
                string currentFilePath;
                string docPath;
                if (doc.IsWorkshared)
                {
                    docPath = ModelPathUtils.ConvertModelPathToUserVisiblePath(doc.GetWorksharingCentralModelPath());
                }
                else
                {
                    docPath = doc.PathName;
                }

                if ((PathType)ent.PathType[i] == PathType.Absolute)
                {
                    currentFilePath = ent.ExcelFilePath[i];
                }
                else
                {
                    currentFilePath = PathExchange.GetFullPath(ent.ExcelFilePath[i], docPath);
                }

                // Get the file write time as UTC
                DateTime modTime    = new FileInfo(currentFilePath).LastWriteTimeUtc;
                DateTime storedTime = Convert.ToDateTime(ent.DateTime[i]);

                // Make sure the save time isn't more or less the same as stored.
                if ((modTime - storedTime).Seconds > 1)
                {
                    modifyIndices.Add(i);
                    modDateTimes.Add(modTime);
                }
            }

            if (modifyIndices.Count == modDateTimes.Count && modifyIndices.Count > 0)
            {
                IntPtr statusBar = FindWindowEx(RevitHandle, IntPtr.Zero, "msctls_statusbar32", "");
                foreach (int i in modifyIndices)
                {
                    if (statusBar != IntPtr.Zero)
                    {
                        SetWindowText(statusBar, string.Format("Updating Excel Schedule {0}.", ent.WorksheetName[modifyIndices[i]]));
                    }
                    Scheduler scheduler = new Scheduler();
                    scheduler.ModifySchedule(doc, ent.ScheduleId[modifyIndices[i]], ent.ExcelFilePath[modifyIndices[i]],
                                             ent.WorksheetName[modifyIndices[i]], "Update Excel Schedule", ent.PathType[modifyIndices[i]],
                                             Properties.Settings.Default.reloadValuesOnly);

                    ent.DateTime[modifyIndices[i]] = modDateTimes[i].ToString();
                }
                if (statusBar != IntPtr.Zero)
                {
                    SetWindowText(statusBar, "");
                }

                // change the dateTimes
                using (Transaction t = new Transaction(doc, "Update schedule date"))
                {
                    t.Start();
                    ds.SetEntity(ent);
                    t.Commit();
                }

                // Write to home
                RevitCommon.FileUtils.WriteToHome("Excel Import - Document Open Reload", doc.Application.VersionName, doc.Application.Username);
            }
        }
Example #20
0
            public void Execute(UIApplication app)
            {
                if (App.docdict.Keys.Count == 0)
                {
                    return;
                }

                TransactWithCentralOptions transact      = new TransactWithCentralOptions();
                SynchLockCallback          transCallBack = new SynchLockCallback();

                transact.SetLockCallback(transCallBack);
                SynchronizeWithCentralOptions syncset           = new SynchronizeWithCentralOptions();
                RelinquishOptions             relinquishoptions = new RelinquishOptions(true)
                {
                    CheckedOutElements = true
                };

                syncset.SetRelinquishOptions(relinquishoptions);

                App.running = true;

                if (relinquish)
                {
                    foreach (Document doc in App.docdict.Keys)
                    {
                        try
                        {
                            WorksharingUtils.RelinquishOwnership(doc, relinquishoptions, transact);
                        }
                        catch { }
                    }

                    relinquish = false;
                }
                if (sync)
                {
                    if (App.Dismiss())
                    {
                        sync        = false;
                        App.running = false;
                        return;
                    }

                    app.Application.FailuresProcessing += FailureProcessor;

                    bool syncfailed = false;

                    foreach (Document doc in App.docdict.Keys)
                    {
                        try
                        {
                            if (docdict[doc])
                            {
                                doc.SynchronizeWithCentral(transact, syncset);
                                app.Application.WriteJournalComment("AutoSync", true);
                            }
                        }
                        catch
                        {
                            syncfailed = true;
                        }
                    }

                    app.Application.FailuresProcessing -= FailureProcessor;

                    if (syncfailed)
                    {
                        countdown -= retrysync;
                    }

                    sync = false;
                }
                if (close)
                {
                    if (App.Dismiss())
                    {
                        App.running = false;
                        close       = false;
                        return;
                    }

                    bool closelast = false;

                    string activepathname = app.ActiveUIDocument.Document.PathName;

                    List <Document> docsdeletelist = new List <Document>();

                    foreach (Document doc in App.docdict.Keys)
                    {
                        if (activepathname == doc.PathName)
                        {
                            closelast = true;
                        }
                        else
                        {
                            docsdeletelist.Add(doc);
                        }
                    }
                    foreach (Document doc in docsdeletelist)
                    {
                        try
                        {
                            doc.Close(false);
                        }
                        catch { }
                    }

                    if (closelast)
                    {
                        RevitCommandId closeDoc = RevitCommandId.LookupPostableCommandId(PostableCommand.Close);
                        app.PostCommand(closeDoc);
                    }

                    close     = false;
                    countdown = 0;
                }

                App.running = false;

                transact.Dispose();
                syncset.Dispose();
                relinquishoptions.Dispose();
            }
Example #21
0
        public void SetParameters(IEnumerable <SetParameterRequest> setParameterRequests)
        {
            var document = GetDocument();

            using (var trans = new Transaction(document, "Set parameters"))
            {
                if (trans.Start() == TransactionStatus.Started)
                {
                    var groupedRequests = setParameterRequests.GroupBy(x => x.ElementId);

                    foreach (var group in groupedRequests)
                    {
                        var element = document.GetElement(group.First().ElementId);
                        var status  = WorksharingUtils.GetCheckoutStatus(element.Document, element.Id);
                        if (status != CheckoutStatus.OwnedByOtherUser)
                        {
                            foreach (var setParameterRequest in group)
                            {
                                Parameter parameter = null;
                                if (int.TryParse(setParameterRequest.ParameterId, out int intValue))
                                {
                                    foreach (Parameter param in element.Parameters)
                                    {
                                        if (param.Id.IntegerValue == intValue)
                                        {
                                            parameter = param;
                                        }
                                    }
                                }

                                if (Guid.TryParse(setParameterRequest.ParameterId, out Guid guid))
                                {
                                    foreach (Parameter param in element.Parameters)
                                    {
                                        if (param.GUID == guid)
                                        {
                                            parameter = param;
                                        }
                                    }
                                }

                                if (parameter == null)
                                {
                                    if (Enum.TryParse(setParameterRequest.ParameterId, out BuiltInParameter bip) && Enum.IsDefined(typeof(BuiltInParameter), bip))
                                    {
                                        parameter = element.get_Parameter(bip);
                                    }
                                    else
                                    {
                                        parameter = element.GetParameters(setParameterRequest.ParameterId).FirstOrDefault();
                                    }
                                }

                                if (parameter != null)
                                {
                                    SetParameter(parameter, setParameterRequest.Value);
                                }
                            }
                        }
                        else
                        {
                            // Could not write parameter
                        }
                    }
                }
                trans.Commit();
            }
        }
Example #22
0
        /// <summary>
        /// delete elements depends on the input params.json file
        /// </summary>
        /// <param name="data"></param>
        public static void DeleteAllElements(DesignAutomationData data)
        {
            if (data == null)
            {
                throw new ArgumentNullException(nameof(data));
            }

            Application rvtApp = data.RevitApp;

            if (rvtApp == null)
            {
                throw new InvalidDataException(nameof(rvtApp));
            }

            string modelPath = data.FilePath;

            if (String.IsNullOrWhiteSpace(modelPath))
            {
                throw new InvalidDataException(nameof(modelPath));
            }

            // If the input revit model passed is a workshared revit file then by default the Design Automation
            // bridge will open the model detached from central, opting DetachAndPreserveWorsets option.
            // Non-worshared revit file will be load as is.
            Document doc = data.RevitDoc;

            if (doc == null)
            {
                throw new InvalidOperationException("Could not open document.");
            }


            // For CountIt workItem: If RvtParameters is null, count all types
            DeleteElementsParams deleteElementsParams = DeleteElementsParams.Parse("params.json");

            using (Transaction transaction = new Transaction(doc))
            {
                transaction.Start("Delete Elements");
                if (deleteElementsParams.walls)
                {
                    FilteredElementCollector col = new FilteredElementCollector(doc).OfClass(typeof(Wall));
                    doc.Delete(col.ToElementIds());
                }
                if (deleteElementsParams.floors)
                {
                    FilteredElementCollector col = new FilteredElementCollector(doc).OfClass(typeof(Floor));
                    doc.Delete(col.ToElementIds());
                }
                if (deleteElementsParams.doors)
                {
                    FilteredElementCollector collector  = new FilteredElementCollector(doc);
                    ICollection <ElementId>  collection = collector.OfClass(typeof(FamilyInstance))
                                                          .OfCategory(BuiltInCategory.OST_Doors)
                                                          .ToElementIds();
                    doc.Delete(collection);
                }
                if (deleteElementsParams.windows)
                {
                    FilteredElementCollector collector  = new FilteredElementCollector(doc);
                    ICollection <ElementId>  collection = collector.OfClass(typeof(FamilyInstance))
                                                          .OfCategory(BuiltInCategory.OST_Windows)
                                                          .ToElementIds();
                    doc.Delete(collection);
                }
                transaction.Commit();
            }

            ModelPath path = ModelPathUtils.ConvertUserVisiblePathToModelPath("result.rvt");
            // If a worshared file is opened as a part of this addin then the new file will be
            // saved as central.
            SaveAsOptions opts = new SaveAsOptions();

            if (doc.IsWorkshared)
            {
                opts.SetWorksharingOptions(new WorksharingSaveAsOptions {
                    SaveAsCentral = true
                });
                WorksharingUtils.RelinquishOwnership(doc, new RelinquishOptions(true), new TransactWithCentralOptions());
            }
            doc.SaveAs(path, new SaveAsOptions());
        }