Using Vault APIs to Check in/out Files from an Inventor Addin

By Barbara Han

Issue

From an Inventor Add-In how do I check out a file from the Vault and generate the corresponding DWF file for that file? Also how do I check the file and DWF file back into the Vault after making some changes?

Solution

Please find attached sample that demonstrates how to do what you are looking for. However, this sample can only be used with "leaf" file (e.g. part file). In case of assembly file, you may get into trouble if the assembly file is edited and references are modified. For example, some parts are added to the assembly, the new file dependencies would not show up if the sample code is used.

The attached C# Inventor Add-In sample application does the following:
– finds the part file in the Vault
– finds its DWF attachment
– checks-out the part file
– checks-out the DWF file
– change a user defined property in part file and save file
– checks-in DWF file
– updates the attachment info to be saved in Vault part file
– checks-in the part file

First of all, DocumentService.GetFileAssociationsByIds gets a list of associated attachments for a file (currently Attachment and Dependency are all supported). The GetFileAssociationsByIds() method can be used to find the information for constructing FileAssocParam that is to be used when checking in file later. GetFileAssociationsByIds() may return multiple attachments, so the results have to be scanned to see which file is DWF file. Because the DWF file's file name is the main file's file name appended with .dwf extension, so call GetLatestAssociatedFilePathsByMasterIds to get all file paths of attachments for a file, if file path matches with expected DWF file path, that file represents the DWF file.

When checking out file from the Vault Server, you can download the file to a local folder and open the local file in the Inventor.

After the file is checked out from the Vault server and is modified by the user in Inventor, you can use Inventor API SaveAs() method in the Document object to create a new DWF file for the document.

In the attached samples, the user name, Vault database and the file named are hard coded, please change them according to your environment settings.

Download Vault_checkout_in_2012

The below is the key code for Vault 2012 version. The code may change across different versions of Vault.

public class Vault
{
  /// 
  /// Check out Inventor file from Vault to locak disk  
  /// open file from Inventor and then modify and save it, 
  /// finally check Inventor file along with its DWF file in Vault
  /// 
  ///
  public bool CheckOutInTest()
  {
    try
    {
      // Login Vault server
 
      VaultHelper helper = new VaultHelper("Administrator", "", "Vault");
 
      // Find part file and corresponding dwf file in Vault
 
      ArrayList fileAssocParamList = new ArrayList();
 
      String sPartinVault = "$/SampleProject/Part3.ipt";
      String sDWFinVault = "$/SampleProject/Part3.ipt.dwf";
 
      // Get our part file
 
      Autodesk.Connectivity.WebServices.File iFile = 
        helper.GetFileAndAssociations(sPartinVault, ref fileAssocParamList);
 
 
 
      // Find DWF attachment
 
      FilePathArray[] filePaths = 
        helper.DocumentService.GetLatestAssociatedFilePathsByMasterIds(
        new long[] { iFile.MasterId }, FileAssociationTypeEnum.None, false, 
        FileAssociationTypeEnum.Attachment, true, true, true, false);
 
      Autodesk.Connectivity.WebServices.File dwfFile = null;
 
      Boolean bFound = false;
      foreach (FilePath filePath in filePaths[0].FilePaths)
      {
        if (filePath.Path == sDWFinVault)
        {
          dwfFile = filePath.File;
 
          bFound = true;
          break;
        }
        if (bFound == true) break;
      }
      // Check out two files  
 
      if (dwfFile != null) helper.Checkout(dwfFile);
      helper.Checkout(iFile);
 
      // Open part file in Inventor
 
      Inventor.Application iApp = AddInServer.Instance.Application;
      Document pMainDoc = iApp.Documents.Open(helper.checkOutPath + iFile.Name, true);
 
      // Do something here in Inventor environment...
      //...
 
      // Edit a custom property of the file, then Save 
      // the file and its .dwf file to the disk
      PropertySet iPropSet = pMainDoc.PropertySets
        ["{D5CDD505-2E9C-101B-9397-08002B2CF9AE}"];
 
      try
      {
        Property iProp = iPropSet["mydata1"];
        iProp.Value = DateTime.Now.ToString();
      }
      catch 
      {
        iPropSet.Add(DateTime.Now.ToString(), "mydata1", null);
      }
      iApp.SilentOperation = true;
      pMainDoc.Save();
 
      iApp.SilentOperation = false;
      string sDWFFullName = pMainDoc.FullFileName + ".dwf";
      pMainDoc.SaveAs(sDWFFullName, true);
 
 
      pMainDoc.Close(true);
 
      Autodesk.Connectivity.WebServices.File dwfFileNewVer = null;
 
      // Check-in dwf attachment first
 
      if (dwfFile != null)
      {
        dwfFileNewVer = helper.Checkin(dwfFile, dwfFile.FileClass, true);
      }
      else
      {
        // ToDo: Add dwf File to Vault
      }
 
      // Check-in part file
 
      helper.Checkin(iFile, iFile.FileClass, iFile.Hidden);
 
      MessageBox.Show("You update the part file and DWF file successfully.");
      return true;
    }
    catch (Exception ex)
    {
      MessageBox.Show(ex.ToString(), "Vault_checkout_in Application", 
        MessageBoxButtons.OK, MessageBoxIcon.Information);
      return false;
    }
  }
}
 

