예제 #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);
        }
예제 #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;
        }
예제 #3
0
        public AdminFamiliesUFRequest(UIApplication uiApp, String text)
        {
            try
            {
                MainUI      uiForm = BARevitTools.Application.thisApp.newMainUi;
                RVTDocument doc    = uiApp.ActiveUIDocument.Document;

                bool   fullSync        = uiForm.adminFamiliesUFFullSyncCheckbox.Checked;
                string currentVersion  = Properties.Settings.Default.BARTRevitFamilyCurrentYear;
                string upgradedVersion = uiApp.Application.VersionNumber;
                //The current library path is needed to make the new library path by swapping the year of the current development library with the year of the Revit version running.
                string currentLibraryPath  = Properties.Settings.Default.RevitBAFamilyLibraryPath;
                string upgradedLibraryPath = currentLibraryPath.Replace(currentVersion, upgradedVersion);
                //If the new library does not yet exist, make it. This will likely be used only once when a new version of Revit is released.
                if (!Directory.Exists(upgradedLibraryPath))
                {
                    Directory.CreateDirectory(upgradedLibraryPath);
                }

                //Do some cleanup in the current library and the new library if backups exist
                GeneralOperations.CleanRfaBackups(currentLibraryPath);
                GeneralOperations.CleanRfaBackups(upgradedLibraryPath);

                //Create a list of family paths in the current library, and a list of family paths in the new library.
                List <string> familiesInCurrentLibrary = GeneralOperations.GetAllRvtFamilies(currentLibraryPath, false);
                //Also, make a dictionary because while the family paths will be evaluated, the paths themselves will need to be retrieved later by family name.
                Dictionary <string, string> currentLibraryDict  = new Dictionary <string, string>();
                List <string> familiesInUpgradedLibrary         = GeneralOperations.GetAllRvtFamilies(upgradedLibraryPath, false);
                Dictionary <string, string> upgradedLibraryDict = new Dictionary <string, string>();
                List <string> familiesToUpgrade = new List <string>();
                List <string> familiesToDelete  = new List <string>();
                List <string> upgradedFamilies  = new List <string>();
                List <string> deletedFamilies   = new List <string>();

                //Just a variable for storing which family name is currently being evaluated
                string currentEvaluation = "";
                //If there are families in the new library...
                if (familiesInUpgradedLibrary.Count > 0)
                {
                    foreach (string upgradedFamilyPath in familiesInUpgradedLibrary)
                    {
                        try
                        {
                            //Get the name of the family and add it as a key in the dictionary, along with the family path
                            currentEvaluation = Path.GetFileNameWithoutExtension(upgradedFamilyPath);
                            upgradedLibraryDict.Add(Path.GetFileNameWithoutExtension(upgradedFamilyPath), upgradedFamilyPath);
                        }
                        catch
                        {
                            continue;
                        }
                    }
                }

                //Next, evaluate what families are in the current library
                foreach (string currentFamilyPath in familiesInCurrentLibrary)
                {
                    //Skip any path that contains "Archive" or "Backup"
                    if (!currentFamilyPath.Contains("Archive") && !currentFamilyPath.Contains("Backup"))
                    {
                        try
                        {
                            //Add the name off the family to dictionary as a key assigned the path
                            currentEvaluation = Path.GetFileNameWithoutExtension(currentFamilyPath);
                            currentLibraryDict.Add(Path.GetFileNameWithoutExtension(currentFamilyPath), currentFamilyPath);
                        }
                        catch
                        {
                            continue;
                        }
                    }
                }

                //Going back to the families in the new library
                if (familiesInUpgradedLibrary.Count > 0)
                {
                    //Evaluate each family name serving as a key in the dictionary for the new library
                    foreach (string upgradedFamily in upgradedLibraryDict.Keys)
                    {
                        //If the current library dictionary has a key with the same family name...
                        if (currentLibraryDict.Keys.Contains(upgradedFamily))
                        {
                            //Compare the dates when the families were last modified to determine if the one in the new library is older than the one in the current library
                            DateTime currentFamilyWriteTime  = File.GetLastWriteTime(currentLibraryDict[upgradedFamily]);
                            DateTime upgradedFamilyWriteTime = File.GetLastWriteTime(upgradedLibraryDict[upgradedFamily]);
                            //If the familly in the current library is more recently modified, add it to the list of families that will need upgraded and saved to the new library, thus replacing the one in the new library with the updated one
                            if (currentFamilyWriteTime > upgradedFamilyWriteTime)
                            {
                                familiesToUpgrade.Add(currentLibraryDict[upgradedFamily]);
                            }
                        }
                        else
                        {
                            //Otherwise, if the family in the new library does not exist in the current library, add it to a list of families to delete if a full sync is performed
                            familiesToDelete.Add(upgradedLibraryDict[upgradedFamily]);
                        }
                    }

                    //If the new library does not contain the family in the current library, add it to the list of families to upgrade and save to the new library.
                    foreach (string originalFamily in currentLibraryDict.Keys)
                    {
                        if (!upgradedLibraryDict.Keys.Contains(originalFamily))
                        {
                            familiesToUpgrade.Add(currentLibraryDict[originalFamily]);
                        }
                    }
                }
                else
                {
                    //If there are no families in the new library, such as one that was just created for a new version of Revit, then all families from the current library will need upgraded and saved in the new library
                    familiesToUpgrade = familiesInCurrentLibrary;
                }

                //Cycle through all of the families that will need to be upgraded and saved to the new library
                foreach (string familyToUpgrade in familiesToUpgrade)
                {
                    try
                    {
                        //First, determine if the family can be opened and is not a newer version of Revit
                        if (RVTOperations.RevitVersionUpgradeCheck(uiApp, familyToUpgrade, true))
                        {
                            //If it can be opened, upgrade it and add its name to the list of families that were upgraded
                            bool result = RVTOperations.UpgradeRevitFile(uiApp, familyToUpgrade, familyToUpgrade.Replace(currentVersion, upgradedVersion), true);
                            if (result == true)
                            {
                                upgradedFamilies.Add(Path.GetFileNameWithoutExtension(familyToUpgrade));
                            }
                        }
                        else
                        {
                            //If the family could not be opened because it was saved in a newer version of Revit, let the user know and skip over the family
                            MessageBox.Show(String.Format("{0} was saved in a new version of Revit", Path.GetFileNameWithoutExtension(familyToUpgrade)));
                        }
                    }
                    catch (Exception f)
                    { MessageBox.Show(f.ToString()); }
                }

                //If the user checked the box to do a full sync, delete the families that were added to the list of families to delete. This will ensure the new library and current library match regarding what families they contain
                if (fullSync)
                {
                    foreach (string familyToDelete in familiesToDelete)
                    {
                        try
                        {
                            File.Delete(familyToDelete);
                            deletedFamilies.Add(Path.GetFileNameWithoutExtension(familyToDelete));
                        }
                        catch (Exception e)
                        { MessageBox.Show(e.ToString()); }
                    }
                }

                //Update the listboxes of the UI showing what families were upgraded and what were deleted
                uiForm.adminFamiliesUFUpgradedFamiliesListBox.DataSource = upgradedFamilies;
                uiForm.adminFamiliesUFDeletedFamiliesListBox.DataSource  = deletedFamilies;
                //Cleanup the family backups in the new library if they exist
                GeneralOperations.CleanRfaBackups(upgradedLibraryPath);
            }
            catch (Exception g)
            {
                MessageBox.Show(g.ToString());
            }
        }
