Example #1
0
        public AdminFamiliesSRCPRequest(UIApplication uiApp, String text)
        {
            MainUI      uiForm = BARevitTools.Application.thisApp.newMainUi;
            RVTDocument doc    = uiApp.ActiveUIDocument.Document;

            //Clear out the backup families from the directory
            List <string> backupFamilies = GeneralOperations.GetAllRvtBackupFamilies(uiForm.adminFamiliesSRCPDirectoryTextBox.Text, true);

            GeneralOperations.CleanRfaBackups(backupFamilies);

            //Get the family files from the directory. If the option to use the date since last modified was checked, use the first method, else use the second method
            List <string> familyFiles = new List <string>();

            if (uiForm.adminFamiliesSRCPUseDateCheckBox.Checked)
            {
                familyFiles = GeneralOperations.GetAllRvtFamilies(uiForm.adminFamiliesSRCPDirectoryTextBox.Text, uiForm.adminFamiliesSRCPDatePicker.Value, true);
            }
            else
            {
                familyFiles = GeneralOperations.GetAllRvtFamilies(uiForm.adminFamiliesSRCPDirectoryTextBox.Text, false);
            }

            //Verify the number of families collected is more than 0
            if (familyFiles.Count > 0)
            {
                foreach (string familyFile in familyFiles)
                {
                    RVTDocument famDoc = RVTOperations.OpenRevitFile(uiApp, familyFile);
                    Family      family = famDoc.OwnerFamily;
                    Parameter   rcp    = family.get_Parameter(BuiltInParameter.ROOM_CALCULATION_POINT);
                    if (rcp.AsInteger() == 0)
                    {
                        try
                        {
                            using (Transaction t1 = new Transaction(famDoc, "SetRoomCalculationPoint"))
                            {
                                t1.Start();
                                rcp.Set(1);
                                t1.Commit();
                            }
                            uiForm.adminFamiliesSRCPListBox.Items.Add(famDoc.Title.Replace(".rfa", "") + ": Updated");
                        }
                        catch (Exception e)
                        {
                            uiForm.adminFamiliesSRCPListBox.Items.Add(famDoc.Title.Replace(".rfa", "") + ": FAILED");
                        }
                    }
                    else
                    {
                        uiForm.adminFamiliesSRCPListBox.Items.Add(famDoc.Title.Replace(".rfa", "") + ": Ignored");
                    }
                    RVTOperations.SaveRevitFile(uiApp, famDoc, true);
                }
            }
            GeneralOperations.CleanRfaBackups(uiForm.adminFamiliesSRCPDirectoryTextBox.Text);
        }
Example #2
0
        public AdminFamiliesBRPRequest(UIApplication uiApp, String text)
        {
            MainUI        uiForm        = BARevitTools.Application.thisApp.newMainUi;
            RVTDocument   doc           = uiApp.ActiveUIDocument.Document;
            SaveAsOptions saveAsOptions = new SaveAsOptions();

            saveAsOptions.Compact               = true;
            saveAsOptions.MaximumBackups        = 3;
            saveAsOptions.OverwriteExistingFile = true;

            //Get how many families to evaluate for the progress bar steps and resetting the progress bar
            int filesToProcess = 0;

            foreach (DataGridViewRow rowCount in uiForm.adminFamiliesBRPFamiliesDGV.Rows)
            {
                if (rowCount.Cells[0].Value.ToString() == "True")
                {
                    filesToProcess++;
                }
            }
            uiForm.adminFamiliesBRPProgressBar.Value   = 0;
            uiForm.adminFamiliesBRPProgressBar.Minimum = 0;
            uiForm.adminFamiliesBRPProgressBar.Maximum = filesToProcess;
            uiForm.adminFamiliesBRPProgressBar.Step    = 1;
            uiForm.adminFamiliesBRPProgressBar.Visible = true;

            //Stop all edits to the DataGridView table
            uiForm.adminFamiliesBAPParametersDGV.EndEdit();
            foreach (DataGridViewRow row in uiForm.adminFamiliesBRPFamiliesDGV.Rows)
            {
                //If the checkbox to select the family is not in a null state, continue
                if (row.Cells["Family Select"].Value != null)
                {
                    //If the checkbox to select the family is checked, continue
                    if (row.Cells["Family Select"].Value.ToString() == "True")
                    {
                        //Get the family path for the selected row and make a dictionary to store the parameters by name
                        string filePath = row.Cells["Family Path"].Value.ToString();
                        Dictionary <string, FamilyParameter> famParams = new Dictionary <string, FamilyParameter>();
                        try
                        {
                            //Open the file and verify it is a family document
                            RVTDocument famDoc = RVTOperations.OpenRevitFile(uiApp, filePath);
                            if (famDoc.IsFamilyDocument)
                            {
                                //saveFamily will be used to determine if the family needs saved or just closed. No need to save the family if nothing was modified
                                bool saveFamily = false;
                                //Get the Family Manager to retrieve the parameters, then add each parameter to the dictionary by name
                                FamilyManager familyManager = famDoc.FamilyManager;
                                foreach (FamilyParameter famParam in familyManager.Parameters)
                                {
                                    if (!famParams.Keys.Contains(famParam.Definition.Name))
                                    {
                                        famParams.Add(famParam.Definition.Name, famParam);
                                    }
                                    else
                                    {
                                        continue;
                                    }
                                }

                                //Cycle through the rows of parameter to remove
                                foreach (DataGridViewRow paramRow in uiForm.adminFamiliesBRPParametersDGV.Rows)
                                {
                                    //If the cell for the parameter name is not null, continue
                                    if (paramRow.Cells["Parameter Name"].Value != null)
                                    {
                                        //Get the name of the parameter to attempt removal, and see if it exists in the dictionary
                                        string name = paramRow.Cells["Parameter Name"].Value.ToString();
                                        if (famParams.Keys.Contains(name))
                                        {
                                            try
                                            {
                                                //Attempt to remove the parameter. This may not be possible if a built-in parameter was specified by name, so the Catch will throw the message stating the name of the parameter that could not be removed and which family it was attempted on
                                                using (Transaction t = new Transaction(famDoc, "Remove Parameter"))
                                                {
                                                    t.Start();
                                                    familyManager.RemoveParameter(famParams[name]);
                                                    t.Commit();
                                                    saveFamily = true;
                                                }
                                            }
                                            catch
                                            {
                                                MessageBox.Show(String.Format("Could not remove parameter '{0}' for family {1}", name, famDoc.Title));
                                            }
                                        }
                                    }
                                }

                                //If there were any changes, save the family. If not, continue on to close the family
                                if (saveFamily == true)
                                {
                                    ModelPath modelPath = ModelPathUtils.ConvertUserVisiblePathToModelPath(filePath);
                                    famDoc.SaveAs(filePath, saveAsOptions);
                                }
                            }
                            //Close the family document
                            famDoc.Close(false);
                        }
                        catch
                        {
                            MessageBox.Show("The family could not be opened, likely due to being a newer version of Revit");
                        }
                        finally
                        {
                            //No matter what, step forward the progress bar
                            uiForm.adminFamiliesBRPProgressBar.PerformStep();
                        }
                    }
                    else
                    {
                        continue;
                    }
                }
            }
            GeneralOperations.CleanRfaBackups(uiForm.adminFamiliesBRPFamilyDirectory);
            uiForm.adminFamiliesBRPProgressBar.Visible = false;
        }