/// 
/// Helper class
/// 
class VaultHelper
{
    private const int kBufferSize = 1024;
    private const string kCheckOutPath = "C:\Users\hanb\Documents\Vault\";
 
    private SecurityService _secSvc;
    private DocumentService _docSvc;
    private ArrayList fileAssocParamList;
 
    public DocumentService DocumentService
    {
        get
        {
            return _docSvc;
        }
    }
    public string checkOutPath
    {
        get
        {
            return kCheckOutPath;
        }
    }
    public VaultHelper(string login, string password,
      string knowledgeVault)
    {
        // Security Service
        _secSvc = new SecurityService();
        _secSvc.Url = "http://localhost/AutodeskDM/Services/SecurityService.asmx";
        _secSvc.SecurityHeaderValue = new Autodesk.Connectivity.WebServices.
          SecuritySvc.SecurityHeader();
        _secSvc.SignIn(login, password, knowledgeVault);
 
        // Document Service
        _docSvc = new DocumentService();
        _docSvc.SecurityHeaderValue = new Autodesk.Connectivity.WebServices.
          DocumentSvc.SecurityHeader();
        _docSvc.SecurityHeaderValue.Ticket = _secSvc.SecurityHeaderValue.Ticket;
        _docSvc.SecurityHeaderValue.UserId = _secSvc.SecurityHeaderValue.UserId;
        _docSvc.Url = "http://localhost/AutodeskDM/Services/DocumentService.asmx";
        fileAssocParamList = new ArrayList();
    }
 
    // Check in the file
    public Autodesk.Connectivity.WebServices.File Checkin(Autodesk.Connectivity.
      WebServices.File file, 
            FileClassification fileClassification, Boolean hidden)
    {
        Autodesk.Connectivity.WebServices.File retFile = null;
        string filePath = Path.Combine(kCheckOutPath, file.Name);
 
        using (FileStream stream = new FileStream(filePath, FileMode.Open, 
          FileAccess.Read))
        {
            byte[] fileData = new byte[stream.Length];
            stream.Read(fileData, 0, fileData.Length);
 
            // Perform the upload 
 
            if (fileClassification == FileClassification.DesignVisualization)
            {
                retFile = _docSvc.CheckinFile(file.MasterId, file.Comm,
                false, System.IO.File.GetLastWriteTime(filePath), null, null,false,
                file.Name, file.FileClass, hidden, fileData);
 
                for (int i = 0; i < fileAssocParamList.Count; i++)
                {
                    FileAssocParam param1 = (FileAssocParam)fileAssocParamList[i];
                    if (param1.CldFileId == file.Id)
                    {
                        param1.CldFileId = retFile.Id;
                    }
                }
                System.IO.FileAttributes attr = System.IO.File.GetAttributes(filePath);
                //the local file can't be read only.
                if ((attr & System.IO.FileAttributes.ReadOnly) == 0)
                {
                    System.IO.File.SetAttributes(filePath, FileAttributes.ReadOnly);
                }
            }
            else
            {
                // Get bom
                Autodesk.Connectivity.WebServices.BOM tbom = 
                  _docSvc.GetBOMByFileId(file.Id);
 
                FileAssocParam[] paramArray = (FileAssocParam[])
                  fileAssocParamList.ToArray(typeof(FileAssocParam));
 
                retFile = _docSvc.CheckinFile(file.MasterId, file.Comm,
                    false, System.IO.File.GetLastWriteTime(filePath), 
                    paramArray, tbom, true,
                    file.Name, file.FileClass, hidden, fileData);
                if (System.IO.File.Exists(filePath) == true)
                {
                    System.IO.FileAttributes attr = 
                      System.IO.File.GetAttributes(filePath);
 
                    //the local file can't be read only.
                    if ((attr & System.IO.FileAttributes.ReadOnly) == 0)
                    {
                        System.IO.File.SetAttributes(filePath, FileAttributes.ReadOnly);
                    }
                }
            }
        }
 
        return retFile;
    }
 