예제 #4
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);
            }
        }
예제 #5
0
        public QaqcRFSPRequest(UIApplication uiApp, String text)
        {
            MainUI        uiForm      = BARevitTools.Application.thisApp.newMainUi;
            List <string> familyFiles = uiForm.qaqcRFSPFamilyFiles;

            foreach (string familyFile in familyFiles)
            {
                //Open the family file and get its Family Manager. Then, get the list of family parameters
                RVTDocument             familyDoc = uiApp.Application.OpenDocumentFile(familyFile);
                FamilyManager           famMan    = familyDoc.FamilyManager;
                IList <FamilyParameter> famParams = famMan.GetParameters();
                string famName = familyDoc.Title.Replace(".rfa", "");
                //Start a transaction
                using (Transaction t1 = new Transaction(familyDoc, "ChangeSharedParameters"))
                {
                    t1.Start();
                    try
                    {
                        //Cycle through the family parameters
                        foreach (FamilyParameter param in famParams)
                        {
                            string paramName = param.Definition.Name;
                            try
                            {
                                //If the parameter is shared, and the name does not contain BA or BAS, continue
                                if (param.IsShared && !paramName.ToUpper().Contains("BA ") && !paramName.ToUpper().Contains("BAS "))
                                {
                                    //A temporary parameter needs to be made in the place of the one to be removed, so get the group of the parameter to be replaced
                                    BuiltInParameterGroup paramGroup = param.Definition.ParameterGroup;
                                    string paramTempName             = "tempName";
                                    //Determine if the parameter to replaced is an instance parameter
                                    bool paramInstance = param.IsInstance;
                                    //Make replace the parameter with the temporary one, giving it the same group and instance settings
                                    FamilyParameter newParam = famMan.ReplaceParameter(param, paramTempName, paramGroup, paramInstance);
                                    //Then, rename the new parameter
                                    famMan.RenameParameter(newParam, paramName);
                                    //Add to the ListBox the outcome of the shared parameter replacement
                                    uiForm.qaqcRFSPParametersListBox.Items.Add(famName + " : " + paramName + ": SUCCESS");
                                }
                            }
                            catch
                            {
                                //If the replacement fails, report that too
                                uiForm.qaqcRFSPParametersListBox.Items.Add(famName + " : " + paramName + ": FAILED");
                            }
                        }
                        t1.Commit();
                        //Update the MainUI
                        uiForm.qaqcRFSPParametersListBox.Update();
                        uiForm.qaqcRFSPParametersListBox.Refresh();
                    }
                    catch
                    {
                        t1.RollBack();
                    }
                }
                //Save the family and remove the backups
                RVTOperations.SaveRevitFile(uiApp, familyDoc, true);
                GeneralOperations.CleanRfaBackups(Path.GetDirectoryName(familyFile));
            }
        }