Example #3
0
        //
        //This class is associated with the Upgrade Projects tool
        public SetupUPRequest(UIApplication uiApp, String text)
        {
            MainUI       uiForm = BARevitTools.Application.thisApp.newMainUi;
            DataGridView dgv    = uiForm.setupUPDataGridView;

            dgv.EndEdit();

            RVTDocument doc = uiApp.ActiveUIDocument.Document;
            string      hostFilePathToUpgrade  = uiForm.setupUPOriginalFilePathTextBox.Text;
            string      hostFilePathForUpgrade = uiForm.setupUPUpgradedFilePathSetTextBox.Text + "\\" + uiForm.setupUPUpgradedFilePathUserTextBox.Text + ".rvt";

            //Reset the progress bar
            uiForm.setupUPProgressBar.Value   = 0;
            uiForm.setupUPProgressBar.Minimum = 0;
            uiForm.setupUPProgressBar.Step    = 1;

            //Determine the number of steps for the progress bar based on the number of links checked for upgrading plus 1 for the host
            int progressBarSteps = 1;

            foreach (DataGridViewRow row in dgv.Rows)
            {
                if (row.Cells["Upgrade"].Value != null)
                {
                    if (row.Cells["Upgrade"].Value.ToString() == "True")
                    {
                        progressBarSteps++;
                    }
                }
            }
            uiForm.setupUPProgressBar.Maximum = progressBarSteps;

            //Let the user know if they are trying to save over a file that already exists
            if (File.Exists(hostFilePathForUpgrade))
            {
                MessageBox.Show("A file already exists with the name and location specified for the upgrade of the host Revit project file");
            }
            //If they didn't set a save location for the file, let them know
            else if (uiForm.setupUPUpgradedFilePathUserTextBox.Text == "")
            {
                MessageBox.Show("No location for the upgrade of the host Revit project file is set");
            }
            else
            {
                //Otherwise, show the progress bar and step through the rows of the DataGridView links
                uiForm.setupUPProgressBar.Visible = true;
                for (int i = 0; i < dgv.Rows.Count; i++)
                {
                    try
                    {
                        if (dgv.Rows[i].Cells["Upgrade"].Value != null)
                        {
                            //If the link is allowed to be upgraded, and its checkbox is checked, continue
                            if (dgv.Rows[i].Cells["Allow Upgrade"].Value.ToString() == "True" && dgv.Rows[i].Cells["Upgrade"].Value.ToString() == "True")
                            {
                                //Grab the orignial path for the link and the path for where it will be saved
                                string linkFilePathToUpgrade  = dgv.Rows[i].Cells["Original Path"].Value.ToString();
                                string linkFilePathForUpgrade = dgv.Rows[i].Cells["New Path"].Value.ToString();
                                //Perform the upgrade operations on the file and report if it was successful
                                bool linkResult = RVTOperations.UpgradeRevitFile(uiApp, linkFilePathToUpgrade, linkFilePathForUpgrade, false);

                                if (linkResult == true)
                                {
                                    //If the upgrade was successful, set the Upgrade Result column to true and set the row's background color to GreenYellow
                                    dgv.Rows[i].Cells["Upgrade Result"].Value = true;
                                    dgv.Rows[i].DefaultCellStyle.BackColor    = System.Drawing.Color.GreenYellow;
                                }
                                else
                                {
                                    //If the upgrade failed, set the Upgrade Result column to false and set the background color to red
                                    dgv.Rows[i].Cells["Upgrade Result"].Value = false;
                                    dgv.Rows[i].DefaultCellStyle.BackColor    = System.Drawing.Color.Red;
                                }
                                //Step forward the progress bar
                                uiForm.setupUPProgressBar.PerformStep();
                                uiForm.Update();
                            }
                        }
                        else
                        {
                            continue;
                        }
                    }
                    catch (Exception e)
                    {
                        MessageBox.Show(e.Message);
                    }
                }

                //Once the links are done upgrading, upgrade the host
                bool hostResult = RVTOperations.UpgradeRevitFile(uiApp, hostFilePathToUpgrade, hostFilePathForUpgrade, false);
                //Determine how many links were able to be upgraded
                int countOfUpgradeLinks = 0;
                foreach (DataGridViewRow row in dgv.Rows)
                {
                    try
                    {
                        if (row.Cells["Upgrade"].Value != null)
                        {
                            if (row.Cells["Upgrade"].Value.ToString() == "True")
                            {
                                countOfUpgradeLinks++;
                            }
                        }
                    }
                    catch
                    {
                        continue;
                    }
                    finally
                    {
                        uiForm.setupUPProgressBar.PerformStep();
                        uiForm.Update();
                    }
                }

                //If the host was able to be upgraded, continue
                if (hostResult == true)
                {
                    //Set the background color of the text box to GreenYellow
                    uiForm.setupUPOriginalFilePathTextBox.BackColor = System.Drawing.Color.GreenYellow;
                    if (countOfUpgradeLinks > 0)
                    {
                        try
                        {
                            //Open the upgraded host and get the links
                            RVTDocument hostDoc = RVTOperations.OpenRevitFile(uiApp, hostFilePathForUpgrade);
                            Dictionary <string, RevitLinkType> linkNames = new Dictionary <string, RevitLinkType>();
                            var linkTypes = new FilteredElementCollector(hostDoc).OfClass(typeof(RevitLinkType)).ToElements();
                            foreach (RevitLinkType linkType in linkTypes)
                            {
                                //Add each link to a dictionary with their file name and indexed link type
                                linkNames.Add(linkType.Name.Replace(".rvt", ""), linkType);
                            }

                            //Cycle through the links
                            foreach (DataGridViewRow row in dgv.Rows)
                            {
                                try
                                {
                                    //If the link's row was checked for upgrading, it was able to be upgraded, the upgraded file exists at the New Path location, and the dictionary of links contains the original name of the link, continue
                                    if (row.Cells["Upgrade"].Value.ToString() == "True" &&
                                        row.Cells["Upgrade Result"].Value.ToString() == "True" &&
                                        File.Exists(row.Cells["New Path"].Value.ToString()) &&
                                        linkNames.Keys.Contains(row.Cells["Original Name"].Value.ToString()))
                                    {
                                        try
                                        {
                                            //Get the link to reload via the name from the dictionary
                                            RevitLinkType linkToReload = linkNames[row.Cells["Original Name"].Value.ToString().Replace(".rvt", "")];
                                            //Convert the link's user path to a model path, then reload it
                                            ModelPath modelPathToLoadFrom = ModelPathUtils.ConvertUserVisiblePathToModelPath(row.Cells["New Path"].Value.ToString());
                                            linkToReload.LoadFrom(modelPathToLoadFrom, new WorksetConfiguration());
                                        }
                                        catch (Exception e)
                                        {
                                            //If the link was upgraded but could not be reloaded, set the background color to orange and let the user know it could not be reloaded
                                            row.DefaultCellStyle.BackColor = System.Drawing.Color.Orange;
                                            MessageBox.Show(String.Format("Could not remap the link named {0} in the host file", row.Cells["Original Name"].Value.ToString()));
                                            MessageBox.Show(e.ToString());
                                        }
                                    }
                                }
                                catch { continue; }
                            }
                            //Save the upgraded host file
                            RVTOperations.SaveRevitFile(uiApp, hostDoc, true);
                        }
                        catch (Exception e) { MessageBox.Show(e.ToString()); }
                    }
                }
                else
                {
                    //If the host file failed to upgrade, set its text box background color to red
                    uiForm.setupUPOriginalFilePathTextBox.BackColor = System.Drawing.Color.Red;
                }
                uiForm.Update();
                uiForm.Refresh();
            }
        }