    public Autodesk.Connectivity.WebServices.File Checkout(
      Autodesk.Connectivity.WebServices.File file)
    {
        Folder[] folders = _docSvc.GetFoldersByFileMasterId(file.MasterId);
        string filePath = Path.Combine(kCheckOutPath, file.Name);
 
        if (System.IO.File.Exists(filePath) == true)
        {
            System.IO.FileAttributes attr = System.IO.File.GetAttributes(filePath);
            // The local file can't be read only.
 
            if ((attr & System.IO.FileAttributes.ReadOnly) != 0)
            {
                System.IO.File.SetAttributes(filePath, FileAttributes.Normal);
            }
        }
 
        // Check out the file
 
        byte[] bytes;
        Autodesk.Connectivity.WebServices.File fileOut = 
          _docSvc.CheckoutFile(folders[0].Id, file.Id, 
          CheckoutFileOptions.Master, Environment.MachineName,
          kCheckOutPath,file.Comm, true, true, out bytes);
 
        // Get the latest data of the file from Vault                   
        System.IO.File.WriteAllBytes(filePath, bytes);
 
        return fileOut;
    }
 
    public Autodesk.Connectivity.WebServices.File 
      GetFileAndAssociations(string path,ref ArrayList fileAssocParams)
    {
        string[] paths = new string[1];
 
        paths[0] = path;
        Autodesk.Connectivity.WebServices.File[] files = 
          _docSvc.FindLatestFilesByPaths(paths);
 
        FileAssocArray[] assocArray = _docSvc.GetFileAssociationsByIds(
          new long[] { files[0].Id }, FileAssociationTypeEnum.None, false,
        FileAssociationTypeEnum.All,false, false, true);
 
        FileAssocArray assemblyAssoc = assocArray[0];
 
        if (assemblyAssoc != null)
        {
            foreach (FileAssoc assoc in assemblyAssoc.FileAssocs)
            {
 
                FileAssocParam param1 = new FileAssocParam();
                param1.CldFileId = assoc.CldFile.Id;
                param1.RefId = assoc.RefId;
                param1.Source = assoc.Source;
                param1.Typ = assoc.Typ;
                param1.ExpectedVaultPath = assoc.ExpectedVaultPath;
                fileAssocParams.Add(param1);
 
            }
        }
        return files[0];
    }
}

Comments

6 responses to “Using Vault APIs to Check in/out Files from an Inventor Addin”

  1. Shane Avatar
    Shane

    I get the following error:
    System.Web.Services.Protocols.SoapException: Server did not recognize the value of HTTP Header SOAPAction: http://AutodeskDM/Services/Security/11/15/2011/SignIn.
    at System.Web.Services.Protocols.Soap11ServerProtocolHelper.RouteRequest()
    Any ideas?

  2. Balaji A Avatar
    Balaji A

    Any Solution for the above Issue!
    Thanks

  3. Just change http://AutodeskDM/Ser.. by http://localhost/..

  4. Hello, Barbara,
    how we can determine the RefId for new references? This is absolutely necessery, otherwise the data in Vault will not be reliable

  5. Nathalie Avatar
    Nathalie

    Hi Barbara,
    Would you happen to have the code in VBA or VBscript? Or any help resources?
    Thank you

  6. Hi,
    I am working on Vault 2016 VDF,
    Is there any latest post on checkin/checkout using Vault 2016 api?
    Moreover, i could not find Inventor assembly.
    Any help would be highly appreciated.
    Thanks
    Adil

Leave a Reply

Discover more from Autodesk Developer Blog

Subscribe now to keep reading and get access to the full archive.

Continue reading