예제 #6
0
        public AdminFamiliesUFVPRequest(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.adminFamiliesUFVPDirectoryTextBox.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.adminFamiliesUFVPCheckBox.Checked)
            {
                familyFiles = GeneralOperations.GetAllRvtFamilies(uiForm.adminFamiliesUFVPDirectoryTextBox.Text, uiForm.adminFamiliesUFVPDatePicker.Value, true);
            }
            else
            {
                familyFiles = GeneralOperations.GetAllRvtFamilies(uiForm.adminFamiliesUFVPDirectoryTextBox.Text, false);
            }

            //Verify the number of families collected is more than 0
            if (familyFiles.Count > 0)
            {
                try
                {
                    //Make a dictionary of the shared parameter names and definitions for use later.
                    Dictionary <string, ExternalDefinition> sharedParameterDefinitions = new Dictionary <string, ExternalDefinition>();
                    DefinitionFile definitionFile = null;
                    bool           sharedParametersIsAccessible = true;
                    try
                    {
                        definitionFile = uiApp.Application.OpenSharedParameterFile();
                        DefinitionGroups sharedParameterGroups = definitionFile.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 shared parameters file is not accessible, set to false
                    catch { sharedParametersIsAccessible = false; }

                    //Reset and prepare the progress bar
                    uiForm.adminFamiliesUFVPProgressBar.Value   = 0;
                    uiForm.adminFamiliesUFVPProgressBar.Minimum = 0;
                    uiForm.adminFamiliesUFVPProgressBar.Maximum = familyFiles.Count;
                    uiForm.adminFamiliesUFVPProgressBar.Step    = 1;
                    uiForm.adminFamiliesUFVPProgressBar.Visible = true;

                    //Only proceed if the shared parameters file was accessible and the version parameter exists in the shared parameters
                    if (sharedParametersIsAccessible && sharedParameterDefinitions.Keys.Contains(BARevitTools.Properties.Settings.Default.RevitUFVPParameter))
                    {
                        foreach (string familyFile in familyFiles)
                        {
                            //The AdminFamiliesUFVPRequest.SetParameters() method will set the parameter value
                            SetParameters(uiApp, familyFile, sharedParameterDefinitions[Properties.Settings.Default.RevitUFVPParameter]);
                            uiForm.adminFamiliesUFVPProgressBar.PerformStep();
                        }
                    }
                    //If the shared parameter does not exist, let the user know. It will need to be made first
                    else if (sharedParametersIsAccessible && !sharedParameterDefinitions.Keys.Contains(BARevitTools.Properties.Settings.Default.RevitUFVPParameter))
                    {
                        MessageBox.Show(String.Format("Could not get the shared parameter '{0}' in the shared parameters file located at {1}. Please verify its existence", Properties.Settings.Default.RevitUFVPParameter, definitionFile.Filename));
                    }
                    //If the shared parameters file itself could not be accessed, inform the user.
                    else
                    {
                        MessageBox.Show("Could not open the shared parameters file. Verify it is loaded in the Manage Tab > Shared Parameters");
                    }
                }
                catch (Exception e)
                {
                    MessageBox.Show(e.ToString());
                }
                finally
                {
                    //Go back through the directory where the families are located and clean up the backups made from saving them after the parameter value was set.
                    List <string> backupFamilies2 = GeneralOperations.GetAllRvtBackupFamilies(uiForm.adminFamiliesUFVPDirectoryTextBox.Text, true);
                    GeneralOperations.CleanRfaBackups(backupFamilies2);
                }
            }
        }
예제 #7
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();
        }
예제 #8
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)));
            }
        }