def check_empty_assembly_code(self, selected_code):

        self.sublabel_no_selection.Text = ""

        ids = list()

        element_instances = []

        for i, v in id_empty_dict.iteritems():
            if len(v) == 0:
                element_instances.append(i.Id)
                ids.append(i.Id)

        self.sublabel_objects.Text = "Number of Objects Current Selection: " + str(
            len(ids))
        assembly_codes_selected = '-'
        self.sublabel.Text = "Number of Assembly Codes Selected: " + str(
            assembly_codes_selected)

        #Hide Reset Active View
        t = Transaction(doc, 'Reset HideIsolate')
        t.Start()
        view.TemporaryViewModes.DeactivateAllModes()
        t.Commit()

        idElements = List[ElementId](ids)

        #Hide Isolate Objects in Active View
        t = Transaction(doc, 'Filter Elements')
        t.Start()
        view.IsolateElementsTemporary(idElements)
        t.Commit()
Exemple #2
0
def createobj(type):

    # get Drafting View named "xForm" for object creation and Selection.
    fecv = DB.FilteredElementCollector(doc).OfClass(DB.ViewDrafting) \
            .WhereElementIsNotElementType().ToElements()
    dv = [i for i in fecv if i.ViewName.Equals("xForm")]
    draftview = dv[0] if dv else None

    if not draftview:
        t = Transaction(doc, "xForm")
        t.Start()
        fec = DB.FilteredElementCollector(doc).OfClass(
            DB.ViewFamilyType).ToElements()
        viewdrafttype = [
            i for i in fec if i.ViewFamily.Equals(DB.ViewFamily.Drafting)
        ][0]
        draftview = DB.ViewDrafting.Create(doc, viewdrafttype.Id)
        draftview.Name = "xForm"
        t.Commit()
        print draftview.Name

    # Get line of linestyle = type
    fec = FilteredElementCollector(doc).OfCategory(DB.BuiltInCategory.OST_Lines) \
                .ToElements()
    detailc = [
        i for i in fec
        if i.CurveElementType.Equals(DB.CurveElementType.DetailCurve)
    ]
    li = [i for i in detailc if i.LineStyle.Id.Equals(type.Id)]
    line = li[0] if li else None

    if not line:
        print "line not found"

        try:
            t = Transaction(doc, "Draw Line")
            t.Start()
            linee = DB.Line.CreateBound(XYZ.Zero, XYZ(0, 10, 0))
            line = doc.Create.NewDetailCurve(draftview, linee)
            print type
            line.LineStyle = type
            t.Commit()
        except:
            import traceback
            print traceback.format_exc()

    if line and draftview:
        # Select it/Add it to Selection
        listId = List[ElementId]()
        listId.Add(line.Id)
        uidoc.Selection.SetElementIds(listId)
        # Start CreateSimilar Command.
        try:
            revitcomid = UI.RevitCommandId.LookupPostableCommandId(
                UI.PostableCommand.CreateSimilar)
            if revitcomid:
                uiapp.PostCommand(revitcomid)
        except:
            import traceback
            print traceback.format_exc()
    def check_for_selected_code(self, selected_code):

        if len(selected_code) == 0:

            self.sublabel_no_selection.Text = "Please select an Assembly Code First!"

        if len(selected_code) > 0:

            self.sublabel.Text = "Number of Assembly Codes Selected: " + str(
                len(selected_code))

            ids = list()

            for i, v in id_assembly_dict.iteritems():
                if len(v) > 1:
                    for code in selected_code:
                        if v[0] == code:
                            ids.append(i.Id)

            self.sublabel_objects.Text = "Number of Objects Current Selection: " + str(
                len(ids))

            #Hide Reset Active View
            t = Transaction(doc, 'Reset HideIsolate')
            t.Start()
            view.TemporaryViewModes.DeactivateAllModes()
            t.Commit()

            idElements = List[ElementId](ids)

            #Hide Isolate Objects in Active View
            t = Transaction(doc, 'Filter Elements')
            t.Start()
            view.IsolateElementsTemporary(idElements)
            t.Commit()