Example #4
0
        public AdminDataGFFRequest(UIApplication uiApp, String text)
        {
            //Items pertaining to the open UI
            MainUI        uiForm         = BARevitTools.Application.thisApp.newMainUi;
            List <string> itemsToCollect = uiForm.adminDataGFFItemsToCollect;

            //UI settings related to the proggress bar
            int filesToProcess = uiForm.adminDataGFFFiles.Count;

            uiForm.adminDataGFFDataProgressBar.Value   = 0;
            uiForm.adminDataGFFDataProgressBar.Minimum = 0;
            uiForm.adminDataGFFDataProgressBar.Maximum = filesToProcess;
            uiForm.adminDataGFFDataProgressBar.Step    = 1;
            uiForm.adminDataGFFDataProgressBar.Visible = true;

            //New objects
            DataTable dt             = new DataTable();
            int       selectionGroup = -2;

            //Getting the items from the list obtained from checked listbox items to determine what datatable columns are needed
            //The items below are able to be obtained without API calls. Statementselect remains -1 to indicate no API request will be needed, saving time.
            if (itemsToCollect.Contains("Family Name"))
            {
                DataColumn familyNameColumn = dt.Columns.Add("FamilyName", typeof(String));
                selectionGroup = -1;
            }

            if (itemsToCollect.Contains("Family Size"))
            {
                DataColumn familySizeColumn = dt.Columns.Add("FamilySize", typeof(Double));
                selectionGroup = -1;
            }

            if (itemsToCollect.Contains("Date Last Modified"))
            {
                DataColumn dateLastModifiedColumn = dt.Columns.Add("DateLastModified", typeof(String));
                selectionGroup = -1;
            }

            //Here is where items must be obtained via API calls. Statementselect changes from -1 to 0 to later indicate that API usage will be needed.
            if (itemsToCollect.Contains("Revit Version"))
            {
                DataColumn revitVersionColumn = dt.Columns.Add("RevitVersion", typeof(String));
                selectionGroup = 0;
            }

            if (itemsToCollect.Contains("Family Category"))
            {
                DataColumn familyCategoryColumn = dt.Columns.Add("FamilyCategory", typeof(String));
                selectionGroup = 0;
            }

            //From here, the IF statments indicate the files will need to be opened and API calls will be used, resulting in a slow data collection. Statementselect becomes 1
            if (itemsToCollect.Contains("Family Types"))
            {
                DataColumn familyTypeColumn = dt.Columns.Add("FamilyType", typeof(String));
                selectionGroup = 1;
            }

            if (itemsToCollect.Contains("Parameter Name"))
            {
                DataColumn parameterNameColumn = dt.Columns.Add("ParameterName", typeof(String));
                selectionGroup = 1;
            }

            if (itemsToCollect.Contains("Parameter Group"))
            {
                DataColumn parameterGroupColumn = dt.Columns.Add("ParameterGroup", typeof(String));
                selectionGroup = 1;
            }

            if (itemsToCollect.Contains("Parameter Type"))
            {
                DataColumn parameterTypeColumn = dt.Columns.Add("ParameterType", typeof(String));
                selectionGroup = 1;
            }

            if (itemsToCollect.Contains("Parameter Value"))
            {
                //If the parameter value is to be collected, it could be either an integer, double, or string, so create all three columns anyways
                DataColumn parameterValueIntegerColumn = dt.Columns.Add("ParameterValueInteger", typeof(Int32));
                parameterValueIntegerColumn.AllowDBNull = true;
                DataColumn parameterValueDoubleColumn = dt.Columns.Add("ParameterValueDouble", typeof(Double));
                parameterValueDoubleColumn.AllowDBNull = true;
                DataColumn parameterValueStringColumn = dt.Columns.Add("ParameterValueString", typeof(String));
                parameterValueStringColumn.AllowDBNull = true;
                selectionGroup = 1;
            }

            if (itemsToCollect.Contains("Parameter Is Instance"))
            {
                DataColumn parameterIsInstanceColumn = dt.Columns.Add("ParameterIsInstance", typeof(Boolean));
                selectionGroup = 1;
            }

            if (itemsToCollect.Contains("Parameter Is Shared"))
            {
                DataColumn parameterIsSharedColumn = dt.Columns.Add("ParameterIsShared", typeof(Boolean));
                selectionGroup = 1;
            }

            if (itemsToCollect.Contains("Parameter GUID"))
            {
                DataColumn parameterGUIDColumn = dt.Columns.Add("ParameterGUID", typeof(String));
                selectionGroup = 1;
            }

            //Cycle through the file paths obtained from the open UI
            foreach (string filePath in uiForm.adminDataGFFFiles)
            {
                //Increment the progress bar of the open UI
                uiForm.adminDataGFFDataProgressBar.PerformStep();
                // If selectionGroup is -1, no use of the API will be used
                if (selectionGroup == -1)
                {
                    DataRow row = dt.NewRow();
                    if (dt.Columns.Contains("FamilyName"))
                    {
                        row["FamilyName"] = GeneralOperations.GetFileName(filePath);
                    }

                    if (dt.Columns.Contains("FamilySize"))
                    {
                        row["FamilySize"] = GeneralOperations.GetFileSize(filePath);
                    }

                    if (dt.Columns.Contains("DateLastModified"))
                    {
                        row["DateLastModified"] = GeneralOperations.GetFileLastModifiedDate(filePath);
                    }

                    dt.Rows.Add(row);
                }

                //If selectionGroup is 0, then the API will be used, resulting in slower processing
                else if (selectionGroup == 0)
                {
                    //Get the Revit version year of the file
                    int rvtNumber = RVTOperations.GetRevitNumber(filePath);
                    //Check to see if the GetRevitNumber did not return 0 (could not be determined), and that the saved in version is not newer that the one running.
                    if (rvtNumber != 0 && Convert.ToInt32(uiApp.Application.VersionNumber) >= rvtNumber)
                    {
                        DataRow row = dt.NewRow();

                        if (dt.Columns.Contains("FamilyName"))
                        {
                            row["FamilyName"] = GeneralOperations.GetFileName(filePath);
                        }

                        if (dt.Columns.Contains("FamilySize"))
                        {
                            row["FamilySize"] = GeneralOperations.GetFileSize(filePath);
                        }

                        if (dt.Columns.Contains("DateLastModified"))
                        {
                            row["DateLastModified"] = GeneralOperations.GetFileLastModifiedDate(filePath);
                        }

                        if (dt.Columns.Contains("RevitVersion"))
                        {
                            row["RevitVersion"] = RVTOperations.GetRevitVersion(filePath);
                        }

                        RVTDocument doc = RVTOperations.OpenRevitFile(uiApp, filePath);
                        if (dt.Columns.Contains("FamilyCategory") && doc.IsFamilyDocument)
                        {
                            row["FamilyCategory"] = RVTOperations.GetRevitFamilyCategory(doc);
                        }

                        doc.Close(false);
                        dt.Rows.Add(row);
                    }
                }

                //If selectionGroup is 1, then the API will be used, and the file must be opened to obtain the information
                else if (selectionGroup == 1)
                {
                    //Verifying Revit version year
                    int rvtNumber = RVTOperations.GetRevitNumber(filePath);
                    if (rvtNumber != 0 && Convert.ToInt32(uiApp.Application.VersionNumber) >= rvtNumber)
                    {
                        //Open the Revit file
                        RVTDocument doc = RVTOperations.OpenRevitFile(uiApp, filePath);
                        //Ensure it is a family document
                        if (doc.IsFamilyDocument)
                        {
                            //Get the family manager of the family file
                            FamilyManager famMan = doc.FamilyManager;
                            //Get the set of family types from the family file
                            FamilyTypeSet familyTypes = famMan.Types;

                            Transaction t1 = new Transaction(doc, "CycleFamilyTypes");
                            t1.Start();
                            FailureHandlingOptions failureHandlingOptions = t1.GetFailureHandlingOptions();
                            failureHandlingOptions.SetFailuresPreprocessor(new RVTFailuresPreprocessor());
                            t1.SetFailureHandlingOptions(failureHandlingOptions);

                            //For each family type...
                            foreach (FamilyType famType in familyTypes)
                            {
                                //Create a subtransaction to change the current family type in the family manager
                                SubTransaction s1 = new SubTransaction(doc);
                                s1.Start();

                                famMan.CurrentType = famType;
                                s1.Commit();

                                //Get each parameter from the current family type, and create a row for each parameter
                                foreach (FamilyParameter param in famMan.GetParameters())
                                {
                                    DataRow row = dt.NewRow();
                                    if (dt.Columns.Contains("FamilyName"))
                                    {
                                        try { row["FamilyName"] = GeneralOperations.GetFileName(filePath); }
                                        catch { row["FamilyName"] = ""; }
                                    }
                                    if (dt.Columns.Contains("FamilySize"))
                                    {
                                        try { row["FamilySize"] = GeneralOperations.GetFileSize(filePath); }
                                        catch { row["FamilySize"] = 0; }
                                    }
                                    if (dt.Columns.Contains("DateLastModified"))
                                    {
                                        try { row["DateLastModified"] = GeneralOperations.GetFileLastModifiedDate(filePath); }
                                        catch { row["DateLastModified"] = ""; }
                                    }
                                    if (dt.Columns.Contains("RevitVersion"))
                                    {
                                        try { row["RevitVersion"] = RVTOperations.GetRevitVersion(filePath); }
                                        catch { row["RevitVersion"] = ""; }
                                    }
                                    if (dt.Columns.Contains("FamilyCategory"))
                                    {
                                        try { row["FamilyCategory"] = RVTOperations.GetRevitFamilyCategory(doc); }
                                        catch { row["FamilyCategory"] = ""; }
                                    }
                                    if (dt.Columns.Contains("FamilyType"))
                                    {
                                        try { row["FamilyType"] = famType.Name.ToString(); }
                                        catch { row["FamilyType"] = ""; }
                                    }

                                    if (dt.Columns.Contains("ParameterName"))
                                    {
                                        try { row["ParameterName"] = param.Definition.Name; }
                                        catch { row["ParameterName"] = ""; }
                                    }

                                    if (dt.Columns.Contains("ParameterGroup"))
                                    {
                                        try { row["ParameterGroup"] = param.Definition.ParameterGroup.ToString(); }
                                        catch { row["ParameterGroup"] = ""; }
                                    }

                                    if (dt.Columns.Contains("ParameterType"))
                                    {
                                        try { row["ParameterType"] = param.Definition.ParameterType.ToString(); }
                                        catch { row["ParameterType"] = ""; }
                                    }

                                    //Here is where the attempts to get the parameter values begins. Get the StorageType of the parameter, then determine which column the data goes in
                                    if (dt.Columns.Contains("ParameterValueInteger") && param.StorageType == StorageType.Integer)
                                    {
                                        try { row["ParameterValueInteger"] = famType.AsInteger(param); }
                                        catch { row["ParameterValueInteger"] = 0; }
                                    }

                                    if (dt.Columns.Contains("ParameterValueDouble") && param.StorageType == StorageType.Double)
                                    {
                                        try { row["ParameterValueDouble"] = famType.AsDouble(param); }
                                        catch { row["ParameterValueDouble"] = 0; }
                                    }

                                    if (dt.Columns.Contains("ParameterValueString") && param.StorageType == StorageType.ElementId)
                                    {
                                        //Instead of getting the ElementID, which is limited in value to someone reading the data, get the element name instead
                                        try { row["ParameterValueString"] = doc.GetElement(famType.AsElementId(param)).Name; }
                                        catch { row["ParameterValueString"] = ""; }
                                    }

                                    if (dt.Columns.Contains("ParameterValueString") && param.StorageType == StorageType.String)
                                    {
                                        //First, try getting the parameter string as a string. If that fails, try getting it as a ValueString
                                        try
                                        {
                                            string paramValue = famType.AsString(param);
                                            row["ParameterValueString"] = paramValue;
                                        }
                                        catch
                                        {
                                            try
                                            {
                                                string paramValue = famType.AsValueString(param).ToString();
                                                row["ParameterValueString"] = paramValue;
                                            }
                                            catch
                                            {
                                                row["ParameterValueString"] = "";
                                            }
                                        }
                                    }

                                    if (dt.Columns.Contains("ParameterIsInstance"))
                                    {
                                        try { row["ParameterIsInstance"] = param.IsInstance; }
                                        catch { row["ParameterIsInstance"] = false; }
                                    }

                                    if (dt.Columns.Contains("ParameterIsShared"))
                                    {
                                        try { row["ParameterIsShared"] = param.IsShared; }
                                        catch { row["ParameterIsShared"] = false; }
                                    }

                                    if (dt.Columns.Contains("ParameterGUID"))
                                    {
                                        try { row["ParameterGUID"] = param.GUID.ToString(); }
                                        catch { row["ParameterGUID"] = ""; }
                                    }
                                    //Add the datatable row to the datatable
                                    dt.Rows.Add(row);
                                }
                            }
                            //Commit the primary transaction
                            t1.Commit();
                        }
                        //Close the document, do not save
                        doc.Close(false);
                    }
                }
                else
                {
                    //selectionGroup is still -2, and thus nothing was selected. Do nothing.
                    continue;
                }
            }

            //Set the datatable of the open UI to the one with the obtained data
            uiForm.adminDataGFFDataTable = dt;
            //Indicate the collection is done with the label
            uiForm.adminDataGFFCollectDataWaitLabel.Text = "Done!";
            //Hide the progress bar when done, and clear out the list of data items to collect
            uiForm.adminDataGFFDataProgressBar.Visible = false;
            uiForm.adminDataGFFItemsToCollect.Clear();
        }
