Macro - open document as detach from central and save the document.

Macro - open document as detach from central and save the document.

Anonymous
Not applicable
8,921 Views
28 Replies
Message 1 of 29

Macro - open document as detach from central and save the document.

Anonymous
Not applicable

Hello there,

 

I have come up with an idea of a Macro and would like to know whether it could be done and how could it be done. I have been working in a project and need to detach it from central for all the partners involved in the project, it is kind of an arduous task.

 

Therefore, I have thought on developing a macro with macro manager where i could open the active document as detach from central and they save it into a file.

 

Is this possible?

 

Many thanks!

0 Likes
8,922 Views
28 Replies
Replies (28)
Message 21 of 29

Anonymous
Not applicable

Hi all,

I would love to listen to somebody who could explain how to get it up and running.

I tried to build the attached solution on my PC, but SharpDeveloper is throwing at me errors - see printscreen.

Any ideas what went wrong? - sorry I'm not a C# guru...

0 Likes
Message 22 of 29

dnenov
Contributor
Contributor

Hey Plamen,

 

I know it was confusing for me when I started. I hope I can address your problem with the image below. Right-click on the References and then try to find the missing library reference. 

 

add reference.png

Message 23 of 29

Anonymous
Not applicable

Dnenov,

 

It worked the treat! - Thank you mate!

Maciej

Message 24 of 29

hamdibr
Participant
Participant

First Thanks Helen.

When i buikd the solution after adding references. I always have error for InternalStartup void. The Startup and the Suhtdown are not accepted.

I also get error on  Application.OpenDocumentFile(mp, opt)

Could you help me please.

Sorry the error message are in french. and sorry for my english)

 