Exemple #4
0
def DeleteExcessLineStyles(doc, list, start_time, limit):
    lineStyle = doc.Settings.Categories.get_Item(
        BuiltInCategory.OST_Lines).SubCategories
    standard = {}
    for i in lineStyle:
        # individual transactions
        t = Transaction(doc, 'Delete Excess Line Styles')
        t.Start()
        if not i.Name in list and i.Name[
                0] != '<' and i.Id.IntegerValue > 0 and time.time(
                ) - start_time < limit:
            try:
                if i.Name[0:5] == prefix:
                    standard[i.Name] = i
                else:
                    print('Deleting Line Style ' + i.Name)
                    doc.Delete(i.Id)

            except:
                print('Failed to Delete ' + i.Name)
        t.Commit()

    sel_delete = forms.SelectFromList.show(standard.keys(),
                                           button_name='Select Item',
                                           multiselect=True)
    for s in sel_delete:
        if time.time() - start_time < limit:
            t = Transaction(doc, 'Delete Excess Line Styles')
            t.Start()
            print('Deleting Line Style ' + standard[s].Name)
            doc.Delete(standard[s].Id)
            t.Commit()
def firstrun():
    # get Drafting View named "xForm" for object creation and Selection.
    fecv = DB.FilteredElementCollector(doc).OfClass(DB.ViewDrafting) \
            .WhereElementIsNotElementType().ToElements()
    dv = [i for i in fecv if i.ViewName.Equals("xForm")]
    draftview = dv[0] if dv else None
    #print "no draftview, create one", draftview

    if not draftview:
        t = Transaction(doc, "xForm")
        t.Start()
        fec = DB.FilteredElementCollector(doc).OfClass(
            DB.ViewFamilyType).ToElements()
        viewdrafttype = [
            i for i in fec if i.ViewFamily.Equals(DB.ViewFamily.Drafting)
        ][0]
        draftview = DB.ViewDrafting.Create(doc, viewdrafttype.Id)
        draftview.Name = "xForm"
        t.Commit()
        #print draftview, draftview.Name

    lines = FilteredElementCollector(doc, draftview.Id) \
                .OfCategory(DB.BuiltInCategory.OST_Lines) \
                .ToElements()

    if not lines:
        #print "NO line"
        t = Transaction(doc, "Draw Line")
        t.Start()
        linee = DB.Line.CreateBound(XYZ.Zero, XYZ(0, 10, 0))
        singleline = doc.Create.NewDetailCurve(draftview, linee)
        t.Commit()
        lines = List[Element]()
        lines.Add(singleline)

    lstyles = sorted([(doc.GetElement(i).Name, doc.GetElement(i))
                      for i in lines[0].GetLineStyleIds()])
    #print len(lstyles), len(lines)

    if not len(lstyles) == len(lines):
        t = Transaction(doc, "Create Lines with Linestyles")
        t.Start()
        [doc.Delete(i.Id) for i in lines]
        for i in range(len(lstyles)):
            linee = DB.Line.CreateBound(XYZ(i * 2, 0, 0), XYZ(i * 2, 10, 0))
            line = doc.Create.NewDetailCurve(draftview, linee)
            line.LineStyle = lstyles[i][1]
        t.Commit()
    return lstyles