Example #5
0
        //Here, the families or types will be made
        private static void CreateFamilyTypesFromTable(UIApplication uiApp, MainUI uiForm, string saveDirectory, DataGridView dgv, SaveAsOptions saveAsOptions, string familyFileToUse)
        {
            //First thing to do is open the family document and access the FamilyManager
            RVTDocument   famDoc = RVTOperations.OpenRevitFile(uiApp, familyFileToUse);
            FamilyManager famMan = famDoc.FamilyManager;

            string tempFamilyPath = "";

            //Next, delete all of the family types except one from the family and save the file off for temporary use
            try
            {
                //This is in a Try/Catch becuse there is a possibility for failure
                RVTOperations.DeleteFamilyTypes(famDoc, famMan);
                tempFamilyPath = saveDirectory + "\\" + String.Format(famDoc.Title).Replace(".rfa", "") + "_temp.rfa";
                famDoc.SaveAs(tempFamilyPath, saveAsOptions);
            }
            catch { MessageBox.Show("Could not save out a temporary family file to the location where the families are to be saved. Verify the location is not read-only."); }
            //Ensure the open family gets closed
            finally { famDoc.Close(); }

            //Then, reopen the temporary family if it exists
            if (tempFamilyPath != "")
            {
                //Get all of the parameters in the family and add them to a dictionary indexed by the parameter name
                RVTDocument        newFamDoc  = RVTOperations.OpenRevitFile(uiApp, tempFamilyPath);
                FamilyManager      newFamMan  = newFamDoc.FamilyManager;
                FamilyParameterSet parameters = newFamMan.Parameters;
                Dictionary <string, FamilyParameter> famParamDict = new Dictionary <string, FamilyParameter>();
                foreach (FamilyParameter param in parameters)
                {
                    famParamDict.Add(param.Definition.Name, param);
                }

                //These integer values will be used to increment loops
                int rowsCount    = dgv.Rows.Count;
                int columnsCount = dgv.Columns.Count;

                //Keep track of what family types were made so the script can later delete out the one that pre-existed in the family but is not needed.
                List <string> familyTypesMade = new List <string>();
                //If the user decide to make types per row instead of families per row...
                if (uiForm.multiCatCFFEFamilyCreationComboBox.SelectedItem.ToString() == "Combine Types (1 File)")
                {
                    //The progress bar should be prepared using the number of rows multipled by the number of columns for the number of steps to perform. This gives a better indication of progress than doing it based on the number of rows
                    uiForm.multiCatCFFEFamiliesProgressBar.Minimum = 0;
                    uiForm.multiCatCFFEFamiliesProgressBar.Maximum = (rowsCount - 1) * (columnsCount - 1);
                    uiForm.multiCatCFFEFamiliesProgressBar.Step    = 1;
                    uiForm.multiCatCFFEFamiliesProgressBar.Visible = true;

                    //Open the transaction
                    Transaction t2 = new Transaction(newFamDoc, "MakeNewTypes");
                    t2.Start();
                    //The maximum of rows is greater than the maximum index value by 1, so this uses < to stop before an index out of range exception occurs. Also, the index starts at 1 instead of 0 because the top row is the info about the data type
                    for (int i = 1; i < rowsCount; i++)
                    {
                        //The type name is in the first column.
                        string newTypeName = dgv.Rows[i].Cells[0].Value.ToString();
                        //This operation will get the existing type names in the family as new ones are added to avoide duplication
                        Dictionary <string, FamilyType> existingTypeNames = RVTOperations.GetFamilyTypeNames(newFamMan);
                        //If the type does not exist in the dictionary...
                        if (!existingTypeNames.Keys.Contains(newTypeName))
                        {
                            //Create a new type and add it to the list of types made
                            FamilyType newType = newFamMan.NewType(newTypeName);
                            newFamMan.CurrentType = newType;
                            familyTypesMade.Add(newType.Name);
                        }
                        else
                        {
                            //Otherwise set the current type in the family manager to the pre-existing one with the name of the one to be created
                            newFamMan.CurrentType = existingTypeNames[newTypeName];
                            //Add that one to the list of types made, though it wasn't actually made
                            familyTypesMade.Add(newFamMan.CurrentType.Name);
                        }

                        //Next, cycle through the columns, again starting with the column at index 1 and incrementing the columns to one less than the number of columns
                        for (int j = 1; j < columnsCount; j++)
                        {
                            //Get the parameter name from the first column's header text
                            string paramName = dgv.Columns[j].HeaderText;
                            //Get the storage type from the first row
                            string paramStorageTypeString = dgv.Rows[0].Cells[j].Value.ToString();
                            var    paramValue             = dgv.Rows[i].Cells[j].Value;
                            //Assuming the parameter value is set...
                            if (paramValue.ToString() != "")
                            {
                                //Set the parameter given the information about the FamilyManager, parameter definition, parameter type, parameter data type, value to set, and whether or not to convert inches to feet. Because this script relies on inch input, this needs done to convert to feet used by the Revit API
                                FamilyParameter param     = famParamDict[paramName];
                                ParameterType   paramType = param.Definition.ParameterType;
                                RVTOperations.SetFamilyParameterValue(newFamMan, param, paramType, paramStorageTypeString, paramValue, true);
                            }
                            //Step forward the progress bar for this parameter
                            uiForm.multiCatCFFEFamiliesProgressBar.PerformStep();
                        }
                    }
                    t2.Commit();

                    //In another transaction, delete the pre-existing type used to generate the other types
                    Transaction t3 = new Transaction(newFamDoc, "DeleteOldTypes");
                    t3.Start();
                    foreach (FamilyType type in newFamMan.Types)
                    {
                        //Set the current type to the one with the pre-existing type name and delete it
                        if (!familyTypesMade.Contains(type.Name))
                        {
                            newFamMan.CurrentType = type;
                            newFamMan.DeleteCurrentType();
                        }
                    }
                    t3.Commit();

                    //Save out the family to the directory and remove the _temp from the name
                    newFamDoc.SaveAs(saveDirectory + "\\" + String.Format(newFamDoc.Title).Replace("_temp", "") + ".rfa", saveAsOptions);
                    newFamDoc.Close();
                }

                //If the user chose to make a family file per row, the family will be saved out multiple times
                else if (uiForm.multiCatCFFEFamilyCreationComboBox.SelectedItem.ToString() == "1 Family Per Type (Multiple Files)")
                {
                    //Set the number of steps for the progress bar to the number of rows with families to make
                    uiForm.multiCatCFFEFamiliesProgressBar.Minimum = 0;
                    uiForm.multiCatCFFEFamiliesProgressBar.Maximum = rowsCount - 1;
                    uiForm.multiCatCFFEFamiliesProgressBar.Step    = 1;
                    uiForm.multiCatCFFEFamiliesProgressBar.Visible = true;

                    //Again, starting at row index 1 because the first is the information about the data types. This loop will produce a family per row. One familly will be opened and saved off multiple times, performing the process of deleting types, adding a default type, and setting parameters before each save
                    for (int i = 1; i < rowsCount; i++)
                    {
                        Transaction t2 = new Transaction(newFamDoc, "MakeNewTypes");
                        t2.Start();
                        //Create a new type using the name of the type in the first column
                        FamilyType newType = newFamMan.NewType(dgv.Rows[i].Cells[0].Value.ToString());
                        //Clean up the family file name by leaving everything that does not pass the regular expression in CleanFileName

                        string saveName = GeneralOperations.CleanFileName(newType.Name);
                        if (saveName != "")
                        {
                            //Assuming nothing went wrong modifying the family name...
                            newFamMan.CurrentType = newType;
                            //Cycle through the columns to set the parameter values this performs the same operations as those above for making 1 family with multiple types
                            for (int j = 1; j < columnsCount; j++)
                            {
                                string paramName = dgv.Columns[j].HeaderText;
                                string paramStorageTypeString = dgv.Rows[0].Cells[j].Value.ToString();
                                var    paramValue             = dgv.Rows[i].Cells[j].Value;
                                if (paramValue.ToString() != "")
                                {
                                    FamilyParameter param     = famParamDict[paramName];
                                    ParameterType   paramType = param.Definition.ParameterType;
                                    RVTOperations.SetFamilyParameterValue(newFamMan, param, paramType, paramStorageTypeString, paramValue, true);
                                }
                            }
                            t2.Commit();

                            //Again, do another transaction to delete the pre-existing type
                            Transaction t3 = new Transaction(newFamDoc, "DeleteOldTypes");
                            t3.Start();
                            foreach (FamilyType type in newFamMan.Types)
                            {
                                newFamMan.CurrentType = type;
                                if (newFamMan.CurrentType.Name != newType.Name)
                                {
                                    newFamMan.DeleteCurrentType();
                                }
                            }
                            t3.Commit();
                            //Save out the family and continue the loop
                            newFamDoc.SaveAs(saveDirectory + "\\" + saveName + ".rfa", saveAsOptions);
                            uiForm.multiCatCFFEFamiliesProgressBar.PerformStep();
                        }
                    }
                    // The family document is finally closed after saving off itself for each row
                    newFamDoc.Close();
                }
                else
                {
                    MessageBox.Show("No Creation Method was selected");
                }

                //Delete the _temp file
                File.Delete(tempFamilyPath);

                //Clean up the backup files too
                List <string> backupFiles = GeneralOperations.GetAllRvtBackupFamilies(uiForm.multiCatCFFEFamilySaveLocation, false);
                GeneralOperations.CleanRfaBackups(backupFiles);
            }
        }
