Attach File to an Item

By Barbara Han

Using Vault API, you can attach one or more files to an item. The basic work flow is:
1. Obtain an editable item using ItemService.EditItem or ItemService.AddItemRevision.
2. Obtain each DocumentService.File that you would like to add as attachment of the editable item.
3. Create an array of ItemService.Attmt. ItemService.Attmt is a simple structure that contains ID of File and pin flag which controls if the attachment is pinned to a specific version of a File.
4. Finally call ItemService.UpdateAndCommitItem. If it fails then you should call ItemService.UndoEditItems to undo any changes to the item.

 

Here is a small console application (both C# and VB.NET version) demonstrates above work flow. It does the following:
1. Prompts for vault credentials (login, password, server, vault)
2. Prompts for item choice. You can create a new item, or use an existing item – you will be prompted for item number.
3. Prompts for one or more files to attach. It’’s designed to use full path (i.e. $/My Folder/My File.ipt). To stop adding entry, press enter.
4. It adds given files to the item and report status of item update.

C#:

using System;

using System.Collections;

using Autodesk.Connectivity.WebServices;

using Autodesk.Connectivity.WebServicesTools;

 

namespace ItemAttachment

{

  class App

  {

    private WebServiceManager ServiceManager;

    /// <summary>

    /// The main entry point for the application.

    /// </summary>

    [STAThread]

    static void Main(string[] args)

    {

      try

      {

        App app = new App();

        app.Run();

      }

      catch(System.Exception ex)

      {

        Console.WriteLine("ERROR: {0}", ex.Message);

      }

    }

 

    private void Run()

    {

      Login();

      Item item = GetItem();

 

      try

      {

        ArrayList files = GetFiles();

        ArrayList attachments = new ArrayList();

 

        foreach(File file in files)

        {

          Attmt attmt = new Attmt();

 

          attmt.FileId = file.Id;

          attmt.Pin = false;

          attachments.Add(attmt);

        }

        ServiceManager.ItemService.UpdateAndCommitItem(item,

          0,false, null, null,null,

          (Attmt[])attachments.ToArray(typeof(Attmt)),

          null, 2);

        Console.WriteLine("Item {0} was succesfully updated.",

          item.ItemNum);

        Console.ReadLine();

      }

      catch

      {

        ServiceManager.ItemService.UndoEditItems(new long[] { item.Id });

        Console.WriteLine("Error while editing item.");

      }

      Logout();

    }

 

    private void Login()

    {

      Console.Write("User Name: ");

      string userName = Console.ReadLine();

 

      Console.Write("Password: ");

      string password = Console.ReadLine();

 

      Console.Write("Server: ");

      string server = Console.ReadLine();

 

      Console.Write("Vault: ");

      string vault = Console.ReadLine();

 

      UserPasswordCredentials userpasswordCred = new UserPasswordCredentials(

        server, vault, userName, password);

      ServiceManager = new WebServiceManager(userpasswordCred);

    }

 

    private void Logout()

    {

      ServiceManager.SecurityService.SignOut();

    }

 

    private Item GetItem()

    {

      Console.Write("Create new item [Y/N] <Yes>: ");

      string answer = Console.ReadLine();

 

      if (0 == answer.Length)

      {

        answer = "Y";

      }

      Item item = null;

 

      if (0 == string.Compare(answer, "Y", true))

      {

        Cat[] categories = ServiceManager.CategoryService.

          GetCategoriesByEntityClassId("ITEM", true);

        long catId = -1;

        foreach (Cat category in categories)

        {

          if ((category.SysName == "Part"))

          {

            catId = category.Id;

          }

        }

        item = ServiceManager.ItemService.AddItemRevision(catId);

      }

      else

      {

        Console.Write("Enter item number: ");

 

        string itemNo = Console.ReadLine();

        Item itemRev = ServiceManager.ItemService.GetLatestItemByItemNumber(itemNo);

 

        item = ServiceManager.ItemService.EditItem(itemRev.RevId);

      }

      return item;

    }

 

    private ArrayList GetFiles()

    {

      ArrayList results = new ArrayList();

 

      do

      {

        Console.Write("Enter full document name (incl. path): ");

        string filePath = Console.ReadLine();

 

        if (0 == filePath.Length)

        {

          break;

        }

        File[] files = ServiceManager.DocumentService.FindLatestFilesByPaths(new string[] { filePath } );

 

        foreach(File file in files)

        {

          if (-1 == file.Id)

          {

            continue;

          }

          results.Add(file);

        }

      } while(true);

      return results;

    }

  }

}

 

VB.NET:

Imports System

Imports System.Collections

Imports Autodesk.Connectivity.WebServices

Imports Autodesk.Connectivity.WebServicesTools

 

Class App

  Private ServiceManager As WebServiceManager

  Shared Sub Main()

    Try

      Dim app As App = New App

      app.Run()

    Catch ex As System.Exception

      Console.WriteLine("ERROR: {0}", ex.Message)

    End Try

  End Sub

 

  Private Sub Run()

    Login()

    Dim item As Item = GetItem()

 

    Try

      Dim files As ArrayList = GetFiles()

      Dim attachments As ArrayList = New ArrayList

 

      For Each file As File In files

        Dim attmt As Attmt = New Attmt

 

        attmt.FileId = file.Id

        attmt.Pin = False

        attachments.Add(attmt)

      Next

      ServiceManager.ItemService.UpdateAndCommitItem(item, _

        0, False, Nothing, Nothing, _

        Nothing, attachments.ToArray(GetType(Attmt)), _

        Nothing, 2)

      Console.WriteLine("Item {0} was succesfully updated.", _

        item.ItemNum)

      Console.ReadLine()

    Catch

 

      ServiceManager.ItemService.UndoEditItems(New Long() {item.Id})

      Console.WriteLine("Error while editing item.")

    End Try

    Logout()

  End Sub

 

  Private Sub Login()

    Console.Write("User Name: ")

    Dim userName As String = Console.ReadLine()

 

    Console.Write("Password: ")

    Dim password As String = Console.ReadLine()

 

    Console.Write("Server: ")

    Dim server As String = Console.ReadLine()

 

    Console.Write("Vault: ")

    Dim vault As String = Console.ReadLine()

 

    Dim userPasswordCred As UserPasswordCredentials = New UserPasswordCredentials(server, vault, userName, password)

    ServiceManager = New WebServiceManager(userPasswordCred)

  End Sub

 

  Private Sub Logout()

    ServiceManager.Dispose()

  End Sub

 

  Private Function GetItem() As Item

    Console.Write("Create new item [Y/N] <Yes>: ")

    Dim answer As String = Console.ReadLine()

 

    If 0 = answer.Length Then

      answer = "Y"

    End If

    Dim item As Item = Nothing

 

    If 0 = String.Compare(answer, "Y", True) Then

      Dim categories As Cat() = ServiceManager.CategoryService.GetCategoriesByEntityClassId("ITEM", True)

      Dim catId As Long = -1

      For Each category As Cat In categories

        If category.SysName = "Part" Then

          catId = category.Id

        End If

      Next

 

      item = ServiceManager.ItemService.AddItemRevision(catId)

    Else

      Console.Write("Enter item number: ")

 

      Dim itemNo As String = Console.ReadLine()

      Dim itemRev As Item = ServiceManager.ItemService.GetLatestItemByItemNumber(itemNo)

 

      item = ServiceManager.ItemService.EditItem(itemRev.RevId)

    End If

    Return item

  End Function

 

  Private Function GetFiles() As ArrayList

    Dim results As ArrayList = New ArrayList

 

    Do

      Console.Write("Press ENTER to stop, or enter full document name (incl. path): ")

      Dim filePath As String = Console.ReadLine()

 

   &#1
60; 
If 0 = filePath.Length Then

        Exit Do

      End If

 

      Dim files() As File = _

        ServiceManager.DocumentService.FindLatestFilesByPaths(New String() {filePath})

 

      For Each file As File In files

        If -1 <> file.Id Then

          results.Add(file)

        End If

      Next

    Loop While True

    Return results

  End Function

 

End Class

Note: The sample uses 2 as activeInputs value for UpdateAndCommitItem. It means that only attachments are set (all other values are ignored). In real case, you may need to pass the old item’s file associations (i.e. Primary link) available by ItemService.GetItemFileAssociationsByItemIds to the item.

This picture shows the running result:

image


Comments

One response to “Attach File to an Item”

  1. How would you modify the VB code to maintain existing attachents already in a existing item?

Leave a Reply

Discover more from Autodesk Developer Blog

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

Continue reading