Exemple #6
0
def firstrun():
    # get Drafting View named "xForm" for object creation and Selection.
    fecv = DB.FilteredElementCollector(doc).OfClass(DB.ViewDrafting) \
            .WhereElementIsNotElementType().ToElements()
    dv = [i for i in fecv if i.ViewName.Equals("xForm")]
    draftview = dv[0] if dv else None

    if not draftview:
        t = Transaction(doc, "xForm")
        t.Start()
        fec = DB.FilteredElementCollector(doc).OfClass(
            DB.ViewFamilyType).ToElements()
        viewdrafttype = [
            i for i in fec if i.ViewFamily.Equals(DB.ViewFamily.Drafting)
        ][0]
        draftview = DB.ViewDrafting.Create(doc, viewdrafttype.Id)
        draftview.Name = "xForm"
        draftview.Scale = 100
        t.Commit()
        #print draftview, draftview.Name

    notes = FilteredElementCollector(doc, draftview.Id).OfClass(TextNote) \
                .WhereElementIsNotElementType() \
                .ToElements()

    notetypes = sorted(
        DB.FilteredElementCollector(doc).OfClass(DB.TextNoteType).ToElements(),
        key=lambda x: x.get_Parameter(DB.BuiltInParameter.SYMBOL_NAME_PARAM
                                      ).AsString())

    if not notes or not len(notes) == len(notetypes):

        # TextNote Create( Document document, ElementId viewId, XYZ position, string text, ElementId typeId )
        t = Transaction(doc,
                        "Create TextNotes of all TextTypes in DraftingView")
        t.Start()
        if not len(notes) == len(notetypes):
            [doc.Delete(i.Id) for i in notes]

        for i, j in enumerate(notetypes):
            text = j.get_Parameter(
                DB.BuiltInParameter.SYMBOL_NAME_PARAM).AsString()
            textnote = DB.TextNote.Create(doc, draftview.Id,
                                          XYZ(0, -i * 3.5, 0), text, j.Id)
        t.Commit()

    return [(i.get_Parameter(DB.BuiltInParameter.SYMBOL_NAME_PARAM).AsString(),
             i) for i in notetypes]  # Tupel
Exemple #7
0
 def button_find_replace(self, sender, e):
     t = Transaction(doc, __title__)
     t.Start()
     for TN in self.selected_text_notes:
         TN.Text = self.prefix + str(TN.Text).replace(
             self.find, self.replace) + self.suffix
     t.Commit()
Exemple #8
0
def delete_elements(type):
    t = Transaction(doc, "Delete selection")
    t.Start()
    for elid in uidoc.Selection.GetElementIds():
        #print elid
        doc.Delete(elid)
    t.Commit()
Exemple #9
0
 def btnDeleteFilters_Click(self, sender, args):
     selected_Filters_Name = self.lbFiltersName.SelectedItems #cant use global?
     selected_Filters = map(lambda f: filter_source[filter_names.index(f)],
                            selected_Filters_Name) #cant use global?
     if not selected_Filters:
         warningDialog.MainContent = "No Filter is selected!"
         warningDialog.DefaultButton = UI.TaskDialogResult.Cancel
         warningDialog.Show()
     else:
         warningDialog.MainContent = "{} will be deleted.\n Are you sure?".\
                                     format(map(lambda x: x,\
                                                selected_Filters_Name))
         warningDialog.CommonButtons = UI.TaskDialogCommonButtons.Yes\
                                     | UI.TaskDialogCommonButtons.No
         warnDialog = warningDialog.Show()
         if warnDialog == UI.TaskDialogResult.Yes:
             trans = Transaction(doc, "Delete Filters")
             trans.Start()
             map(lambda x: viewInstance.RemoveFilter(x), selected_Filters)
             trans.Commit()
     
     #Update Filters List
     view_Instance_Name_ = self.cbbViewName.SelectedItem
     if view_Instance_Name_ in view_Source_Name:
         filter_Source_ = view_Source[view_Source_Name.\
                                      index(view_Instance_Name_)].GetFilters()
     self.lbFiltersName.ItemsSource = map(lambda i: doc.GetElement(i).Name,\
                                          filter_Source_)
Exemple #10
0
class Action:
    def __init__(self, name=None):
        self.transaction = Transaction(doc, name if name else DEFAULT_TRANSACTION_NAME)

    def __enter__(self):
        self.transaction.Start()
        return self.transaction

    def __exit__(self, exception, exception_value, traceback):
        if exception:
            self.transaction.RollBack()
            logger.error('Error in Transaction Context. Rolling back changes. | {}:{}'.format(exception,
                                                                                              exception_value))
        else:
            try:
                self.transaction.Commit()
            except Exception as errmsg:
                self.transaction.RollBack()
                logger.error('Error in Transaction Commit. Rolling back changes. | {}'.format(errmsg))

    @staticmethod
    def carryout(name):
        from functools import wraps

        def wrap(f):
            @wraps(f)
            def wrapped_f(*args, **kwargs):
                with Action(name):
                    return_value = f(*args, **kwargs)
                return return_value
            return wrapped_f
        return wrap