'batch.ThisApplication' ne contient pas une définition pour 'Startup' et aucune méthode d'extension 'Startup' acceptant un premier argument de type 'batch.ThisApplication' n'a été trouvée (une directive using ou une référence d'assembly est-elle manquante ?) (CS1061) - C:\ProgramData\Autodesk\Revit\Macros\2019\Revit\AppHookup\opencentraleeeee\Source\opencentraleeeee\ThisApplication.cs:45,9
'batch.ThisApplication' ne contient pas une définition pour 'Shutdown' et aucune méthode d'extension 'Shutdown' acceptant un premier argument de type 'batch.ThisApplication' n'a été trouvée (une directive using ou une référence d'assembly est-elle manquante ?) (CS1061) - C:\ProgramData\Autodesk\Revit\Macros\2019\Revit\AppHookup\opencentraleeeee\Source\opencentraleeeee\ThisApplication.cs:46,9
Une référence d'objet est requise pour la propriété, la méthode ou le champ non statique 'Autodesk.Revit.ApplicationServices.Application.OpenDocumentFile(Autodesk.Revit.DB.ModelPath, Autodesk.Revit.DB.OpenOptions)' (CS0120) - C:\ProgramData\Autodesk\Revit\Macros\2019\Revit\AppHookup\opencentraleeeee\Source\opencentraleeeee\ThisApplication.cs:77,28
'Application' est une référence ambiguë entre 'Autodesk.Revit.ApplicationServices.Application' et 'System.Windows.Forms.Application' (CS0104) - C:\ProgramData\Autodesk\Revit\Macros\2019\Revit\AppHookup\opencentraleeeee\Source\opencentraleeeee\ThisApplication.cs:77,28

 

#region Revit Macros generated code
		private void InternalStartup()
		{
			this.Startup += new System.EventHandler(Module_Startup);
			this.Shutdown += new System.EventHandler(Module_Shutdown);
		}
		#endregion

 

0 Likes
Message 25 of 29

stever66
Advisor
Advisor

When you crete a new module, make sure you are creating  application level macro, not a document macro.  (They are different tabs on the create module window.)

 

Also make sure you select C#.

 

After you create a new module, create a new macro in that module.   Now the startup and shutdown methods re automatically created - don’t change those.  ( you should be able to build and run the empty macro without any errors, although it won’t do anything yet.)

 

In-between the braces after your macro name, try adding :

 

TaskDialog.Show(“Revit”, “Sucess”);

 

You should be able to get that to run and show the task dialog box.   If that works you can delete that line and copy in the code.  Start by copying everything from the OpenFileDialog line down and paste it into the same place where you put the TaskDialog line earlier.   You will probably have to delete 3 of the } closed braces  at the end,  and you will have to make sure you have the right number of braces everywhere.

 

after that go back to the top and add any using statements that are missing.

 

then add any missing references s shown in the earlier post.

 

with some care, that should work.

Message 26 of 29

hamdibr
Participant
Participant

Thank you very much stever,

It was so helpful.

I am sure i will need your help again soon 🙂

In fact, i try to create a macro to open central file, detached and preserve worksharing, and save them in backup folder.

I work on projet with almost 100 small buildings, so for each building we 4 centrale file (architeure, Structural, Mech, and electrical) so we have about 400 central file to handle to upgrate from prelimary design to final design stage.

The Idea is to create, a backup files for each central for actual stage. and continu working in the same cental filesfor the detailed design phase.

I usually use dynamo, with few python code. but i think Dynamo cannot be helpful in this.

0 Likes
Message 27 of 29

hamdibr
Participant
Participant

I finally did it. The macro open a list of file from giving directory, detached them from the central file, and save them as new central file.

What i want to do next is the resume error if one of centrale file is corrupted.

if there is any idea please advise.

thx

 

'
' Created by SharpDevelop.
' User: Hamdi.benromdhane
' Date: 01/12/2020
' Time: 17:54

' To change this template use Tools | Options | Coding | Edit Standard Headers.
'
Imports System
Imports Autodesk.Revit.UI
Imports Autodesk.Revit.DB
Imports Autodesk.Revit.UI.Selection
Imports System.Collections.Generic
Imports System.Linq
Imports Autodesk.Revit.ApplicationServices
Imports System.IO
Imports System.Windows.Forms
Imports Autodesk.Revit.Exceptions


<Autodesk.Revit.Attributes.Transaction(Autodesk.Revit.Attributes.TransactionMode.Manual)> _
<Autodesk.Revit.DB.Macros.AddInId("1123BFB6-C2C5-4C0E-B353-2F920D29EABA")> _
Partial Public Class ThisApplication

    Private Sub Module_Startup(ByVal sender As ObjectByVal e As System.EventArgs) Handles Me.Startup
    
    End Sub
    
    Private Sub Module_Shutdown(ByVal sender As ObjectByVal e As System.EventArgs) Handles Me.Shutdown
    
    End Sub
    
        Public  Sub OpenCentral_0_1()
'            Dim theDialogRevit As OpenFileDialog = New OpenFileDialog()
'            theDialogRevit.Title = "Select Revit Project Files"
'            theDialogRevit.Filter = "RVT files|*.rvt"
'            theDialogRevit.FilterIndex = 1
'            theDialogRevit.InitialDirectory = "C:\"
'            theDialogRevit.Multiselect = True

            
                Dim mpath As String = "" 'Chemin du projet
                Dim mpathOnlyFilename As String = ""
                Dim bpath As String ="" 'Chemin de backup
                Dim bFilePath As String ="" 'chemin de fichier de sauvegarde
                Dim folderBrowserDialog1 As FolderBrowserDialog = New FolderBrowserDialog()
                folderBrowserDialog1.Description = "Select Folder Where Revit Projects"
                folderBrowserDialog1.RootFolder = Environment.SpecialFolder.MyComputer
                

                If folderBrowserDialog1.ShowDialog() = DialogResult.OK Then
                    mpath = folderBrowserDialog1.SelectedPath
                    
                folderBrowserDialog1.Description = "Select Folder Where To backup Revit Projects"
                folderBrowserDialog1.RootFolder = Environment.SpecialFolder.MyComputer
                If folderBrowserDialog1.ShowDialog() = DialogResult.OK Then
                    bpath = folderBrowserDialog1.SelectedPath
                    
                    
                    Dim CentralFile As String() = Directory.GetFiles(mpath,"*.rvt",SearchOption.AllDirectories)
                    Dim BackupFile As List(Of String)= New List (Of String)
                    Dim BackupStatut As List(Of String) = New List (Of String)

                    For Each  projectPath As String In CentralFile
                        Dim filePath As FileInfo = New FileInfo(projectPath)
                        Dim mp As ModelPath = ModelPathUtils.ConvertUserVisiblePathToModelPath(filePath.FullName)
                        Dim opt As OpenOptions = New OpenOptions()
                        opt.DetachFromCentralOption = DetachFromCentralOption.DetachAndPreserveWorksets
                        mpathOnlyFilename = filePath.Name
                        bFilePath =   bpath & projectPath.Remove(0,mpath.Length) '& "\" & mpathOnlyFilename 'filePath.Directory.FullName & "\new\"
                        BackupFile.Add(bFilePath)
                        
                        If File.Exists(bFilePath) =False Then 
                            Dim openedDoc As Document = Application.OpenDocumentFile(mp, opt)    
                            Dim optionlocal As SaveAsOptions = New SaveAsOptions()
                            Dim options As WorksharingSaveAsOptions = New WorksharingSaveAsOptions()
                            options.SaveAsCentral = True
                            optionlocal.SetWorksharingOptions(options)
                            optionlocal.OverwriteExistingFile = False
                            Directory.CreateDirectory(Path.GetDirectoryName(bFilePath))
                            Dim modelPathout As ModelPath = ModelPathUtils.ConvertUserVisiblePathToModelPath(bFilePath)
                            openedDoc.SaveAs(modelPathout, optionlocal)
                            openedDoc.Close(True)
                            BackupStatut.Add("New File Created")
                        End If
                        BackupStatut.Add("File Already Exist")
                    Next
                    'Création de fichier csv
                    Dim pathcsv As String = bpath + "\resulat.csv"
                    Using csv As StreamWriter = File.CreateText(pathcsv)
                        Dim linecsv As String =""
                    
                    For i As Integer = 0 To CentralFile.Length
                        linecsv = CentralFile(i) + ","+BackupFile(i)+","+BackupStatut(i)
                        csv.WriteLine(linecsv)
                    Next
                    End Using
                    
'Dim ListCentralFile As String = String.Join(",", CentralFileList)
'For Each filepath As String In CentralFile
'        
'Next
'Dim FullPath As String = Path.GetFullPath(mpath)
'Dim RelativePath As String = FullPath.Substring(mpath.Length)


                End If
            End If
        End Sub
    End Class

  

0 Likes
Message 28 of 29

sragan
Collaborator
Collaborator

In general in C#, if you think your code might run into a problem and generate an error, you put that code inside a try-catch-finally block:

 

try{

your code

}

catch

{

code for what to do when an error is encountered

}

finally

{

any cleanup code that has to run in either case

}

 

Try searching online for C# try catch for more info.  You can choose to catch all errors or only specific errors, or do different things for different errors.

 

 

 

 

Message 29 of 29

hamdibr
Participant
Participant

thank yo @sragan .

it was useful 

0 Likes