public void ChangeWeather(int daypos) { if (GeneralOperations.Success(25)) { isRain = true; if (wet + 30 <= 100) { wet += 30; } else { wet = 100; } t--; } else { isRain = false; if (wet - 1 >= 10) { wet--; } else { wet = 10; } } ChangeTemperature(daypos); }
private void ComputerServcing_Load(object sender, EventArgs e) { GeneralOperations go = new GeneralOperations(); GeneralOperations go2 = new GeneralOperations(); List <AccessPropertySP> getComputerServices = go.GetAllComputerServices(); //go2.GetServiceProviderAdditionalDetails(userName) DataTable dt = new DataTable(); dt.Columns.Add("Name"); dt.Columns.Add("Profession"); dt.Columns.Add("City"); dt.Columns.Add("Address"); foreach (var item in getComputerServices) { var row = dt.NewRow(); row["Name"] = item.UserName; row["Profession"] = item.Profession; row["City"] = item.City; row["Address"] = item.Address; dt.Rows.Add(row); } computerservicingdataGridView.DataSource = dt; }
protected IOrganizationService GetAdministratorServiceProxy(IOrganizationService userServiceProxy, IServiceProvider serviceProvider) { GeneralOperations generalOperations = new GeneralOperations(userServiceProxy); Guid adminUserId = new Guid(generalOperations.GetConfigurationValue("AdminUserId")); return(GetOrganizationServiceProxy(serviceProvider, adminUserId)); }
public DashboardforSP(string spUserName) { InitializeComponent(); this.spUserName = spUserName; generalOperations = new GeneralOperations(); accessProperty = generalOperations.GetServiceProviderRegDetails(spUserName); fullnametextBox.Text = accessProperty.FullName; divisiontextBox.Text = accessProperty.Division; citytextBox.Text = accessProperty.City; addresstextBox.Text = accessProperty.Address; mobilenumbertextBox.Text = accessProperty.MobileNumber; generalOperations2 = new GeneralOperations(); accessProperty2 = generalOperations2.GetServiceProviderAdditionalDetails(spUserName); try { servicechargetextBox.Text = accessProperty2.ServiceCharge.ToString(); availabilitytextBox.Text = accessProperty2.AvailStime; } catch (Exception exp) { } }
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); }
public AllCatCFFE2Request(UIApplication uiApp, String text) { MainUI uiForm = BARevitTools.Application.thisApp.newMainUi; uiForm.multiCatCFFEFamiliesProgressBar.Value = 0; string saveDirectory = uiForm.multiCatCFFEFamilySaveLocation; DataGridView dgv = uiForm.multiCatCFFEFamiliesDGV; RVTDocument doc = uiApp.ActiveUIDocument.Document; SaveAsOptions saveAsOptions = new SaveAsOptions(); saveAsOptions.Compact = true; saveAsOptions.MaximumBackups = 1; saveAsOptions.OverwriteExistingFile = true; //From the Comments section of the Excel template properties, get the family path for the family that was used to make the template string familyFileToUse = uiForm.multiCatCFFEFamilyFileToUse; if (!File.Exists(familyFileToUse)) { //If the family does not exist at that path, prompt the user to find it MessageBox.Show(String.Format("Could not find the family file '{0}'. Please navigate to it in the following window", familyFileToUse)); string file = GeneralOperations.GetFile(); if (file != "") { //If the family was selected, set the selection to the family to use familyFileToUse = file; } else { familyFileToUse = ""; } } //Assuming the family file to use exists, the user has set the save location, and they have set the creation method, continue if (familyFileToUse != "" && uiForm.multiCatCFFEFamilySaveLocation != "" && uiForm.multiCatCFFEFamiliesDGV.Rows.Count != 0 && uiForm.multiCatCFFEFamilyCreationComboBox.Text != "<Select Creation Method>") { //Call the AllCatCFFE2Request.CreateFamilyTypesFromTable method CreateFamilyTypesFromTable(uiApp, uiForm, saveDirectory, dgv, saveAsOptions, familyFileToUse); } //Otherwise, tell the user else if (uiForm.multiCatCFFEFamilySaveLocation == "") { MessageBox.Show("No save directory selected"); } else if (uiForm.multiCatCFFEFamilyCreationComboBox.Text == "<Select Creation Method>") { MessageBox.Show("Please select a creation method"); } else { MessageBox.Show("No families can be made because a family to use was not identified"); } }
private void MaidService_Load(object sender, EventArgs e) { string sql = "SELECT *FROM Registrations WHERE userName='******'"; AccessProperty ap = new AccessProperty(); DataAcess da = new DataAcess(); SqlDataReader reader = da.GetData(sql); while (reader.Read()) { textBox1.Text = Convert.ToString(reader["City"]); GeneralOperations go = new GeneralOperations(); dataGridView1.DataSource = go.GetMaid(); } da.ConnectionClose(); }
public static bool InviteCondition(Citizen patient) { if ((Equals(patient.HealthStatus, HealthStatus.Critical) || Equals(patient.HealthStatus, HealthStatus.SeriousCold) || (Equals(patient.HealthStatus, HealthStatus.MildСold) && !patient.HardWorker)) && patient.WasSick) { return(GeneralOperations.Success(patient.TrustTheDoctor)); } else { return(false); } }
public static bool Condition(Weather weather, Citizen ppatient, int status, Virus virus) { int statusFactor = InfectFactors.StatusFactor(status); int wetFactor = InfectFactors.WetFactor(weather, virus.WetProtect); int temperatureFactor = InfectFactors.TemperatureFactor(weather, virus.CoefDifficultInfectDuringUncomfort, virus.MinInfectT, virus.MaxInfectT); int imunityFactor = InfectFactors.ImmunityFactor(ppatient.Immunity); float probability = (3 * imunityFactor + wetFactor + temperatureFactor + statusFactor) / 6; if (GeneralOperations.Success(probability)) { return(true); } else { return(false); } }
private void Registerformbutton_Click(object sender, EventArgs e) { double serviceCharge = Convert.ToDouble(NameregistertextBox.Text); string availableTime = fromtimetextBox.Text + " " + fromtimecomboBox.Text + "-" + totimetextBox.Text + " " + totimecomboBox.Text; GeneralOperations generalOperations = new GeneralOperations(); int result = generalOperations.AddServiceProviderDetails(spUserName, serviceCharge, availableTime); if (result > 0) { MessageBox.Show("Details Added successfully !!"); DashboardforSP dashboardforSP = new DashboardforSP(spUserName); this.Hide(); dashboardforSP.Show(); //UpdateListOfProducts(); } else { MessageBox.Show("Error in adding."); } }
public static void CreateBackgroundElementPrefabs() { if (BackgroundTypesDictionary.Count == 0) { Debug.LogError("Please initialize the manager first; it doesn't know yet which types exist. (Background Types Dictionary is empty)"); return; } string prefabPath = GeneralInformation.Paths.PrefabsFolder; GeneralOperations.CreateFolderIfEmpty(prefabPath); // create a prefab for each type foreach (KeyValuePair <BackgroundTypes, BackgroundType> pair in BackgroundTypesDictionary) { // create parent empty object GameObject gameObject = new GameObject(pair.Key.ToString()); gameObject.AddComponent <BackgroundElement>().SetType(pair.Key); if (pair.Value.ShouldBlockUpwards) { gameObject.AddComponent <BoxCollider>(); } // create geometric placeholder child CreateBasicObject(name: "Geometric", parent: gameObject.transform, tag: "EditorOnly", mesh: pair.Value.geometricMesh, material: pair.Value.Materials[0]); // create pretty inGame child GameObject prettyChild = CreateBasicObject(name: "Pretty", parent: gameObject.transform, mesh: pair.Value.Meshes[0], material: pair.Value.Materials[0]); if (pair.Value.CanCollide) { MeshCollider collider = prettyChild.AddComponent <MeshCollider>(); // TODO: add an option for a non-automatic collider? collider.convex = true; } prettyChild.SetActive(false); // make a prefab out of it and remove it from the scene GameObject prefab = PrefabUtility.SaveAsPrefabAsset(gameObject, prefabPath + Separator + pair.Key.ToString() + ".prefab"); // Object.Destroy cannot be called in edit mode Object.DestroyImmediate(gameObject); } }
public ServiceProviderProfile(string spUsername) { InitializeComponent(); this.spUsername = spUsername; generalOperations = new GeneralOperations(); accessProperty = generalOperations.GetServiceProviderRegDetails(spUsername); fullnametextBox.Text = accessProperty.UserName; EmailtextBox.Text = accessProperty.EmailId; passwordtextBox.Text = accessProperty.Password; catagorytextBox.Text = accessProperty.Category; addresstextBox.Text = accessProperty.Address; citytextBox.Text = accessProperty.City; divisiontextBox.Text = accessProperty.Division; mobiletoextBox.Text = accessProperty.MobileNumber; NidtextBox.Text = accessProperty.NID; nametextBox.Text = accessProperty.FullName; dobtextBox.Text = accessProperty.DOB; gendertextBox.Text = accessProperty.Gender; professiontextBox.Text = accessProperty.Profession; }
//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); } }
public AdminController() { generalOperations = new GeneralOperations(); }
public HomeController() { generalOperations = new GeneralOperations(); }
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(); }
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(); }
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)); } }
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; } }
//мутация public void Mutate(int NumberOfCitizens, int NumberOfInfected) { if (GeneralOperations.Success((NumberOfInfected / NumberOfCitizens) * 100)) { return; } int coefOfMutate; if (GeneralOperations.Success(ProbabilityOfPositiveMutation)) { coefOfMutate = 1; } else { coefOfMutate = -1; } Random rand = new Random(); int caseOfMutation = rand.Next(100); switch (caseOfMutation) { case int n when(n <= 2): if (MutateConditions.DifficultConditions(Difficult)) { Difficult += coefOfMutate; } break; case int n when(n > 2 && n <= 8): if (MutateConditions.MinInfectTConditions(MaxInfectT, MaxInfectT, MinComfortT, MaxComfortT)) { MinInfectT += coefOfMutate; } break; case int n when(n > 8 && n <= 14): if (MutateConditions.MaxInfectTConditions(MaxInfectT, MaxInfectT, MinComfortT, MaxComfortT)) { MaxInfectT += coefOfMutate; } break; case int n when(n > 15 && n <= 20): if (MutateConditions.MinComfortTConditions(MaxInfectT, MaxInfectT, MinComfortT, MaxComfortT)) { MinComfortT += coefOfMutate; } break; case int n when(n > 20 && n <= 26): if (MutateConditions.MaxComfortTConditions(MaxInfectT, MaxInfectT, MinComfortT, MaxComfortT)) { MaxComfortT += coefOfMutate; } break; case 27: if (MutateConditions.CoefDifficultInfectConditions(CoefDifficultInfectDuringUncomfort)) { CoefDifficultInfectDuringUncomfort += coefOfMutate; } break; case int n when(n > 27 && n <= 29): if (MutateConditions.SystemDamagedConditions(skeletonDamaged)) { skeletonDamaged += coefOfMutate; } break; case int n when(n > 29 && n <= 32): if (MutateConditions.SystemDamagedConditions(muscleDamaged)) { muscleDamaged += coefOfMutate; } break; case int n when(n > 32 && n <= 37): if (MutateConditions.SystemDamagedConditions(respiratoryDamaged)) { respiratoryDamaged += coefOfMutate; } break; case int n when(n > 37 && n <= 39): if (MutateConditions.SystemDamagedConditions(circulatoryDamaged)) { circulatoryDamaged += coefOfMutate; } break; case int n when(n > 39 && n <= 42): if (MutateConditions.SystemDamagedConditions(diureticDamaged)) { diureticDamaged += coefOfMutate; } break; case int n when(n > 42 && n <= 44): if (MutateConditions.SystemDamagedConditions(digestiveDamaged)) { digestiveDamaged += coefOfMutate; } break; case int n when(n > 44 && n <= 48): if (MutateConditions.SystemDamagedConditions(nervousDamaged)) { nervousDamaged += coefOfMutate; } break; case int n when(n > 48 && n <= 50): if (MutateConditions.SystemDamagedConditions(reproductiveDamaged)) { reproductiveDamaged += coefOfMutate; } break; case int n when(n > 50 && n <= 53): if (MutateConditions.SystemDamagedConditions(sensoryDamaged)) { sensoryDamaged += coefOfMutate; } break; case int n when(n > 53 && n <= 57): if (MutateConditions.SystemDamagedConditions(lyphaticDamaged)) { lyphaticDamaged += coefOfMutate; } break; case int n when(n > 57 && n <= 62): if (MutateConditions.SystemDamagedConditions(immunityDamaged)) { immunityDamaged += coefOfMutate; } break; } }
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; }
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()); } }
public static void InitializeManager() { // get all background types automatically // this is faster (if harder to read) than Resources.FindObjectsOfTypeAll // because it only searches a few folders instead of the whole project string[] typesPaths = AssetDatabase.FindAssets("t: BackgroundType", new[] { GeneralInformation.Paths.TypesFolder }); foreach (string path in typesPaths) { BackgroundType type = AssetDatabase.LoadAssetAtPath <BackgroundType>(AssetDatabase.GUIDToAssetPath(path)); if (BackgroundTypesDictionary == null) { BackgroundTypesDictionary = new Dictionary <BackgroundTypes, BackgroundType>(); } if (!BackgroundTypesDictionary.ContainsValue(type)) { BackgroundTypesDictionary.Add(type.Type, type); // for each background type, get the meshes from the mesh folder string[] meshesPaths = AssetDatabase.FindAssets( type.FindMeshesByName? type.Type.ToString() + " t: Mesh": "t: Mesh" , new[] { type.MeshesFolder }); if (meshesPaths.Length == 0) { Debug.LogError("Could not find meshes to use for " + type.Type.ToString() + " at " + type.MeshesFolder + ". If this is not fixed, the Prefab Creation will fail."); } foreach (string meshPath in meshesPaths) { Mesh mesh = AssetDatabase.LoadAssetAtPath <Mesh>(AssetDatabase.GUIDToAssetPath(meshPath)); if (!type.Meshes.Contains(mesh)) { type.Meshes.Add(mesh); } } } } // create x versions of each material per type, ensure it has the right scale // and offset it x different ways // we need to use Database.CreateAsset so there is a path on disk to the new materials; // otherwise the ScriptableObject trying to link to the new materials throws an error Vector2 tiling; Material newMat; string matPath; string matFolder; foreach (BackgroundType type in BackgroundTypesDictionary.Values) { if (!type.ShouldOffsetTexture) { type.NewMaterials = type.Materials; } else if (type.NewMaterials == null || type.NewMaterials.Count == 0) { // we find the folder containing the materials // and create a subfolder for the variations if (type.Materials == null || type.Materials.Count == 0) { Debug.LogError("You forgot to add materials to the element type " + type.Type + "!"); continue; } matPath = AssetDatabase.GetAssetPath(type.Materials[0]); int lastSlash = matPath.LastIndexOf(Separator); matPath = matPath.Remove(lastSlash); matFolder = matPath + Separator + GeneralInformation.Paths.AlternativeMaterialsFolderName; GeneralOperations.CreateFolderIfEmpty(matFolder); // for cleaning up purposes later if (!AlternateMaterialsFoldersPaths.Contains(matFolder)) { AlternateMaterialsFoldersPaths.Add(matFolder); if (isDebugging) { Debug.Log("created folder " + matFolder); } } tiling = type.TextureTiling; foreach (Material mat in type.Materials) { mat.mainTextureScale = tiling; for (int i = 0; i < 3; i++) { newMat = new Material(mat) { mainTextureOffset = new Vector2(Random.Range((float)0, (float)1), Random.Range((float)0, (float)1)) }; AssetDatabase.CreateAsset(newMat, matPath + Separator + GeneralInformation.Paths.AlternativeMaterialsFolderName + Separator + (mat.name + "_" + type.name + "_v" + i + ".mat")); type.NewMaterials.Add(newMat); if (isDebugging) { Debug.Log("added material " + newMat + " to the list."); } } //and then reset it so as not to commit useless stuff each time you make one small change mat.mainTextureScale = Vector2.one; } if (isDebugging) { Debug.Log("Just treated " + type.name + " background type."); } } } }
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))); } }
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); } } }