Exemple #11
0
    def ok_click(self, sender, e):
        room_doc = self.source_project.SelectedItem
        space_doc = self.target_project.SelectedItem
        room = room_doc.GetElement(self.sample_room_id)
        space = space_doc.GetElement(self.sample_space_id)

        # Try RoomToSpace with sample room and space to make sure it works before batch on all with all spaces
        try:
            t = Transaction(space_doc, "Test")
            t.Start()
            self.room_to_space(room, space)
        except ValueError as e:
            logger.info("{}".format(e.message))
            t.RollBack()
            return
        except TypeError as e:
            logger.info("Is target parameter empty ?")
            t.RollBack()
            return
        t.RollBack()

        # Copy from values from
        with rpw.db.Transaction(doc=space_doc, name="RoomToSpace"):
            for space in FilteredElementCollector(
                    self.target_project.SelectedItem).OfCategory(
                        BuiltInCategory.OST_MEPSpaces):
                if space.Location:
                    room = room_doc.GetRoomAtPoint(space.Location.Point)
                if room:
                    self.room_to_space(room, space)
        self.Close()
def load_family(folder_path='Insert Path Here',
                file_name='Insert File Name Here'):
    'Loads a family into the Revit project with path and file name.'
    family_path = os.path.join(folder_path, file_name)
    if os.path.exists(family_path) is False:
        return 'Path does not exist.'

    family_loaded = clr.Reference[Autodesk.Revit.DB.Family]()
    t = Transaction(doc)
    t.Start('Load Family')

    loaded = doc.LoadFamily(family_path, FamilyLoadOptions(), family_loaded)
    if loaded:
        family = family_loaded.Value
        symbols = []

        for family_symbol_id in family.GetFamilySymbolIds():
            family_symbol = doc.GetElement(family_symbol_id)
            symbols.append(family_symbol)

        for s in symbols:
            try:
                s.Activate()
            except:
                pass

        t.Commit()
        return symbols

    else:
        t.Commit()
        return 'Family already exists in project.'
Exemple #13
0
 def Execute(self, app):
     if start_increase.GetValue()['Да'] or end_increase.GetValue()['Да']:
         t = Transaction(doc, 'Добавить учащение')
         t.Start()
         rebar = RB_Rebar(selection[0])
         path_length = rebar.ArrayLength
         normale = rebar.Normal
         start_space = rebar.rebar.MaxSpacing
         reb_count = int(ceil(path_length / start_space))
         biv = (path_length - (reb_count - 1) * start_space)
         rebars = List[ElementId]()
         rebars.Add(rebar.rebar.Id)
         if end_increase.GetValue()['Да'] and start_increase.GetValue(
         )['Да']:
             biv = biv / 2
         if biv > to_feet(20):
             rebar.SetAsNumberWithSpacing(reb_count, start_space)
             if start_increase.GetValue()['Да']:
                 rebar.translate(normale * biv)
                 tr = rebar.copy_by_normal_length(normale * -biv)
                 tr.SetAsSingle()
                 rebars.Add(tr.rebar.Id)
             if end_increase.GetValue()['Да']:
                 tr = rebar.copy_by_normal_length(
                     normale * (start_space * (reb_count - 1) + biv))
                 tr.SetAsSingle()
                 rebars.Add(tr.rebar.Id)
             __revit__.ActiveUIDocument.Selection.SetElementIds(rebars)
         t.Commit()
     FORM.Close()
Exemple #14
0
def create_gird(scoord,
                ecoord,
                name_gird
                ):
    # context-like objects that guard any 
    # changes made to a Revit model
    t = Transaction(doc, "Create grids")

    # Starts the transaction.
    t.Start()

    # create line reference 
    line_ref = Line.CreateBound(scoord, ecoord)

    # create gird  
    grid_ins = Grid.Create(doc, line_ref)

    # retrieve name for gird 
    name = grid_ins.get_Parameter(BuiltInParameter.DATUM_TEXT)

    # set name for gird 
    name.Set(name_gird)

    # Commits all changes made 
    # to the model during the transaction.
    t.Commit()