Example #6
0
        public AdminDataGBDVRequest(UIApplication uiApp, String text)
        {
            MainUI    uiForm = BARevitTools.Application.thisApp.newMainUi;
            DataTable dt     = new DataTable();

            uiForm.adminDataGBDVWaitLabel.Text    = "Please Wait...";
            uiForm.adminDataGBDVWaitLabel.Visible = true;

            //Begin by getting the Revit version of the BA Details file in the BART properties. This should be lowest supported BART version
            string detailVersion = RVTOperations.GetRevitNumber(BARevitTools.Properties.Settings.Default.RevitProjectBADetails).ToString();
            //Get the last two digits for the year of the BA Details Revit version
            string detailSubVersion = detailVersion.Substring(detailVersion.Length - 2);
            //Get the version of Revit running and then get the last two digits
            string activeSubVersion = uiApp.Application.VersionNumber.Substring(uiApp.Application.VersionNumber.Length - 2);
            //Get the appropriate BA Details file by version number. This only works if the files are named with the A## suffix
            string detailsFile = BARevitTools.Properties.Settings.Default.RevitProjectBADetails.Replace(detailSubVersion, activeSubVersion);

            //Create a new DataTable to collect data.
            dt = new DataTable();
            DataColumn categoryColumn     = dt.Columns.Add("Category", typeof(String)); //View type
            DataColumn divisionSortColumn = dt.Columns.Add("Division", typeof(String)); //BA View Sort 1 Division
            DataColumn typeSortColumn     = dt.Columns.Add("Type", typeof(String));     //BA View Sort 2 Type
            DataColumn nameColumn         = dt.Columns.Add("Name", typeof(String));     //View name

            //Try to open the details file saved in the running version of Revit.
            RVTDocument detailsDoc = null;

            try
            {
                //Open the BA Details file
                detailsDoc = RVTOperations.OpenRevitFile(uiApp, detailsFile);
            }
            catch
            {
                //Assuming the file could not be opened because it does not exist at the expected location, prompt the user to select it.
                MessageBox.Show(String.Format("Could not load the {0} file. Please select the BA Details file to use in the following dialog.", detailsFile));
                try
                {
                    //Generate the file selection dialog
                    string filePath = GeneralOperations.GetFile();
                    detailsDoc = RVTOperations.OpenRevitFile(uiApp, filePath);
                }
                catch {; }
            }

            //Assuming the BA Details was opened, continue
            if (detailsDoc != null)
            {
                List <ViewDrafting> viewsCollection  = new FilteredElementCollector(detailsDoc).OfClass(typeof(ViewDrafting)).WhereElementIsNotElementType().Cast <ViewDrafting>().ToList();
                List <ViewSheet>    sheetsCollection = new FilteredElementCollector(detailsDoc).OfClass(typeof(ViewSheet)).WhereElementIsNotElementType().Cast <ViewSheet>().ToList();

                //Order the views by division, type, and name
                var viewsGroupedQuery =
                    from viewElem in viewsCollection
                    orderby viewElem.GetParameters("BA View Sort 1 Division").First().ToString(), viewElem.GetParameters("BA View Sort 2 Type").First().ToString(), viewElem.Name
                select viewElem;

                //Fill out the DataTable
                foreach (ViewDrafting viewDrafting in viewsGroupedQuery)
                {
                    DataRow row = dt.NewRow();
                    row["Category"] = "View";
                    row["Division"] = viewDrafting.GetParameters("BA View Sort 1 Division").First().AsString();
                    row["Type"]     = viewDrafting.GetParameters("BA View Sort 2 Type").First().AsString();
                    row["Name"]     = viewDrafting.Name;
                    dt.Rows.Add(row);
                }

                //Order the sheets by discipline, division, and name
                var sheetsGroupedQuery =
                    from sheetElem in sheetsCollection
                    orderby sheetElem.GetParameters("BA Sheet Discipline").First().AsString(), sheetElem.GetParameters("BA Sheet Division").First().AsString(), sheetElem.Name
                select sheetElem;

                //Add the sheets to the DataTable
                foreach (ViewSheet viewSheet in sheetsGroupedQuery)
                {
                    DataRow row = dt.NewRow();
                    row["Category"] = "Sheet";
                    row["Division"] = viewSheet.GetParameters("BA Sheet Discipline").First().AsString();
                    row["Type"]     = viewSheet.GetParameters("BA Sheet Division").First().AsString();
                    row["Name"]     = viewSheet.Name;
                    dt.Rows.Add(row);
                }

                uiForm.adminDataGBDVWaitLabel.Text = "Done!";
                detailsDoc.Close(false);

                uiForm.adminDataGBDVDataTable = dt;
            }
        }
