public Result Execute(ExternalCommandData commandData, ref string message, ElementSet elements) { UIApplication uiApp = commandData.Application; Document doc = commandData.Application.ActiveUIDocument.Document; UIDocument uidoc = uiApp.ActiveUIDocument; using (TransactionGroup txGp = new TransactionGroup(doc)) { txGp.Start("Initialize PED data"); using (Transaction trans1 = new Transaction(doc)) { trans1.Start("Create parameters"); ped ped = new ped(); ped.CreateElementBindings(commandData); trans1.Commit(); } using (Transaction trans2 = new Transaction(doc)) { trans2.Start("Populate parameters"); ped ped = new ped(); ped.PopulateParameters(commandData); trans2.Commit(); } txGp.Assimilate(); } return(Result.Succeeded); }
public static TResult InvokeGroup <TResult>(this Document doc, Func <TransactionGroup, TResult> func, string name = "default") { using (var tr = new TransactionGroup(doc, name)) { tr.Start(); var result = func(tr); var status = tr.GetStatus(); switch (status) { case TransactionStatus.Started: tr.Commit(); return(result); case TransactionStatus.Committed: case TransactionStatus.RolledBack: return(result); case TransactionStatus.Error: tr.RollBack(); return(result); default: return(result); } } }
public Result Execute(ExternalCommandData commandData, ref string message, ElementSet elements) { _uiDoc = commandData.Application.ActiveUIDocument; var doc = _uiDoc.Document; if (doc.ActiveView.ViewType != ViewType.ProjectBrowser) { using (var trg = new TransactionGroup(doc, "Копирование значений имя системы")) { trg.Start(); foreach (var cat in GetDuctCategories()) { var elementsByCat = new FilteredElementCollector(doc) .OfCategory(cat) .WhereElementIsNotElementType() .ToList(); if (elementsByCat.Count > 0) { RevitFunctions.CopySystemNameValue(doc, elementsByCat); } } trg.Assimilate(); } var td = new TaskDialog("Copy views") { Id = "ID_TaskDialog_Copy_Views", MainIcon = TaskDialogIcon.TaskDialogIconInformation, Title = "Создание копий видов с применением фильтра", TitleAutoPrefix = false, AllowCancellation = true, MainInstruction = "Данные из параметра Имя системы для всех элементов систем воздуховодов скопированы", MainContent = "Хотите создать копии текущего вида с применением фильтров по системам?" }; td.AddCommandLink(TaskDialogCommandLinkId.CommandLink1, "Да, создать фильтры и виды"); td.AddCommandLink(TaskDialogCommandLinkId.CommandLink2, "Нет"); var tdRes = td.Show(); if (tdRes != TaskDialogResult.CommandLink1) { return(Result.Cancelled); } var sysNameParamElement = new FilteredElementCollector(doc) .OfClass(typeof(ParameterElement)) .FirstOrDefault(p => p.Name == "ИмяСистемы"); var sysNameParam = sysNameParamElement as ParameterElement; foreach (var systemName in GetDuctSystemNames(doc)) { CreateFilterForDuctSystem(doc, sysNameParam, systemName); } } else { TaskDialog.Show("Предупреждение", "Не активирован вид для создания копий с применением фильтра"); } return(Result.Succeeded); }
public Result Execute( ExternalCommandData commandData, ref string message, ElementSet elements) { UIApplication uiapp = commandData.Application; UIDocument uidoc = uiapp.ActiveUIDocument; Application app = uiapp.Application; Document doc = uidoc.Document; Tools tools = new Tools(uiapp); if (!tools.go) { TaskDialog.Show("Failed", "Please, run 'Budget Parameters' first."); return(Result.Failed); } using (TransactionGroup tgx = new TransactionGroup(doc)) { tgx.Start(); tools.ModellingTool(); tools.WindowsAndDoorsHosts(); tools.BoQ(); tgx.Commit(); } TaskDialog.Show("Status", "Tools and Hosts successfully finished."); return(Result.Succeeded); }
public Result Execute(ExternalCommandData commandData, ref string message, ElementSet elements) { _dbdocument = commandData.Application.ActiveUIDocument.Document; TransactionGroup outerGroup = new TransactionGroup(_dbdocument, "preview control"); outerGroup.Start(); try { PreviewModel form = new PreviewModel(commandData.Application.Application, new ElementId(-1)); form.ShowDialog(); } catch (Exception e) { throw e; } finally { outerGroup.RollBack(); } return(Result.Succeeded); }
public Result Execute( ExternalCommandData commandData, ref string message, ElementSet elements) { UIApplication uiApp = commandData.Application; _uiDoc = uiApp.ActiveUIDocument; _doc = _uiDoc.Document; SettingsUsr.Init(); // this cleaned up the text display problem // Application.SetCompatibleTextRenderingDefault(false); using (TransactionGroup tg = new TransactionGroup(_doc, "measure points")) { tg.Start(); Process(_uiDoc, _doc); if (tg.GetStatus() == TransactionStatus.Started) { tg.RollBack(); } } return(Result.Succeeded); }
/// <summary> /// Utility to duplicate drafting views and their contents from one document to another. /// </summary> /// <param name="fromDocument">The source document.</param> /// <param name="views">The collection of drafting views.</param> /// <param name="toDocument">The target document.</param> /// <returns>The number of drafting elements created in the copied views.</returns> public static int DuplicateDraftingViews(Document fromDocument, IEnumerable <ViewDrafting> views, Document toDocument) { // Return value int numberOfDetailElements = 0; // Transaction group for all activities using (TransactionGroup tg = new TransactionGroup(toDocument, "API - Duplication across documents with detailing")) { tg.Start(); // Use LINQ to convert to list of ElementIds for use in CopyElements() method List <ElementId> ids = views.AsEnumerable <View>().ToList <View>().ConvertAll <ElementId>(ViewConvertToElementId); // Duplicate. Pass true to get a map from source element to its copy Dictionary <ElementId, ElementId> viewMap = DuplicateElementsAcrossDocuments(fromDocument, ids, toDocument, true); // For each copied view, copy the contents foreach (ElementId viewId in viewMap.Keys) { View fromView = fromDocument.GetElement(viewId) as View; View toView = toDocument.GetElement(viewMap[viewId]) as View; numberOfDetailElements += DuplicateDetailingAcrossViews(fromView, toView); } tg.Assimilate(); } return(numberOfDetailElements); }
public void Execute(UIApplication uiapp) { UIDocument uidoc = uiapp.ActiveUIDocument; Document doc = uidoc.Document; try { string result = "F"; TransactionGroup tr = new TransactionGroup(doc); tr.Start("Save As"); result = Save_As(uiapp, doc); tr.Assimilate(); if (result == "S") { doc.Save(); string pa = doc.PathName; File.Copy(pa, path.Text + "\\" + name.Text + ".rvt", true); RevitCommandId saveDoc = RevitCommandId.LookupPostableCommandId(PostableCommand.Undo); uiapp.PostCommand(saveDoc); Data_File(path.Text + "\\" + name.Text + ".rvt", doc); MessageBox.Show("Save As Success!", "SUCCESS", MessageBoxButton.OK, MessageBoxImage.Information); } } catch (Exception ex) { MessageBox.Show(ex.Message); } return; }
public static void Import(Document doc, string filename) { using (TransactionGroup tg = new TransactionGroup(doc, "Import Doors")) { tg.Start(); var Lines = File.ReadAllLines(filename); var Doors = new FilteredElementCollector(doc).OfCategory(BuiltInCategory.OST_Doors).ToList(); foreach (var line in Lines) { if (Doors.Any(x => x.get_Parameter(BuiltInParameter.ALL_MODEL_MARK).AsString() == line.Split('\t')[1])) { var d = Doors.FirstOrDefault(x => x.get_Parameter(BuiltInParameter.ALL_MODEL_MARK).AsString() == line.Split('\t')[1]); if (d != null) { using (Transaction t = new Transaction(doc, "Update " + line.Split('\t')[1])) { t.Start(); var e = d as Element; for (int i = 0; i < DoorParameters.Count(); i++) { try { e.SetElementParam(DoorParameters[i], line.Split('\t')[i + 3]); } catch { } } try { e.get_Parameter(BuiltInParameter.ALL_MODEL_INSTANCE_COMMENTS).SetValueString(line.Split('\t').Last()); } catch { } t.Commit(); } } } } tg.Commit(); } }
private void Cut(WallIntersectionData data, AngleCalculator calculator, WallExtrusion extrusion) { using (TransactionGroup tranGr = new TransactionGroup(_doc)) { tranGr.Start("wall penetration one element"); var _roundOpen = _doc.GetFamilySymbol("Отверстие_Поворотное", "Отверстие"); var _rectOpen = _doc.GetFamilySymbol("ОтверстиеПрямоугольное_Поворотное", "Отверстие"); using (Transaction tran = new Transaction(_doc)) { tran.Start("Creating wall penetration"); FamilyInstance fi = _doc.Create.NewFamilyInstance(data.WallSideFaceRef, calculator.LocationPoint, new XYZ(1, 0, 0), _rectOpen); tran.Commit(); tran.Start("SetPar"); double offset = UnitUtils.ConvertToInternalUnits(0, DisplayUnitType.DUT_MILLIMETERS); fi.LookupParameter("ШиринаОтверстия").Set(extrusion.Width + offset); fi.LookupParameter("ВысотаОтверстия").Set(extrusion.Height + offset); fi.LookupParameter("УголВертикальногоПоворота").Set(calculator.VerticalAngle); fi.LookupParameter("УголГоризонтальногоПоворота").Set(calculator.HorizontalAngle); tran.Commit(); } tranGr.Assimilate(); } }
public static void InvokeGroup(this Document doc, Action <TransactionGroup> action, string name = "default") { using (var tr = new TransactionGroup(doc, name)) { tr.Start(); action(tr); var status = tr.GetStatus(); switch (status) { case TransactionStatus.Started: tr.Commit(); return; case TransactionStatus.Committed: case TransactionStatus.RolledBack: break; case TransactionStatus.Error: tr.RollBack(); return; default: return; } } }
//methdo to execute all the other methods public Execution(Document tempDoc, ElementSet tempSelected, string name, int minSpace) { doc = tempDoc; familyName = name; minSpacing = minSpace; ManageView view = new ManageView(doc); Intersectors.view3D = ManageView.view3D; DuctsAndTrays.trayDuctlist = ConverToList(tempSelected); CreateAndPlace createAndPlace = new CreateAndPlace(doc, familyName); using (TransactionGroup tx = new TransactionGroup(doc, "Support Generation")) { tx.Start(); view.GetBoundsDetail(); LeastWidthPoints(); view.SetBounds(); tx.Assimilate(); } }
public void Execute(UIApplication uiapp) { UIDocument uidoc = uiapp.ActiveUIDocument; Document doc = uidoc.Document; try { TransactionGroup transaction = new TransactionGroup(doc); transaction.Start("Update Material"); string result = Sua_Thong_Tin_Vat_Lieu_Project(uiapp, doc); transaction.Assimilate(); if (result == "S") { F_GetFactor.get_material_factor(doc, my_material_factor, thong_tin_he_so_vat_lieu_project); thong_tin_vat_lieu_project.Items.Refresh(); MessageBox.Show("Update Success!", "SUCCESS", MessageBoxButton.OK, MessageBoxImage.Information); } } catch (Exception ex) { MessageBox.Show(ex.Message); } return; }
public void Execute(UIApplication uiapp) { UIDocument uidoc = uiapp.ActiveUIDocument; Document doc = uidoc.Document; try { TransactionGroup transaction = new TransactionGroup(doc); transaction.Start("Parameters"); string result = Them_Hoac_Xoa_Information_Trong_Project(uiapp, doc); string result1 = Them_Hoac_Xoa_Parameter_Trong_Project(uiapp, doc); if (result == "S" && result1 == "S") { MessageBox.Show("Process Success!", "SUCCESS", MessageBoxButton.OK, MessageBoxImage.Information); } transaction.Assimilate(); } catch (Exception ex) { MessageBox.Show(ex.Message); } return; }
public static void CollectData(this Document doc) { using (TransactionGroup tg = new TransactionGroup(doc, "Output Xml and Update Data")) { tg.Start(); using (Transaction t = new Transaction(doc, "Add Parameters:")) { t.Start(); foreach (Param p in Parameters) { doc.AddParam(p); } t.Commit(); } using (Transaction t = new Transaction(doc, "Collect Project Data")) { t.Start(); var fams = new FilteredElementCollector(doc).OfClass(typeof(Family)).Count(); var insts = new FilteredElementCollector(doc).OfClass(typeof(FamilyInstance)).Count(); var mats = new FilteredElementCollector(doc).OfCategory(BuiltInCategory.OST_Materials).Count(); var Sheets = new FilteredElementCollector(doc).OfCategory(BuiltInCategory.OST_Sheets).ToElementIds().ToList(); var Views = new FilteredElementCollector(doc).OfCategory(BuiltInCategory.OST_Views).ToElementIds().ToList(); var vos = Views.Where(x => !Viewport.CanAddViewToSheet(doc, Sheets.FirstOrDefault(), x)).Count(); doc.SetParam(ProjectParams.Families, fams.ToString()); doc.SetParam(ProjectParams.FamilyInstances, insts.ToString()); doc.SetParam(ProjectParams.Materials, mats.ToString()); doc.SetParam(ProjectParams.Sheets, Sheets.Count().ToString()); doc.SetParam(ProjectParams.Views, Views.Count().ToString()); doc.SetParam(ProjectParams.ViwesOnSheets, vos.ToString()); t.Commit(); } tg.Commit(); } }
public Result Execute(ExternalCommandData commandData, ref string message, ElementSet elements) { UIApplication uiapp = commandData.Application; UIDocument uidoc = uiapp.ActiveUIDocument; Application app = uiapp.Application; Document doc = uidoc.Document; // code using (TransactionGroup transGr = new TransactionGroup(doc)) { transGr.Start("VD1TransGr"); VD1ViewModel viewModel = new VD1ViewModel(uidoc); VD1Window window = new VD1Window(viewModel); if (window.ShowDialog() == false) { return(Result.Cancelled); } transGr.Assimilate(); } return(Result.Succeeded); }
internal void RenumberProcess(IList <GridInfo> targetGridInfoList) { using (TransactionGroup tg = new TransactionGroup(uidoc.Document, Properties.Messages.RenumberGrids_Transaction)) { tg.Start(); using (Transaction t0 = new Transaction(uidoc.Document, Properties.Messages.RenumberGrids_Transaction_AdjustNames)) { t0.Start(); IList <Element> allGrids = new FilteredElementCollector(uidoc.Document).OfCategory(BuiltInCategory.OST_Grids).WhereElementIsNotElementType().ToElements(); for (int i = 0; i < allGrids.Count; i++) { Grid currentGrid = allGrids.ElementAt(i) as Grid; currentGrid.Name = string.Format("ONBOX {0}", i.ToString()); } t0.Commit(); } using (Transaction t1 = new Transaction(uidoc.Document, Properties.Messages.RenumberGrids_Transaction)) { t1.Start(); ApplyTheRenumberingOnTheActualGrids(targetGridInfoList); t1.Commit(); } tg.Assimilate(); } }
public void CreateFloorFromLink() { using (var tg = new TransactionGroup(m_doc)) { tg.Start("Create Floors"); try { foreach (var lrp in selectedLinkedRooms) { var room = lrp.LinkedRoom; var edgeArrayArray = GetRoomBoundaries(room, lrp.TransformValue); var curveArrayList = CreateProfiles(edgeArrayArray); var floorType = FindFloorType(room); var newFloor = CreateNewFloor(room, curveArrayList, floorType); if (null != newFloor) { createdFloors.Add(newFloor); } } tg.Assimilate(); } catch (Exception ex) { tg.RollBack(); MessageBox.Show("Cannot create floors from the selected linked room.\n" + ex.Message, "Create Floors from Linked Rooms", MessageBoxButtons.OK, MessageBoxIcon.Warning); } } }
public Result Execute(ExternalCommandData commandData, ref string message, ElementSet elements) { var doc = commandData.Application.ActiveUIDocument.Document; var group = new TransactionGroup(doc); group.Start("创建很多墙"); var transaction = new Transaction(doc); try { transaction.Start("创建一片墙"); //创建墙体 var subTran = new SubTransaction(doc); transaction.Commit(); group.Assimilate(); } catch (Exception e) { if (transaction.GetStatus() == TransactionStatus.Started) { transaction.RollBack(); } } return(Result.Succeeded); }
private void Intersection(Wall wall) { var intersectElement = GetIntersectElements(wall); using (TransactionGroup tranGr = new TransactionGroup(_doc)) { tranGr.Start("wall penetration"); using (Transaction tran = new Transaction(_doc)) { tran.Start("Load family symbols"); FamilySymbol rectOpen = _doc.GetFamilySymbol("Extrusion", "Type 1"); FamilySymbol roundOpen = _doc.GetFamilySymbol("Extrusion_round", "Type 1"); tran.Commit(); foreach (Element intersector in intersectElement) { if (intersector is MEPCurve mep) { CutInMepCurve(tran, wall, mep, rectOpen, roundOpen); continue; } CutBasicRectangular(tran, wall, intersector, rectOpen); } } tranGr.Assimilate(); } }
public Result Execute(ExternalCommandData commandData, ref string message, ElementSet elements) { UIApplication uiapp = commandData.Application; UIDocument uidoc = uiapp.ActiveUIDocument; Application app = uiapp.Application; Document doc = uidoc.Document; Element element = doc.GetElement(uidoc.Selection.PickObject(ObjectType.Element)); using (TransactionGroup transg = new TransactionGroup(doc)) { transg.Start("Transaction Group"); //Exception(Out Side Transaction) //SetParameter(element,"Transaction Group"); using (Transaction tran = new Transaction(doc)) { tran.Start("Transaction"); SetParameter(element, "Transaction"); using (SubTransaction subtrans = new SubTransaction(doc)) { subtrans.Start(); SetParameter(element, "Sub Transaction"); subtrans.Commit(); } tran.Commit(); } transg.Commit(); } return Result.Succeeded; }
/// <summary> /// This method implements the external command within /// Revit. /// </summary> /// <param name="commandData">An ExternalCommandData /// object which contains reference to Application and /// View needed by external command.</param> /// <param name="message">Error message can be returned /// by external command. This will be displayed only if /// the command status was "Failed". There is a limit /// of 1023 characters for this message; strings longer /// than this will be truncated.</param> /// <param name="elements">Element set indicating /// problem elements to display in the failure dialog. /// This will be used only if the command status was /// "Failed".</param> /// <returns>The result indicates if the execution /// fails, succeeds, or was canceled by user. If it /// does not succeed, Revit will undo any changes made /// by the external command.</returns> Result IExternalCommand.Execute( ExternalCommandData commandData, ref string message , ElementSet elements) { ResourceManager res_mng = new ResourceManager( GetType()); ResourceManager def_res_mng = new ResourceManager( typeof(Properties.Resources)); Result result = Result.Failed; try { UIApplication ui_app = commandData?.Application ; UIDocument ui_doc = ui_app?.ActiveUIDocument; Application app = ui_app?.Application; Document doc = ui_doc?.Document; /* Wrap all transactions into the transaction * group. At first we get the transaction group * localized name. */ var tr_gr_name = UIBuilder.GetResourceString( GetType(), typeof(Properties.Resources), "_transaction_group_name"); using (var tr_gr = new TransactionGroup(doc, tr_gr_name)) { if (TransactionStatus.Started == tr_gr .Start()) { /* Here do your work or the set of * works... */ if (DoWork(commandData, ref message, elements)) { tr_gr.Assimilate(); tr_gr.Commit(); result = Result.Succeeded; } else { tr_gr.RollBack(); } } } } catch (Exception ex) { TaskDialog.Show(def_res_mng.GetString("_Error") , ex.Message); result = Result.Failed; } finally { res_mng.ReleaseAllResources(); def_res_mng.ReleaseAllResources(); } return(result); }
private void BtnCreate_Click(object sender, EventArgs e) { // check if at least one item is selected if (LsvWorksets.CheckedItems.Count == 0) { UI.Info.Form_Info1.infoMsgMain = "Selection"; UI.Info.Form_Info1.infoMsgBody = "Select one or more worksets from the list."; using (UI.Info.Form_Info1 thisForm = new Info.Form_Info1()) { thisForm.ShowDialog(); } } else { // collect selected worksets List <string> selectedWorksets = new List <string>(); foreach (ListViewItem item in LsvWorksets.CheckedItems) { selectedWorksets.Add(item.Text); } // check if workset name is in use usedNames = GetUsedNames(m_doc, selectedWorksets); if (usedNames.Any()) { using (UI.Info.Form_Warning thisForm = new UI.Info.Form_Warning()) { thisForm.ShowDialog(); } } // proceed if workset names are unique else { using (TransactionGroup tg = new TransactionGroup(m_doc, "Transfer Worksets")) { tg.Start(); createdWorksets.Clear(); // clear results list for when running the command more than once. foreach (string WorksetName in selectedWorksets) { using (Transaction t = new Transaction(m_doc, "Single Transaction")) { t.Start(); Workset newWorkset = null; newWorkset = Workset.Create(m_doc, WorksetName); createdWorksets.Add(WorksetName); t.Commit(); } } tg.Assimilate(); } // show Results Form using (UI.Info.Form_Results thisForm = new Info.Form_Results()) { thisForm.ShowDialog(); } DialogResult = DialogResult.OK; } } }
//starts a transaction group public void StartTransactions(string transactionName) { if (!transactionList.HasStarted()) { //prepare the transaction group and start it transactionList.Start(transactionName); } }
/// <summary> /// Executes on type to instance change /// </summary> /// <param name="uiapp"></param> /// <param name="text"></param> /// <param name="values"></param> private void ExecuteParameterChange(UIApplication uiapp, String text, List <string> values, string type) { UIDocument uidoc = uiapp.ActiveUIDocument; Document doc = uidoc.Document; if (!doc.IsFamilyDocument) { Command.global_message = "Please run this command in a family document."; TaskDialog.Show("Message", Command.global_message); } if ((uidoc != null)) { using (TransactionGroup tg = new TransactionGroup(doc, "Parameter Type To Instance")) { tg.Start(); using (Transaction trans = new Transaction(uidoc.Document)) { FailureHandlingOptions failureHandlingOptions = trans.GetFailureHandlingOptions(); FailureHandler failureHandler = new FailureHandler(); failureHandlingOptions.SetFailuresPreprocessor(failureHandler); failureHandlingOptions.SetClearAfterRollback(true); trans.SetFailureHandlingOptions(failureHandlingOptions); // Since we'll modify the document, we need a transaction // It's best if a transaction is scoped by a 'using' block // The name of the transaction was given as an argument if (trans.Start(text) == TransactionStatus.Started) { FamilyManager mgr = doc.FamilyManager; foreach (var value in values) { FamilyParameter fp = mgr.get_Parameter(value); if (fp.IsInstance) { mgr.MakeType(fp); } else { mgr.MakeInstance(fp); }; } } doc.Regenerate(); trans.Commit(); uidoc.RefreshActiveView(); if (failureHandler.ErrorMessage != "") { if (EncounteredError != null) { EncounteredError(this, null); } } } tg.Assimilate(); } } }
/// <summary> /// Animate the transparency of an element. This will export images of the element, then revert the element back to where it was. /// Inspired by the Bad Monkeys team. /// </summary> /// <param name="element">The element to set transparency to.</param> /// <param name="startPercentage">The transparency start percent.</param> /// <param name="endPercentage">The transparency end percent.</param> /// <param name="iterations">Numnber of images.</param> /// <param name="directoryPath">Where to save the images.</param> /// <param name="view">View to export from.</param> /// <returns name="element">The element.</returns> /// <search> /// rhythm /// </search> public static object AnimateTransparency(List <global::Revit.Elements.Element> element, int startPercentage, int endPercentage, int iterations, string directoryPath, global::Revit.Elements.Element view) { Autodesk.Revit.DB.Document doc = DocumentManager.Instance.CurrentDBDocument; UIDocument uiDocument = new UIDocument(doc); Autodesk.Revit.DB.View internalView = (Autodesk.Revit.DB.View)view.InternalElement; //create a new form! DefaultProgressForm statusBar = new DefaultProgressForm("Exporting Images", "Exporting image {0} of " + iterations.ToString(), "Animate Element Transparency", iterations + 1); double d = (endPercentage - startPercentage) / (iterations - 1.0); int incrementor = Convert.ToInt32(d); //starts a transaction group so we can roolback the changes after using (TransactionGroup transactionGroup = new TransactionGroup(doc, "group")) { TransactionManager.Instance.ForceCloseTransaction(); transactionGroup.Start(); using (Transaction t2 = new Transaction(doc, "Modify parameter")) { int num2 = 0; while (startPercentage <= endPercentage) { statusBar.Activate(); t2.Start(); //declare the graphic settings overrides OverrideGraphicSettings ogs = new OverrideGraphicSettings(); //solid fill id ElementId pattId = new ElementId(20); //set the overrides to the graphic settings ogs.SetSurfaceTransparency(startPercentage); foreach (var e in element) { //apply the changes to view internalView.SetElementOverrides(e.InternalElement.Id, ogs); } t2.Commit(); uiDocument.RefreshActiveView(); var exportOpts = new ImageExportOptions { FilePath = directoryPath + num2.ToString(), FitDirection = FitDirectionType.Horizontal, HLRandWFViewsFileType = ImageFileType.PNG, ImageResolution = ImageResolution.DPI_300, ShouldCreateWebSite = false }; doc.ExportImage(exportOpts); ++num2; startPercentage = startPercentage + incrementor; statusBar.Increment(); } } transactionGroup.RollBack(); } statusBar.Close(); return(element); }
public void RenameAllExecuted(object param) { using (TransactionGroup tg = new TransactionGroup(m_doc)) { tg.Start("Rename Families"); try { ProgressManager.InitializeProgress("Renaming.. ", typeProperties.Count); for (int i = 0; i < typeProperties.Count; i++) { ProgressManager.StepForward(); FamilyTypeProperties ftp = typeProperties[i]; if (ftp.IsLinked) { continue; } ElementType eType = m_doc.GetElement(ftp.FamilyTypeId) as ElementType; if (null != eType) { using (Transaction trans = new Transaction(m_doc)) { trans.Start("Rename"); try { if (eType is FamilySymbol) { (eType as FamilySymbol).Family.Name = ftp.FamilyName; } eType.Name = ftp.TypeName; trans.Commit(); typeProperties[i].CurrentFamilyName = ftp.FamilyName; typeProperties[i].CurrentTypeName = ftp.TypeName; typeProperties[i].IsLinked = true; typeProperties[i].ToolTip = "Current Family Name: " + ftp.FamilyName + ", Current Tyle Name: " + ftp.TypeName; typeProperties[i].IsSelected = false; } catch (Exception ex) { trans.RollBack(); string message = ex.Message; } } } } ProgressManager.FinalizeProgress(); this.StatusText = fileName; tg.Assimilate(); } catch (Exception ex) { tg.RollBack(); MessageBox.Show("Failed to rename families and types.\n" + ex.Message, "Rename Families and Types", MessageBoxButton.OK, MessageBoxImage.Warning); } } }
public void Start(Document docRvt) { //IL_0002: Unknown result type (might be due to invalid IL or missing references) //IL_000b: Unknown result type (might be due to invalid IL or missing references) //IL_000c: Unknown result type (might be due to invalid IL or missing references) //IL_0011: Unknown result type (might be due to invalid IL or missing references) //IL_0026: Unknown result type (might be due to invalid IL or missing references) //IL_002b: Unknown result type (might be due to invalid IL or missing references) //IL_002d: Unknown result type (might be due to invalid IL or missing references) //IL_003e: Unknown result type (might be due to invalid IL or missing references) //IL_00b1: Unknown result type (might be due to invalid IL or missing references) //IL_00b7: Unknown result type (might be due to invalid IL or missing references) //IL_00bc: Unknown result type (might be due to invalid IL or missing references) //IL_00bd: Unknown result type (might be due to invalid IL or missing references) //IL_00be: Unknown result type (might be due to invalid IL or missing references) //IL_00cf: Unknown result type (might be due to invalid IL or missing references) //IL_00ec: Unknown result type (might be due to invalid IL or missing references) //IL_00ed: Unknown result type (might be due to invalid IL or missing references) //IL_010b: Unknown result type (might be due to invalid IL or missing references) //IL_010e: Unknown result type (might be due to invalid IL or missing references) //IL_0116: Unknown result type (might be due to invalid IL or missing references) //IL_0126: Unknown result type (might be due to invalid IL or missing references) //IL_0127: Unknown result type (might be due to invalid IL or missing references) TransactionGroup val = null; try { StringBuilder stringBuilder = new StringBuilder(); foreach (Document document in docRvt.get_Application().get_Documents()) { if (document.get_IsFamilyDocument()) { stringBuilder.Append(document.get_Title() + "\n"); } } if (stringBuilder.Length > 0) { FamMgr_Util.ShowMessage(EnvMsg.CloseAllFamilyDocument + "\n\n" + stringBuilder); } else { val = new TransactionGroup(docRvt, "FamilyManager Basic"); val.Start(); IntPtr mainWindowHandle = Process.GetCurrentProcess().MainWindowHandle; (CEntry.FamilyUploaderDlg = new frmFamilyUploader(docRvt)).ShowDialog(new MainWin32Wnd(mainWindowHandle)); val.Commit(); } } catch (Exception ex) { FamMgr_Util.ShowMessage(FamMgr_Util.GetMessageString(ex.Message)); if ((int)val != 0 && val.HasStarted() && !val.HasEnded()) { val.RollBack(); } } }
public bool RunViewAnalysis(ProgressBar progressBar, TextBlock statusLable) { bool result = true; using (TransactionGroup tg = new TransactionGroup(m_doc)) { tg.Start("Run View Analysis"); try { UpdateLableDelegate updateLabelDelegate = new UpdateLableDelegate(statusLable.SetValue); List <int> keys = roomDictionary.Keys.ToList(); int finishedRoom = 0; foreach (int roomId in keys) { if (AbortFlag.GetAbortFlag()) { return(false); } using (Transaction trans = new Transaction(m_doc)) { trans.Start("Find Visibility"); try { RoomData rData = roomDictionary[roomId]; string roomInfo = rData.RoomObj.Name + " (" + finishedRoom + " of " + keys.Count + ")"; Dispatcher.CurrentDispatcher.Invoke(updateLabelDelegate, System.Windows.Threading.DispatcherPriority.Background, new object[] { TextBlock.TextProperty, roomInfo }); progressBar.Visibility = System.Windows.Visibility.Visible; RoomData updatedData = FindVisibility(rData, progressBar); roomDictionary.Remove(roomId); roomDictionary.Add(roomId, updatedData); finishedRoom++; trans.Commit(); } catch (Exception ex) { trans.RollBack(); result = false; string message = ex.Message; } } } tg.Assimilate(); } catch (Exception ex) { result = false; MessageBox.Show("Failed to run view analysis.\n" + ex.Message, "Run View Analysis", MessageBoxButton.OK, MessageBoxImage.Warning); tg.RollBack(); } } return(result); }
public Result Execute( ExternalCommandData commandData, ref string message, ElementSet elements) { UIApplication uiapp = commandData.Application; UIDocument uidoc = uiapp.ActiveUIDocument; Document doc = uidoc.Document; using( TransactionGroup g = new TransactionGroup( doc ) ) { g.Start( "Cut Beam with Voids" ); // Retrieve or load cutting symbol FamilySymbol cuttingSymbol = RetrieveOrLoadCuttingSymbol( doc ); // Select beam to cut Selection sel = uidoc.Selection; FamilyInstance beam = null; try { Reference r = sel.PickObject( ObjectType.Element, new BeamSelectionFilter(), "Pick beam to cut" ); beam = doc.GetElement( r.ElementId ) as FamilyInstance; } catch( Autodesk.Revit.Exceptions .OperationCanceledException ) { return Result.Cancelled; } // Place cutting instances and apply cuts CutBeamWithVoid( beam, cuttingSymbol ); g.Assimilate(); // Calling Commit after Assimilate throws an // exception saying "The Transaction group has // not been started (its status is not // 'Started').." //g.Commit(); } return Result.Succeeded; }
private bool AssignParameter(XYZLocation xyzLocation) { var assigned = false; using (var tg = new TransactionGroup(m_doc)) { tg.Start("Assign Parameters"); try { foreach (var eId in instanceIds) { using (var trans = new Transaction(m_doc)) { trans.Start("Assign Parameter"); try { var instance = m_doc.GetElement(eId) as FamilyInstance; if (null != instance) { var locationPt = instance.Location as LocationPoint; var point = locationPt.Point; XYZ location1; XYZ location2; xyzLocation.GetTransformedValues(point, out location1, out location2); //assign parameters var paramSet = SetParameterValue(instance, "XYZ_Location_1_Description", xyzLocation.Description1); paramSet = SetParameterValue(instance, "XYZ_Location_1_X", location1.X); paramSet = SetParameterValue(instance, "XYZ_Location_1_Y", location1.Y); paramSet = SetParameterValue(instance, "XYZ_Location_1_Z", location1.Z); paramSet = SetParameterValue(instance, "XYZ_Location_2_Description", xyzLocation.Description2); paramSet = SetParameterValue(instance, "XYZ_Location_2_X", location2.X); paramSet = SetParameterValue(instance, "XYZ_Location_2_Y", location2.Y); paramSet = SetParameterValue(instance, "XYZ_Location_2_Z", location2.Z); } trans.Commit(); } catch (Exception ex) { trans.RollBack(); var messag = ex.Message; } } } tg.Assimilate(); } catch (Exception ex) { tg.RollBack(); var message = ex.Message; } } return(assigned); }
/// <summary> /// Start transaction group button click event /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void btnStartTransGroup_Click(object sender, EventArgs e) { m_transGroupCount++; m_transactionGroup = new TransactionGroup(m_document, "Transaction Group " + m_transGroupCount.ToString()); m_transactionGroup.Start(); AddNode(OperationType.StartTransactionGroup); UpdateButtonsStatus(); }
/// <summary> /// Constructor /// </summary> /// <param name="commandData">the external command data</param> public TransactionForm(ExternalCommandData commandData) { m_commandData = commandData; m_document = m_commandData.Application.ActiveUIDocument.Document; if (m_document == null) { MessageBox.Show("There is no active document."); } InitializeComponent(); // created the root node m_rootNode = new TreeNode("Command history"); this.transactionsTreeView.Nodes.Add(m_rootNode); // set availability of form buttons UpdateButtonsStatus(); // start the main transaction group (will be hidden to the user) m_mainTtransactionGroup = new TransactionGroup(m_document); m_mainTtransactionGroup.Start(); }
/// <summary> /// Implement this method as an external command for Revit. /// </summary> /// <param name="commandData">An object that is passed to the external application /// which contains data related to the command, /// such as the application object and active view.</param> /// <param name="message">A message that can be set by the external application /// which will be displayed if a failure or cancellation is returned by /// the external command.</param> /// <param name="elements">A set of elements to which the external application /// can add elements that are to be highlighted in case of failure or cancellation.</param> /// <returns>Return the status of the external command. /// A result of Succeeded means that the API external method functioned as expected. /// Cancelled can be used to signify that the user cancelled the external operation /// at some point. Failure should be returned if the application is unable to proceed with /// the operation.</returns> public Autodesk.Revit.UI.Result Execute(ExternalCommandData commandData, ref string message, Autodesk.Revit.DB.ElementSet elements) { // data verification if (null == commandData.Application.ActiveUIDocument) { return Autodesk.Revit.UI.Result.Failed; } MyDocument mydocument = new MyDocument(commandData); // check whether the mass is kind of parallelepiped CurtainSystem.MassChecker checker = new CurtainSystem.MassChecker(mydocument); bool validMass = checker.CheckSelectedMass(); if (!validMass) { message = Properties.Resources.MSG_InvalidSelection; return Result.Cancelled; } UI.CurtainForm curtainForm = null; TransactionGroup transactionGroup = new TransactionGroup(commandData.Application.ActiveUIDocument.Document); try { transactionGroup.Start("CurtainSystemOperation"); curtainForm = new UI.CurtainForm(mydocument); if (null != curtainForm && false == curtainForm.IsDisposed) { curtainForm.ShowDialog(); } transactionGroup.Commit(); } catch (System.Exception ex) { transactionGroup.RollBack(); message = ex.Message; return Result.Failed; } finally { if (null != curtainForm && false == curtainForm.IsDisposed) { curtainForm.Dispose(); } } return Autodesk.Revit.UI.Result.Succeeded; }
public void QTO_2_PlaceHoldersFromDWFMarkups( Document doc, string activityId) { View activeView = doc.ActiveView; if( !( activeView is ViewSheet ) ) { TaskDialog.Show( "QTO", "The current view must be a Sheet View with DWF markups" ); return; } ViewSheet vs = activeView as ViewSheet; Viewport vp = doc.GetElement( vs.GetAllViewports().First() ) as Viewport; View plan = doc.GetElement( vp.ViewId ) as View; int scale = vp.Parameters.Cast<Parameter>() .First( x => x.Id.IntegerValue.Equals( (int) BuiltInParameter.VIEW_SCALE ) ) .AsInteger(); IEnumerable<Element> dwfMarkups = new FilteredElementCollector( doc ) .OfClass( typeof( ImportInstance ) ) .WhereElementIsNotElementType() .Where( x => x.Name.StartsWith( "Markup" ) && x.OwnerViewId.IntegerValue.Equals( activeView.Id.IntegerValue ) ); using( TransactionGroup tg = new TransactionGroup( doc ) ) { tg.Start( "DWF markups placeholders" ); using( Transaction t = new Transaction( doc ) ) { t.Start( "DWF Transfer" ); plan.Parameters.Cast<Parameter>() .First( x => x.Id.IntegerValue.Equals( (int) BuiltInParameter.VIEWER_CROP_REGION ) ) .Set( 1 ); XYZ VC = ( plan.CropBox.Min + plan.CropBox.Max ) / 2; XYZ BC = vp.GetBoxCenter(); t.RollBack(); foreach( Element e in dwfMarkups ) { GeometryElement GeoElem = e.get_Geometry( new Options() ); GeometryInstance gi = GeoElem.Cast<GeometryInstance>().First(); GeometryElement gei = gi.GetSymbolGeometry(); IList<GeometryObject> gos = new List<GeometryObject>(); if( gei.Cast<GeometryObject>().Count( x => x is Arc ) > 0 ) { continue; } foreach( GeometryObject go in gei ) { XYZ med = new XYZ(); if( go is PolyLine ) { PolyLine pl = go as PolyLine; XYZ min = new XYZ( pl.GetCoordinates().Min( p => p.X ), pl.GetCoordinates().Min( p => p.Y ), pl.GetCoordinates().Min( p => p.Z ) ); XYZ max = new XYZ( pl.GetCoordinates().Max( p => p.X ), pl.GetCoordinates().Max( p => p.Y ), pl.GetCoordinates().Max( p => p.Z ) ); med = ( min + max ) / 2; } med = med - BC; // Convert DWF sheet coordinates into model coordinates XYZ a = VC + new XYZ( med.X * scale, med.Y * scale, 0 ); } } t.Start( "DWF Transfer" ); foreach( Element e in dwfMarkups ) { GeometryElement GeoElem = e.get_Geometry( new Options() ); GeometryInstance gi = GeoElem.Cast<GeometryInstance>().First(); GeometryElement gei = gi.GetSymbolGeometry(); IList<GeometryObject> gos = new List<GeometryObject>(); if( gei.Cast<GeometryObject>().Count( x => x is Arc ) == 0 ) { continue; } foreach( GeometryObject go in gei ) { if( go is Arc ) { Curve c = go as Curve; XYZ med = c.Evaluate( 0.5, true ); med = med - BC; XYZ a = VC + new XYZ( med.X * scale, med.Y * scale, 0 ); // Warning CS0618: // Autodesk.Revit.Creation.ItemFactoryBase.NewTextNote( // View, XYZ, XYZ, XYZ, double, TextAlignFlags, string) // is obsolete: // This method is deprecated in Revit 2016. // Please use one of the TextNote.Create methods instead. //doc.Create.NewTextNote( plan, // a, // XYZ.BasisX, // XYZ.BasisY, // MMtoFeet( 5 ), // TextAlignFlags.TEF_ALIGN_CENTER, // activityId ); ElementId textTypeId = new FilteredElementCollector( doc ) .OfClass( typeof( TextNoteType ) ) .FirstElementId(); TextNote.Create( doc, plan.Id, a, activityId, textTypeId ); } } t.Commit(); } } tg.Assimilate(); } }
public static Result Execute2( ExternalCommandData commandData, bool exportToSatFormat) { UIApplication uiapp = commandData.Application; UIDocument uidoc = uiapp.ActiveUIDocument; Application app = uiapp.Application; Document doc = uidoc.Document; if( null == doc ) { ErrorMsg( "Please run this command in a valid" + " Revit project document." ); return Result.Failed; } View view = doc.ActiveView; if( null == view || !( view is View3D ) ) { ErrorMsg( "Please run this command in a valid" + " 3D view." ); return Result.Failed; } if( PartsVisibility.ShowPartsOnly != view.PartsVisibility ) { ErrorMsg( "Please run this command in a view" + " displaying parts and not source elements." ); return Result.Failed; } // Define the list of views to export, // including only the current 3D view List<ElementId> viewIds = new List<ElementId>( 1 ); viewIds.Add( view.Id ); // Iterate over all pre-selected parts List<ElementId> ids = null; Selection sel = uidoc.Selection; ICollection<ElementId> selIds = sel.GetElementIds(); // 2015 //if( 0 < sel.Elements.Size ) // 2014 if( 0 < selIds.Count ) // 2015 { //foreach( Element e in sel.Elements ) // 2014 foreach( ElementId id in selIds ) // 2015 { Element e = doc.GetElement( id ); if( !( e is Part ) ) { ErrorMsg( "Please pre-select only gyp wallboard" + " parts before running this command." ); return Result.Failed; } Part part = e as Part; ICollection<LinkElementId> lids = part.GetSourceElementIds(); if( 1 != lids.Count ) { ErrorMsg( "Gyp wallboard part has multiple" + " source elements." ); return Result.Failed; } LinkElementId lid = lids.First<LinkElementId>(); ElementId hostId = lid.HostElementId; ElementId linkedId = lid.LinkedElementId; ElementId parentId = hostId; ElementId partId = e.Id; // Determine parent category Element parent = doc.GetElement( parentId ); Category cat = parent.Category; ICollection<ElementId> cids = part.GetSourceElementOriginalCategoryIds(); if( 1 != cids.Count ) { ErrorMsg( "Gyp wallboard part has multiple" + " source element categories." ); return Result.Failed; } ElementId cid = cids.First<ElementId>(); //cat = doc.GetElement( id ) as Category; // Expected parent category is OST_Walls BuiltInCategory bic = (BuiltInCategory) cid.IntegerValue; if( BuiltInCategory.OST_Walls != bic ) { ErrorMsg( "Please pre-select only " + " gyp wallboard parts." ); return Result.Failed; } if( null == ids ) { ids = new List<ElementId>( 1 ); } ids.Add( partId ); } if( null == ids ) { ErrorMsg( "Please pre-select only gyp wallboard" + " parts before running this command." ); return Result.Failed; } } // If no parts were pre-selected, // prompt for post-selection if( null == ids ) { IList<Reference> refs = null; try { refs = sel.PickObjects( ObjectType.Element, new WallPartSelectionFilter(), "Please select wall parts." ); } catch( Autodesk.Revit.Exceptions .OperationCanceledException ) { return Result.Cancelled; } ids = new List<ElementId>( refs.Select<Reference, ElementId>( r => r.ElementId ) ); } if( 0 == ids.Count ) { ErrorMsg( "No valid parts selected." ); return Result.Failed; } // Check for shared parameters // to record export history ExportParameters exportParameters = new ExportParameters( doc.GetElement( ids[0] ) ); if( !exportParameters.IsValid ) { ErrorMsg( "Please initialise the CNC fabrication " + "export history shared parameters before " + "launching this command." ); return Result.Failed; } if( !Util.BrowseDirectory( ref _folder, true ) ) { return Result.Cancelled; } try { // Register event handler for // "TaskDialog_Really_Print_Or_Export_Temp_View_Modes" // dialogue uiapp.DialogBoxShowing += new EventHandler<DialogBoxShowingEventArgs>( OnDialogBoxShowing ); object opt = exportToSatFormat ? (object) new SATExportOptions() : (object) new DXFExportOptions(); //opt.FileVersion = ACADVersion.R2000; string filename; using( TransactionGroup txg = new TransactionGroup( doc ) ) { txg.Start( "Export Wall Parts" ); foreach( ElementId id in ids ) { Element e = doc.GetElement( id ); Debug.Assert( e is Part, "expected parts only" ); Part part = e as Part; ICollection<LinkElementId> lids = part.GetSourceElementIds(); Debug.Assert( 1 == lids.Count, "unexpected multiple part source elements." ); LinkElementId lid = lids.First<LinkElementId>(); ElementId hostId = lid.HostElementId; ElementId linkedId = lid.LinkedElementId; ElementId parentId = hostId; ElementId partId = e.Id; filename = string.Format( "{0}_{1}", parentId, partId ); Element host = doc.GetElement( hostId ); Debug.Assert( null != host, "expected to be able to access host element" ); //Debug.Assert( ( host is Wall ), "expected host element to be a wall" ); Debug.Assert( ( host is Wall ) || ( host is Part ), "expected host element to be a wall or part" ); Debug.Assert( null != host.Category, "expected host element to have a valid category" ); //Debug.Assert( host.Category.Id.IntegerValue.Equals( (int) BuiltInCategory.OST_Walls ), "expected host element to have wall category" ); Debug.Assert( host.Category.Id.IntegerValue.Equals( (int) BuiltInCategory.OST_Walls ) || host.Category.Id.IntegerValue.Equals( (int) BuiltInCategory.OST_Parts ), "expected host element to have wall or part category" ); Debug.Assert( ElementId.InvalidElementId != host.LevelId, "expected host element to have a valid level id" ); if( ElementId.InvalidElementId != host.LevelId ) { Element level = doc.GetElement( host.LevelId ); filename = level.Name.Replace( ' ', '_' ) + "_" + filename; } if( view.IsTemporaryHideIsolateActive() ) { using( Transaction tx = new Transaction( doc ) ) { tx.Start( "Disable Temporary Isolate" ); view.DisableTemporaryViewMode( TemporaryViewMode.TemporaryHideIsolate ); tx.Commit(); } Debug.Assert( !view.IsTemporaryHideIsolateActive(), "expected to turn off temporary hide/isolate" ); } using( Transaction tx = new Transaction( doc ) ) { tx.Start( "Export Wall Part " + partId.ToString() ); // This call requires a transaction. view.IsolateElementTemporary( partId ); //List<ElementId> unhideIds = new List<ElementId>( 1 ); //unhideIds.Add( partId ); //view.UnhideElements( unhideIds ); //doc.Regenerate(); // this is insufficient tx.Commit(); } if( exportToSatFormat ) { //ViewSet viewSet = new ViewSet(); // //foreach( ElementId vid in viewIds ) //{ // viewSet.Insert( doc.GetElement( vid ) // as View ); //} // //doc.Export( _folder, filename, viewSet, // (SATExportOptions) opt ); // 2013 doc.Export( _folder, filename, viewIds, (SATExportOptions) opt ); // 2014 } else { doc.Export( _folder, filename, viewIds, (DXFExportOptions) opt ); } // Update CNC fabrication // export shared parameters -- oops, // cannot do this immediately, since // this transaction group will be // rolled back ... just save the // element id and do it later // searately. //exportParameters.UpdateExportHistory( e ); exportParameters.Add( e.Id ); } // We do not commit the transaction group, // because no modifications should be saved. // The transaction group is only created and // started to encapsulate the transactions // required by the IsolateElementTemporary // method. Since the transaction group is not // committed, the changes are automatically // discarded. //txg.Commit(); } } finally { uiapp.DialogBoxShowing -= new EventHandler<DialogBoxShowingEventArgs>( OnDialogBoxShowing ); } using( Transaction tx = new Transaction( doc ) ) { tx.Start( "Update CNC Fabrication Export " + "History Shared Parameters" ); exportParameters.UpdateExportHistory(); tx.Commit(); } return Result.Succeeded; }