Exemple #15
0
def link_method_ifc():
    files_filter = "IFC files (*.ifc)|*.ifc"
    files = pick_files(files_filter)
    for f in files:
        t = Transaction(doc)
        t.Start(__title__)
        f_cache = f + ".rvt"
        recreate = not os.path.exists(f_cache)
        logger.debug("Recreate ifc %s = %s" % (f, recreate))
        # try:
        o = RevitLinkOptions(False)
        # create empty doc
        if recreate:
            doc_ifc = HOST_APP.app.OpenIFCDocument(f)
            save_options = SaveAsOptions()
            save_options.OverwriteExistingFile = True
            doc_ifc.SaveAs(f_cache, save_options)
            doc_ifc.Close()

        link_load_results = RevitLinkType.CreateFromIFC(doc, f, f_cache, False, o)
        # TODO log results http://www.revitapidocs.com/2019/11b095e1-24d9-91b9-ae2e-004f67c94d6e.htm
        logger.debug(link_load_results.LoadResult)
        instance = RevitLinkInstance.Create(doc, link_load_results.ElementId)
        status = True
        # except Exception as e:
        #     logger.error("Unable to import IFC")
        #     logger.error(e)
        #     status = False
        #     instance = None

        if status:
            instance.Pinned = True
            t.Commit()
        else:
            t.RollBack()
Exemple #16
0
    def button_title(self, sender, e):
        t = Transaction(doc, __title__)
        t.Start()

        for TN in self.selected_text_notes:
            TN.Text = str(TN.Text).title()
        t.Commit()
Exemple #17
0
def SetParameterInstance(ElementInstance, ParameterName, ParameterValue):
    ElementInstance = ElementInstance.Symbol
    Parameter = ElementInstance.LookupParameter(ParameterName)
    t = Transaction(doc, "Set parameter")
    t.Start()
    Parameter.Set(ParameterValue)
    t.Commit()
Exemple #18
0
    def find_linked_elements(self):
        t = Transaction(doc, "Search for linked elements")
        t.Start()
        linked_element_ids = doc.Delete(self._rvt_type.Id)
        t.RollBack()

        return linked_element_ids
Exemple #19
0
    def run(self, sender, args):
        text_find = self.text_find
        text_replace = self.text_replace
        count_changed = 0
        t = Transaction(doc, __title__)
        t.Start()

        for e in self.selection:
            definition = self.parameter_to_set.Definition
            param = e.get_Parameter(definition)
            param_before = param.AsString()
            param_after = param_before.replace(text_find, text_replace)

            if param_before != param_after:
                count_changed += 1
                self.parameter_value_set(param, param_after)

        if count_changed:
            t.Commit()
            TaskDialog.Show(
                __title__, "%d of %d elements updated" % (
                    count_changed,
                    len(self.selection),
                ))
        else:
            t.RollBack()
            TaskDialog.Show(__title__, "Nothing was updated")
def parameterupdate(exel_datalist):
    #Create a list from FECsheets matching ex_row_paralist in Project
    # using SheetNR for Equality Check, do this with FEC?
    sheetviews = []
    excel_data = []
    for i in exel_datalist:
        if i[0] and i[1] and i[5]:
            for j in FECsheet:
                if j.SheetNumber == i[0]:
                    sheetviews.append(j)
                    excel_data.append(i)
    #GUID BuiltInParameter ---------------------------
    sheet_issuedate = DB.BuiltInParameter.SHEET_ISSUE_DATE
    sheet_drawnby = DB.BuiltInParameter.SHEET_DRAWN_BY
    mess = []
    t = Transaction(doc, "update sheet parameters")
    t.Start()
    for i, j in zip(sheetviews, excel_data):
        try:
            date = getnsetBIP(i, sheet_issuedate, j[5])
            drawnby = getnsetBIP(i, sheet_drawnby, j[6])
            man_massstab = getnsetSharedPara(i, "man_Massstab", j[7])
            pbrowser = getnsetSharedPara(i, "PBrowser", j[4])
            mess2 = ' {}-{} --> PBrowser: {}, issue_date: {}, drawnby: {}, M: {}'.format(
                i.SheetNumber, i.Name, pbrowser, date, drawnby, man_massstab)
            mess.append(mess2)
        except:
            error = 'Error '
            mess.append(error)
            import traceback
            print("\n", traceback.format_exc())
            continue
    t.Commit()
    return mess