Example #7
0
        private void SetParameters(UIApplication uiApp, string familyFile, ExternalDefinition externalDefinition)
        {
            try
            {
                //Get the FileInfo of the family file and then get the LastWriteTime value as a date string in MM/DD/YYYY format
                FileInfo fileInfo     = new FileInfo(familyFile);
                string   lastModified = fileInfo.LastWriteTime.ToShortDateString();

                //Open the family file
                RVTDocument famDoc = RVTOperations.OpenRevitFile(uiApp, familyFile);
                if (famDoc != null)
                {
                    //Get the family manager for the family file
                    FamilyManager famMan = famDoc.FamilyManager;
                    //Get the family parameters and add them to a dictionary indexed by parameter name
                    FamilyParameter famParameter = null;
                    Dictionary <string, FamilyParameter> famParamDict = new Dictionary <string, FamilyParameter>();
                    foreach (FamilyParameter famParam in famMan.Parameters)
                    {
                        famParamDict.Add(famParam.Definition.Name, famParam);
                    }

                    //Get the number of family types because there must be at least one family type to make this work
                    FamilyTypeSet types         = famMan.Types;
                    int           numberOfTypes = types.Size;

                    Transaction t1 = new Transaction(famDoc, "SetParameters");
                    t1.Start();
                    if (numberOfTypes == 0)
                    {
                        //If the number of family types was 0, then one must be made. Thus Default is a family type created
                        try
                        {
                            famMan.NewType("Default");
                        }
                        catch { MessageBox.Show(String.Format("Could not make a default type or find any type for {0}", familyFile)); }
                    }

                    //Once the existence of a family type is confirmed, move on with determining if the version parameter already exists. If it doesn't add the parameter to the family and regenerate the document
                    if (!famParamDict.Keys.Contains(BARevitTools.Properties.Settings.Default.RevitUFVPParameter))
                    {
                        famParameter = famMan.AddParameter(externalDefinition, BuiltInParameterGroup.PG_IDENTITY_DATA, false);
                        famDoc.Regenerate();
                    }
                    else
                    {
                        famParameter = famParamDict[BARevitTools.Properties.Settings.Default.RevitUFVPParameter];
                    }

                    //Check to see if the value for the parameter is equal to the date last modified
                    if (famMan.CurrentType.AsString(famParameter) == lastModified)
                    {
                        //If so, roll back the transaction and just close the file.
                        t1.RollBack();
                        famDoc.Close(false);
                    }
                    else
                    {
                        //Otherwise set the formula of the version parameter to the quote encapsulated date, just like it would appear in Revit, commit it, then save.
                        famMan.SetFormula(famParameter, "\"" + lastModified + "\"");
                        t1.Commit();
                        RVTOperations.SaveRevitFile(uiApp, famDoc, true);
                    }
                }
                else
                {
                    //If the family could not be opened for any reason, let the user know
                    MessageBox.Show(String.Format("{0} could not be opened.", familyFile));
                }
            }
            catch (Exception e)
            {
                MessageBox.Show(e.ToString());
            }
        }
Example #8
0
        public AllCatCFFE1Request(UIApplication uiApp, String text)
        {
            MainUI             uiForm      = BARevitTools.Application.thisApp.newMainUi;
            RVTDocument        doc         = uiApp.ActiveUIDocument.Document;
            DataTable          dt          = new DataTable();
            DataGridView       dgv         = uiForm.multiCatCFFEExcelDGV;
            RVTDocument        famDoc      = RVTOperations.OpenRevitFile(uiApp, Application.thisApp.newMainUi.multiCatSelectedFamilyFile);
            FamilyManager      famMan      = famDoc.FamilyManager;
            FamilyParameterSet famParamSet = famMan.Parameters;

            //The following columns are being added to the DataTable for use in the Excel template creation
            DataColumn paramSelectColumn          = dt.Columns.Add("Parameter Select", typeof(Boolean));
            DataColumn parameterNameColumn        = dt.Columns.Add("Parameter Name", typeof(String));
            DataColumn parameterGroupColumn       = dt.Columns.Add("Parameter Group", typeof(String));
            DataColumn parameterTypeColumn        = dt.Columns.Add("Parameter Type", typeof(String));
            DataColumn parameterStorageTypeColumn = dt.Columns.Add("Parameter Storage Type", typeof(String));

            //For each family parameter, get data associated with it for the DataTable
            foreach (FamilyParameter famParam in famParamSet)
            {
                string paramName        = famParam.Definition.Name;
                string paramGroup       = RVTOperations.GetNameFromBuiltInParameterGroup(famParam.Definition.ParameterGroup);
                string paramType        = famParam.Definition.ParameterType.ToString();
                string paramStorageType = famParam.StorageType.ToString();
                //Verify the parameter being evaluated is not one where the value is an element because that will not be useful without knowing the element ID ahead of time. Also, ensure the parameter is not locked by a formula, and ensure the ParameterType is valid
                if (paramStorageType.ToString() != "ElementId" && famParam.IsDeterminedByFormula == false && famParam.Definition.ParameterType != ParameterType.Invalid)
                {
                    //Pending the pass of the checks, fill out the DataTable with the parameter name, group, type, and data type
                    DataRow row = dt.NewRow();
                    row["Parameter Select"]       = false;
                    row["Parameter Name"]         = paramName;
                    row["Parameter Group"]        = paramGroup;
                    row["Parameter Type"]         = paramType;
                    row["Parameter Storage Type"] = paramStorageType;
                    dt.Rows.Add(row);
                }
            }

            //Bind the DataTable to the DataGridView
            BindingSource bs = new BindingSource();

            bs.DataSource  = dt;
            dgv.DataSource = bs;

            //Format the DataGridView and set the names for its columns so the row values can be retrieved by column name
            dgv.RowHeadersVisible = false;
            dgv.SelectionMode     = DataGridViewSelectionMode.FullRowSelect;
            dgv.Columns["Parameter Select"].Width            = 45;
            dgv.Columns["Parameter Select"].HeaderText       = "Select";
            dgv.Columns["Parameter Select"].Name             = "Parameter Select";
            dgv.Columns["Parameter Name"].Width              = 125;
            dgv.Columns["Parameter Name"].ReadOnly           = true;
            dgv.Columns["Parameter Name"].HeaderText         = "Name";
            dgv.Columns["Parameter Name"].Name               = "Parameter Name";
            dgv.Columns["Parameter Group"].Width             = 75;
            dgv.Columns["Parameter Group"].ReadOnly          = true;
            dgv.Columns["Parameter Group"].HeaderText        = "Group";
            dgv.Columns["Parameter Group"].Name              = "Parameter Group";
            dgv.Columns["Parameter Type"].Width              = 100;
            dgv.Columns["Parameter Type"].ReadOnly           = true;
            dgv.Columns["Parameter Type"].HeaderText         = "Param Type";
            dgv.Columns["Parameter Type"].Name               = "Parameter Type";
            dgv.Columns["Parameter Storage Type"].Width      = 100;
            dgv.Columns["Parameter Storage Type"].ReadOnly   = true;
            dgv.Columns["Parameter Storage Type"].HeaderText = "Data Format";
            dgv.Columns["Parameter Storage Type"].Name       = "Parameter Storage Type";

            //Sort by the Parameter Name column
            dgv.Sort(dgv.Columns["Parameter Name"], ListSortDirection.Ascending);
            foreach (DataGridViewColumn column in dgv.Columns)
            {
                column.SortMode = DataGridViewColumnSortMode.NotSortable;
            }
            //Close the family
            famDoc.Close(false);
        }