Exemple #21
0
def printview(singlesheet,
              filepathname,
              papersizeobj,
              pdfprinterName,
              tmp_printsetupobj=createTmpPrintSetting()):
    # instantiate new_viewset Instance of ViewSetclass and insert single sheet
    new_viewset = ViewSet()  #ViewSet Class
    new_viewset.Insert(singlesheet)
    printmanager = doc.PrintManager
    # set pdfprinterName = PDFCreator, Adobe PDF ..
    printmanager.SelectNewPrintDriver(pdfprinterName)
    # determine print range to Select option
    printmanager.PrintRange = PrintRange.Select  # PrintRange is a own subclass
    # make the new_viewset current
    viewSheetSetting = printmanager.ViewSheetSetting
    viewSheetSetting.CurrentViewSheetSet.Views = new_viewset
    # set file path ---------------, add filend "_.pdf", "__.pdf" to fileend
    while os.path.exists(filepathname):
        filepathname = filepathname.replace(".pdf", "_.pdf")
        # filepathname must be different, everytime SubmitPrint() is called,
        # else Exception: file exists is raised
    printmanager.PrintToFileName = filepathname  #as string,
    printmanager.Apply()

    printmanager.CombinedFile = True

    _printsetup = printmanager.PrintSetup
    page_orient = DB.PageOrientationType.Portrait
    t = Transaction(
        doc, "Testprint")  #each Transaction must have a name. else: Error
    t.Start()
    _printsetup.CurrentPrintSetting = tmp_printsetupobj  #needs a TransactionProcess, when changed
    _printsetup.CurrentPrintSetting.PrintParameters.PageOrientation = page_orient
    _printsetup.CurrentPrintSetting.PrintParameters.PaperSize = papersizeobj
    try:  #if there are no changes to the PrintSetup obj (ie change to PrintParameters)
        # .Save() method throws an exception, catch Exc. needed.
        _printsetup.Save(
        )  #returns True or throws Exception: Save of print was unsuccessful
    except:
        pass
    try:
        #FECviewSets=FilteredElementCollector(doc).OfClass(ViewSheetSet).ToElements()
        #(doc.Delete(i.Id) for i in FECviewSets if i.Name =="!tmpViewSheetSet")
        viewSheetSetting.SaveAs("!tmpViewSheetSet")
        printmanager.SubmitPrint()
        t.RollBack()  # chose to use RollBack()-Way, see ForumEntry
        import time  # ??? Error, needed!!.
        time.sleep(1)  # 3 sec, necessary, because PDF Printer will cause error
        #if too many docs submitted too fast. see ForumEntry
        #viewSheetSetting.Delete() # replaced with t.RollBack()
        errorReport = "Sucess"
    except:
        import traceback
        errorReport = traceback.format_exc()
        print(errorReport)
        try:
            t.RollBack()
        except:
            pass
    return errorReport
Exemple #22
0
    def run(self, sender, args):
        # print(dir(self))
        if not(self.parameter_to_sort and  self.parameter_to_sort != "" and self.parameter_to_set and  self.parameter_to_set != ""):
            forms.alert("Error! All the parameters should be set")
            return

        result = self.sort(self.selection, self.parameter_to_sort, self.is_reversed)
        i = self.start_from
        text_format = self.text_format
        zeros = self.leading_zeros

        t = Transaction(doc, __title__)
        t.Start()
        for r in result:
            e = r[0]
            definition = self.parameter_to_set.Definition
            param = e.get_Parameter(definition)
            if zeros:
                _i = str(i).zfill(zeros)
            else:
                _i = str(i)
            self.parameter_value_set(param, _i, text_format)
            i += 1
        t.Commit()

        my_config.start_from = i

        # selection_doc.set self.selection
        try:
            self.write_config()
        except:
            pass
        logger.debug("run - set_to", map(lambda e: e[0].Id.IntegerValue, result))
        selection_pyr.set_to(map(lambda e: e[0].Id, result))
        self.Close()
def createSharedPara(_paramName_string,_groupNameinSPfile_string, \
                    _paramtype_enum, _builtInCat_enum,_paramGroupinProperty_enum):	
    # open SharedParameterFile 
    file = uiapp.Application.OpenSharedParameterFile()
    # get GroupName in SharedParameter file, if not exist create new Group  
    group = file.Groups.get_Item(_groupNameinSPfile_string)
    if group == None: 
        group = file.Groups.Create(_groupNameinSPfile_string)
    # Create NewCategorySet()              
    catset = app.Create.NewCategorySet()   
    # Insert Category Objects in CatSet  <Autodesk.Revit.DB.Category object 
    catset.Insert(doc.Settings.Categories.get_Item(_builtInCat_enum)) # returns True 
    # create an instance binding object with categoryset  
    inst_bind = app.Create.NewInstanceBinding(catset)     
    #ExternalDefinitionCreationOptions Class  excpects ( paraname as string, paratype object)
    # An option class used for creating a new shared parameter definition,        
    ED_opt1 = ExternalDefinitionCreationOptions(_paramName_string, _paramtype_enum)
    ED_opt1.Visible = True # True is the default value
    #Create Parameter Definition Object               
    #Test if paraName is in SharedParam file , get Para Name Definition from file, else Create new Name 
    if group.Definitions.Contains(group.Definitions.Item[_paramName_string]):
        _exdef1 = group.Definitions.Item[_paramName_string] # create parameter definition object from Para in file
    else:  
    # _def = group.Definitions.Create(_paramName, _paramtype_enum, _visible) 
        _exdef1 = group.Definitions.Create(ED_opt1) #Create para Definition object wit Ext
    #Create Parameter by inserting the Para Definition in the ParameterBindigs_Map
    try:
        t = Transaction(doc, "Parameter Creation")
        t.Start() 
        bind_Map = doc.ParameterBindings.Insert(_exdef1, inst_bind, _paramGroupinProperty_enum) 
        t.Commit()
    except:
        import traceback
        print(traceback.format_exc())
def createsheets(sheetlist):
    message = []
    dic_sheetGuid = {}
    t = Transaction(doc, "Create SheetViews from EXCEL")
    try:
        t.Start()
        for j in sheetlist:
            try:
                tibl = dic_tibl[j[2]]
            except:
                mess1 = 'Error: TitleBlock1 "{}" not found'.format(j[2])
                message.append(mess1)
                continue
            a = DB.ViewSheet.Create(doc,
                                    tibl.Id)  # ViewSheet Class, Create Method
            a.SheetNumber = j[0]
            a.ViewName = j[1]
            dic_sheetGuid[a.SheetNumber] = str(a.UniqueId)
            #create TitleBlock2 instance
            try:
                tibl_2 = dic_tibl[j[3]]
                newtitleblock = doc.Create.NewFamilyInstance(
                    XYZ(0, 0, 0), tibl_2, a)
                mess2 = '; TitleBlock2: {}'.format(str(j[3]))
            except:
                mess2 = '; TitleBlock2: not found'
                pass
            message.append('--> {}-{}, TiBl1: {}'.format(
                a.SheetNumber, a.ViewName, j[2]) + mess2)
        t.Commit()
    except:
        t.RollBack()
        import traceback
        print(traceback.format_exc())
    return (message, dic_sheetGuid)
Exemple #25
0
def link_method_ifc():
    files_filter = "IFC files (*.ifc)|*.ifc"
    files = pick_files(files_filter)
    for f in files:
        t = Transaction(doc)
        t.Start(__title__)
        f_cache = f + ".rvt"
        recreate = not os.path.exists(f_cache)
        logger.debug("Recreate ifc %s = %s" % (f, recreate))
        # try:
        o = RevitLinkOptions(False)
        # create empty doc
        if recreate:
            new_doc = doc.Application.NewProjectDocument(UnitSystem.Metric)
            new_doc.SaveAs(f_cache)
            new_doc.Close(False)
        link_load_results = RevitLinkType.CreateFromIFC(
            doc, f, f_cache, recreate, o)
        # TODO log results http://www.revitapidocs.com/2019/11b095e1-24d9-91b9-ae2e-004f67c94d6e.htm
        logger.debug(link_load_results.LoadResult)
        instance = RevitLinkInstance.Create(doc, link_load_results.ElementId)
        status = True
        # except Exception as e:
        #     logger.error("Unable to import IFC")
        #     logger.error(e)
        #     status = False
        #     instance = None

        if status:
            instance.Pinned = True
            t.Commit()
        else:
            t.RollBack()