Example #9
0
        public AdminFamiliesBAPRequest(UIApplication uiApp, String text)
        {
            MainUI uiForm = BARevitTools.Application.thisApp.newMainUi;

            uiForm.adminFamiliesBAPDoneLabel.Visible = false;
            RVTDocument   doc           = uiApp.ActiveUIDocument.Document;
            SaveAsOptions saveAsOptions = new SaveAsOptions();

            saveAsOptions.Compact               = true;
            saveAsOptions.MaximumBackups        = 3;
            saveAsOptions.OverwriteExistingFile = true;
            Dictionary <string, ExternalDefinition> sharedParameterDefinitions = new Dictionary <string, ExternalDefinition>();

            //Determine if the shared parameters file is accessible and try to get the shared parameters so their definition names and definitions could be added to a dictionary
            bool sharedParametersIsAccessible = true;

            try
            {
                DefinitionGroups sharedParameterGroups = uiApp.Application.OpenSharedParameterFile().Groups;
                foreach (DefinitionGroup group in sharedParameterGroups)
                {
                    foreach (ExternalDefinition definition in group.Definitions)
                    {
                        if (!sharedParameterDefinitions.Keys.Contains(definition.Name))
                        {
                            sharedParameterDefinitions.Add(definition.Name, definition);
                        }
                    }
                }
            } //If the access fails, then the shared parameters file was not accessible.
            catch { sharedParametersIsAccessible = false; }

            //Get the number of families to process from the DataGridView
            int filesToProcess = 0;

            foreach (DataGridViewRow rowCount in uiForm.adminFamiliesBAPFamiliesDGV.Rows)
            {
                if (rowCount.Cells["Family Select"].Value.ToString() == "True")
                {
                    filesToProcess++;
                }
            }

            //Prepare the progress bar
            uiForm.adminFamiliesBAPProgressBar.Value   = 0;
            uiForm.adminFamiliesBAPProgressBar.Minimum = 0;
            uiForm.adminFamiliesBAPProgressBar.Maximum = filesToProcess;
            uiForm.adminFamiliesBAPProgressBar.Step    = 1;
            uiForm.adminFamiliesBAPProgressBar.Visible = true;

            //Stop any edits to the DataGridView of parameters to add
            uiForm.adminFamiliesBAPParametersDGV.EndEdit();
            try
            {
                foreach (DataGridViewRow row in uiForm.adminFamiliesBAPFamiliesDGV.Rows)
                {
                    try
                    {
                        //If the checkbox for including the family in the process is not null, continue
                        if (row.Cells["Family Select"].Value != null)
                        {
                            //Grab the file path for the family
                            string        filePath      = row.Cells["Family Path"].Value.ToString();
                            List <string> famParamNames = new List <string>();
                            //If the checkbox is checked to select the family
                            if (row.Cells["Family Select"].Value.ToString() == "True")
                            {
                                //Open the family document
                                RVTDocument famDoc = RVTOperations.OpenRevitFile(uiApp, filePath);
                                if (famDoc.IsFamilyDocument)
                                {
                                    //Grab the family manager and make a list of parameter names already in the family
                                    FamilyManager familyManager = famDoc.FamilyManager;
                                    foreach (FamilyParameter famParam in familyManager.Parameters)
                                    {
                                        if (!famParamNames.Contains(famParam.Definition.Name))
                                        {
                                            famParamNames.Add(famParam.Definition.Name);
                                        }
                                        else
                                        {
                                            continue;
                                        }
                                    }

                                    foreach (DataGridViewRow newParamRow in uiForm.adminFamiliesBAPParametersDGV.Rows)
                                    {
                                        try
                                        {
                                            //Get the name of the parameter, group, and type of parameter to add
                                            string name = newParamRow.Cells["Parameter Name"].Value.ToString();
                                            BuiltInParameterGroup group = RVTOperations.GetBuiltInParameterGroupFromString(newParamRow.Cells["Parameter Group"].Value.ToString());
                                            ParameterType         type  = RVTOperations.GetParameterTypeFromString(newParamRow.Cells["Parameter Type"].Value.ToString());
                                            //Determine if the checkbox for making the parameter an instance parameter is checked
                                            bool isInstance = false;
                                            try
                                            {
                                                isInstance = Convert.ToBoolean(newParamRow.Cells["Parameter Is Instance"].Value.ToString());
                                            }
                                            catch { isInstance = false; }

                                            //Determine if the read-only checkbox for the parameter being a shared parameter is checked.
                                            bool isShared = false;
                                            try
                                            {
                                                isShared = Convert.ToBoolean(newParamRow.Cells["Parameter Is Shared"].Value.ToString());
                                            }
                                            catch { isShared = false; }

                                            //If the parameter is shared, and the parameter file is still accessible, and the family does not already contain a parameter with that name, continue
                                            if (isShared == true && sharedParametersIsAccessible == true && !famParamNames.Contains(name))
                                            {
                                                using (Transaction t = new Transaction(famDoc, "Add Parameter"))
                                                {
                                                    t.Start();
                                                    //Get the parameter definition from the dictionary of shared parameters, then add it to the family
                                                    ExternalDefinition definition = sharedParameterDefinitions[newParamRow.Cells["Parameter Name"].Value.ToString()];
                                                    FamilyParameter    newParam   = familyManager.AddParameter(definition, group, isInstance);
                                                    try
                                                    {
                                                        //Try to assign the parameter value if one is to be assigned
                                                        if (newParamRow.Cells["Parameter Value"].Value != null)
                                                        {
                                                            //If the number of types is greater than 0, cycle through them
                                                            if (familyManager.Types.Size > 0)
                                                            {
                                                                foreach (FamilyType familyType in familyManager.Types)
                                                                {
                                                                    //For each type, make a subtransaction
                                                                    SubTransaction s1 = new SubTransaction(famDoc);
                                                                    s1.Start();
                                                                    try
                                                                    {
                                                                        //Then set the family type as current
                                                                        familyManager.CurrentType = familyType;
                                                                        //Attempt to set the parameter value
                                                                        RVTOperations.SetFamilyParameterValue(familyManager, newParam, RVTOperations.SetParameterValueFromString(newParamRow.Cells["Parameter Type"].Value.ToString(), newParamRow.Cells["Parameter Value"].Value));
                                                                        s1.Commit();
                                                                    }
                                                                    catch
                                                                    {
                                                                        //If that fails, let the user know and break out of the loop
                                                                        MessageBox.Show(String.Format("Could not assign value {0} to parameter {1} for type {2} in family {3}.", newParamRow.Cells["Parameter Value"], newParamRow.Cells["Parameter Name"], familyType.Name, row.Cells["Family Name"]));
                                                                        break;
                                                                    }
                                                                }
                                                            }
                                                            else
                                                            {
                                                                //If there was was no family types in the family, just set it for the default one
                                                                RVTOperations.SetFamilyParameterValue(familyManager, newParam, RVTOperations.SetParameterValueFromString(newParamRow.Cells["Parameter Type"].Value.ToString(), newParamRow.Cells["Parameter Value"].Value));
                                                            }
                                                        }
                                                    }
                                                    catch
                                                    {
                                                        //If assignment fails, let the user know the parameter value, parameter name, and the family where the failure occured.
                                                        MessageBox.Show(String.Format("Could not assign value {0} to parameter {1} for family {2}", newParamRow.Cells["Parameter Value"], newParamRow.Cells["Parameter Name"], row.Cells["Family Name"]));
                                                    }
                                                    t.Commit();
                                                }
                                            }
                                            else if (isShared == true && sharedParametersIsAccessible == false && !famParamNames.Contains(name))
                                            {
                                                //If the shared parameter file could not be accessed, let the user know
                                                MessageBox.Show(String.Format("Could not set the shared parameter {0} because the shared parameters file for this project could not be found. " +
                                                                              "Verify the shared parameters file is mapped correctly.", name));
                                            }
                                            else if (isShared != true && !famParamNames.Contains(name))
                                            {
                                                //Otherwise, just make a standard parameter
                                                using (Transaction t = new Transaction(famDoc, "Add Parameter"))
                                                {
                                                    t.Start();
                                                    FamilyParameter newParam = familyManager.AddParameter(name, group, type, isInstance);
                                                    try
                                                    {
                                                        if (newParamRow.Cells["Parameter Value"].Value != null)
                                                        {
                                                            RVTOperations.SetFamilyParameterValue(familyManager, newParam, RVTOperations.SetParameterValueFromString(newParamRow.Cells["Parameter Type"].Value.ToString(), newParamRow.Cells["Parameter Value"].Value));
                                                        }
                                                    }
                                                    catch { continue; }
                                                    t.Commit();
                                                }
                                            }
                                            else
                                            {
                                                //If all other conditions were not met, then the parameter already exists.
                                                MessageBox.Show(String.Format("Could not make parameter '{0}' for {1} because it already exists.", name, famDoc.Title));
                                            }
                                        }
                                        catch { continue; }
                                        finally
                                        {
                                            //Save the family
                                            ModelPath modelPath = ModelPathUtils.ConvertUserVisiblePathToModelPath(filePath);
                                            famDoc.SaveAs(filePath, saveAsOptions);
                                        }
                                    }
                                }
                                //Close the family
                                famDoc.Close(false);
                            }
                            else
                            {
                                continue;
                            }
                            //Step forward the progress bar
                            uiForm.adminFamiliesBAPProgressBar.PerformStep();
                        }
                    }
                    catch
                    {
                        MessageBox.Show("The family could not be opened, likely due to being saved in a newer version of Revit");
                    }
                }
            }
            catch (Exception e)
            {
                MessageBox.Show(e.ToString());
            }
            finally
            {
                //Clean up the backups when done
                GeneralOperations.CleanRfaBackups(uiForm.adminFamiliesBAPFamilyDirectory);
            }
            uiForm.adminFamiliesBAPProgressBar.Visible = false;
            uiForm.adminFamiliesBAPDoneLabel.Visible   = true;
            uiForm.Update();
        }