Exemple #26
0
def link_method_rvt():
    files_filter = "RVT files (*.rvt)|*.rvt"
    files = pick_files(files_filter)

    for f in files:
        t = Transaction(doc)
        t.Start(__title__)

        try:
            mp = ModelPathUtils.ConvertUserVisiblePathToModelPath(f)
            o = RevitLinkOptions(False)
            linkType = RevitLinkType.Create(doc, mp, o)
            instance = RevitLinkInstance.Create(doc, linkType.ElementId)
            status = True
        except Exception as e:
            logger.error("Unable to import RVT")
            logger.error(e)
            status = False
            instance = None

        if status:
            instance.Pinned = True
            t.Commit()
        else:
            t.RollBack()
def addFilter():
    try:
        t = Transaction(doc, "AddFilterToView")
        t.Start()
        [doc.ActiveView.AddFilter(i.Id) for i in response3]
        t.Commit()
    except Exceptions.OperationCanceledException:
        pass
def removeFilter():
    try:
        t = Transaction(doc, "RemoveFilterFromView")
        t.Start()
        [doc.ActiveView.RemoveFilter(i.Id) for i in response3]
        t.Commit()
    except Exceptions.OperationCanceledException:
        pass    
Exemple #29
0
def set_param_from_symbol(FamilySymbol, ParameterName, ParameterValue):
    """ set param from symbol """

    Parameter = FamilySymbol.LookupParameter(ParameterName)
    t = Transaction(doc, "Set parameter")
    t.Start()
    Parameter.Set(ParameterValue)
    t.Commit()
Exemple #30
0
def main(ALIGN):
    """ ADD DOCS
    """
    align_axis = Align.axis[ALIGN]
    align_method = Align.method[ALIGN]

    logger.info('Align Class: {}'.format(ALIGN))
    logger.debug('Align Axis: {}'.format(align_axis))
    logger.debug('Align Methid: {}'.format(align_method))

    elements = get_selected_elements()
    point_collection = PointCollection()

    for element in elements:
        point_element = get_location(element, align_method)
        if point_element:
            point_element.element = element
            point_collection.points.append(point_element)

    point_collection.sort_points(align_axis)
    qty_items = len(point_collection)

    min_target = getattr(point_collection, 'min')
    max_target = getattr(point_collection, 'max')
    delta = getattr(max_target, align_axis) - getattr(min_target, align_axis)

    steps = get_division_steps(delta, qty_items)
    target_locations = [
        getattr(min_target, align_axis) + step for step in steps
    ]

    logger.debug('Min Location Target is: {}'.format(min_target))
    logger.debug('Max Location Target is: {}'.format(max_target))
    logger.debug('delta is: {}'.format(str(delta)))
    logger.debug('steps: {}'.format(steps))
    logger.debug('targer_locations: {}'.format(target_locations))

    t = Transaction(doc, 'Smart Align - Distribute')
    t.Start()

    for point_element, target_location in zip(point_collection,
                                              target_locations):
        current_location = getattr(point_element, align_axis)
        delta = current_location - target_location
        delta_vector = PointElement(0, 0, 0)
        setattr(delta_vector, align_axis, -delta)
        translation = XYZ(*delta_vector.as_tuple)

        move_element(point_element.element, translation)

        logger.debug('current: {}'.format(current_location))
        logger.debug('target: {}'.format(target_location))
        logger.debug('delta: {}'.format(delta))
        logger.debug('delta_vector: {}'.format(delta_vector))
        logger.debug('Translation: {}'.format(str(translation)))

    logger.info('Done.')
    t.Commit()