Example #10
0
        public MaterialsCMSRequest(UIApplication uiApp, String text)
        {
            MainUI        uiForm          = BARevitTools.Application.thisApp.newMainUi;
            ProgressBar   progressBar     = uiForm.materialsCMSExcelCreateSymbolsProgressBar;
            DataGridView  dgv             = uiForm.materialsCMSExcelDataGridView;
            int           rowsCount       = dgv.Rows.Count;
            int           columnsCount    = dgv.Columns.Count;
            List <string> familyTypesMade = new List <string>();

            //Prepare the progress bar. The column count is one less because the first column is the column for family type names
            progressBar.Minimum = 0;
            progressBar.Maximum = (rowsCount) * (columnsCount - 1);
            progressBar.Step    = 1;
            progressBar.Visible = true;

            RVTDocument doc = uiApp.ActiveUIDocument.Document;

            //Reset the progress bar
            uiForm.materialsCMSExcelCreateSymbolsProgressBar.Value = 0;

            //First, try to use the family from the project. If that fails, use the family file
            Family familyToUse = RVTGetElementsByCollection.FamilyByFamilyName(uiApp, Path.GetFileNameWithoutExtension(Properties.Settings.Default.RevitFamilyMaterialsCMSSymbIdMaterialSchedule));

            //Assuming nothing went to hell in the process of loading one famiy...
            if (familyToUse != null)
            {
                //Save out the family to use
                RVTDocument tempFamDoc = doc.EditFamily(familyToUse);
                RVTOperations.SaveRevitFile(uiApp, tempFamDoc, @"C:\Temp\" + tempFamDoc.Title, true);

                //Open the family to use and get its FamilyManager
                RVTDocument   famDoc = RVTOperations.OpenRevitFile(uiApp, @"C:\Temp\" + Path.GetFileName(Properties.Settings.Default.RevitFamilyMaterialsCMSSymbIdMaterialSchedule));
                FamilyManager famMan = famDoc.FamilyManager;

                //Get the parameters from the Family Manager and add them to a dictionary
                FamilyParameterSet parameters = famMan.Parameters;
                Dictionary <string, FamilyParameter> famParamDict = new Dictionary <string, FamilyParameter>();
                foreach (FamilyParameter param in parameters)
                {
                    famParamDict.Add(param.Definition.Name, param);
                }

                //Start a new transaction to make the new family types in the family to use
                using (Transaction t1 = new Transaction(famDoc, "MakeNewTypes"))
                {
                    t1.Start();
                    //Cycle through the rows in the dgv
                    for (int i = 0; i < rowsCount; i++)
                    {
                        //The first column cell will be the type name
                        string newTypeName = dgv.Rows[i].Cells[0].Value.ToString();
                        //Get the family type names in the family
                        Dictionary <string, FamilyType> existingTypeNames = RVTOperations.GetFamilyTypeNames(famMan);
                        //If the family to make from the DGV does not exist in the dictionary keys...
                        if (!existingTypeNames.Keys.Contains(newTypeName))
                        {
                            //Make the family type and add it to the list of types made
                            FamilyType newType = famMan.NewType(newTypeName);
                            famMan.CurrentType = newType;
                            familyTypesMade.Add(newType.Name);
                        }
                        else
                        {
                            //If the type exists, set the current type it from the dictionary and add it to the list of types made
                            famMan.CurrentType = existingTypeNames[newTypeName];
                            familyTypesMade.Add(famMan.CurrentType.Name);
                        }

                        //Next, evaluate the columns that contain parameters
                        for (int j = 1; j < columnsCount; j++)
                        {
                            //The parameter names will be retrieved from the column HeaderText property
                            string paramName = dgv.Columns[j].HeaderText;
                            //Meanwhile the parameter value will come from the DGV cells
                            var paramValue = dgv.Rows[i].Cells[j].Value;

                            try
                            {
                                //If the parameter dictionary contains the parameter and the value to assign it is not empty, continue.
                                if (paramValue.ToString() != "" && famParamDict.Keys.Contains(paramName))
                                {
                                    //Get the family parameter and check if it is locked by a formula
                                    FamilyParameter param = famParamDict[paramName];
                                    if (!param.IsDeterminedByFormula)
                                    {
                                        //If it is not locked by a formula, set the parameter
                                        ParameterType paramType = param.Definition.ParameterType;
                                        RVTOperations.SetFamilyParameterValue(famMan, param, paramValue);
                                    }
                                }
                            }
                            catch
                            {; }
                            finally
                            {
                                //Always perform the step to indicate the progress.
                                progressBar.PerformStep();
                            }
                        }
                    }
                    t1.Commit();
                }

                //Use another transaction to delete the types that were not needed
                using (Transaction t2 = new Transaction(famDoc, "DeleteOldTypes"))
                {
                    t2.Start();
                    //Cycle through the family types and determine if it is in the list of types made
                    foreach (FamilyType type in famMan.Types)
                    {
                        if (!familyTypesMade.Contains(type.Name))
                        {
                            //If the type is not in the list of types made, delete it from the family file
                            famMan.CurrentType = type;
                            famMan.DeleteCurrentType();
                        }
                    }
                    t2.Commit();
                }

                //Save the family document at this point as all of the types and their parameters have been set
                famDoc.Close(true);

                using (Transaction t3 = new Transaction(doc, "LoadFamily"))
                {
                    t3.Start();
                    doc.LoadFamily(@"C:\Temp\" + Path.GetFileName(Properties.Settings.Default.RevitFamilyMaterialsCMSSymbIdMaterialSchedule), new RVTFamilyLoadOptions(), out Family loadedFamily);
                    t3.Commit();
                }

                //Get the drafting view type in the project for BA Drafting View, else just get the first drafting view type
                ViewDrafting   placementView    = null;
                var            draftingViews    = new FilteredElementCollector(doc).OfClass(typeof(ViewDrafting)).WhereElementIsNotElementType().ToElements();
                ViewFamilyType draftingViewType = null;
                try
                {
                    //From the view family types collection, get the first one where its name is BA Drafting View
                    draftingViewType = new FilteredElementCollector(doc).OfClass(typeof(ViewFamilyType)).WhereElementIsElementType().ToElements().Where(elem => elem.Name == "BA Drafting View").First() as ViewFamilyType;
                }
                catch
                {
                    //Well, crap. It doesn't exist. Just get the first type then and call it good.
                    draftingViewType = new FilteredElementCollector(doc).OfClass(typeof(ViewFamilyType)).WhereElementIsElementType().ToElements().First() as ViewFamilyType;
                }

                //Start a transaction for making the ID Material View and placing the family symbol types
                using (Transaction t4 = new Transaction(doc, "MakeIDMaterialView"))
                {
                    t4.Start();
                    foreach (ViewDrafting view in draftingViews)
                    {
                        //Find the view named ID Material View, or whatever jibberish someone typed in the CMS text box for the name to use. in the drafting views
                        if (view.Name == "ID Material View" || view.Name == uiForm.materialsCMSSetViewNameTextBox.Text)
                        {
                            //Delete the drafting view
                            doc.Delete(view.Id);
                            doc.Regenerate();
                            break;
                        }
                        else
                        {
                            continue;
                        }
                    }

                    //Make a new view
                    placementView       = ViewDrafting.Create(doc, draftingViewType.Id);
                    placementView.Scale = 1;
                    if (uiForm.materialsCMSSetViewNameTextBox.Text != "")
                    {
                        //If someone defined a custom view name, use that and strip out brackets if they exist
                        placementView.Name = uiForm.materialsCMSSetViewNameTextBox.Text.Replace("{", "").Replace("}", "");
                    }
                    else
                    {
                        //Otherwise, this will be the new ID Material View
                        placementView.Name = "ID Material View";
                    }

                    try
                    {
                        //Set the view sort parameters if they exist
                        placementView.GetParameters(Properties.Settings.Default.BAViewSort1).First().Set("2 Plans");
                        placementView.GetParameters(Properties.Settings.Default.BAViewSort2).First().Set("230 Finish Plans");
                    }
                    catch (Exception e)
                    {
                        MessageBox.Show(e.ToString());
                    }
                    doc.Regenerate();
                    t4.Commit();
                }


                //Do magic to place each symbol in its view by calling the method below in this class
                PlaceSymbolsInView(uiApp, "ID Use", "Mark", placementView);

                //Clean up the files from the operations
                GeneralOperations.CleanRfaBackups(GeneralOperations.GetAllRvtBackupFamilies(@"C:\Temp\", false));
                File.Delete(@"C:\Temp\" + Path.GetFileName(Properties.Settings.Default.RevitFamilyMaterialsCMSSymbIdMaterialSchedule));
                Application.thisApp.newMainUi.materialsCMSFamilyToUse = RVTGetElementsByCollection.FamilyByFamilyName(uiApp, Path.GetFileNameWithoutExtension(Properties.Settings.Default.RevitFamilyMaterialsCMSSymbIdMaterialSchedule));
            }
            else
            {
                //If the family could not be found, well, let the user know of this.
                MessageBox.Show(String.Format("The {0} family could not be found in the project.",
                                              Path.GetFileNameWithoutExtension(Properties.Settings.Default.RevitFamilyMaterialsCMSSymbIdMaterialSchedule)));
            }
        }