Exemple #1
0
        private List <VDF.Vault.Currency.Entities.IEntity> DoItemSearch(SrchCond[] conditions)
        {
            string     bookmark = string.Empty;
            SrchStatus status   = null;

            //search for files
            List <VDF.Vault.Currency.Entities.IEntity> retVal = new List <VDF.Vault.Currency.Entities.IEntity>();

            while (status == null || retVal.Count < status.TotalHits)
            {
                Item[] items = m_conn.WebServiceManager.ItemService.FindItemRevisionsBySearchConditions(
                    conditions, null, true,
                    ref bookmark, out status);

                if (items != null)
                {
                    foreach (Item item in items)
                    {
                        VDF.Vault.Currency.Entities.ItemRevision vdfItem =
                            new VDF.Vault.Currency.Entities.ItemRevision(m_conn, item);
                        retVal.Add(vdfItem);
                    }
                }
            }

            return(retVal);
        }
Exemple #2
0
        private List <VDF.Vault.Currency.Entities.IEntity> DoCustEntSearch(SrchCond[] conditions)
        {
            string     bookmark = string.Empty;
            SrchStatus status   = null;

            //search for files
            List <VDF.Vault.Currency.Entities.IEntity> retVal = new List <VDF.Vault.Currency.Entities.IEntity>();

            while (status == null || retVal.Count < status.TotalHits)
            {
                CustEnt[] ents = m_conn.WebServiceManager.CustomEntityService.FindCustomEntitiesBySearchConditions(
                    conditions, null, ref bookmark, out status);

                if (ents != null)
                {
                    foreach (CustEnt ent in ents)
                    {
                        VDF.Vault.Currency.Entities.CustomObject vdfEnt = new VDF.Vault.Currency.Entities.CustomObject(m_conn, ent);
                        retVal.Add(vdfEnt);
                    }
                }
            }

            return(retVal);
        }
Exemple #3
0
        private List <VDF.Vault.Currency.Entities.IEntity> DoChangeOrderSearch(SrchCond[] conditions)
        {
            string     bookmark = string.Empty;
            SrchStatus status   = null;

            //search for files
            List <VDF.Vault.Currency.Entities.IEntity> retVal = new List <VDF.Vault.Currency.Entities.IEntity>();

            while (status == null || retVal.Count < status.TotalHits)
            {
                ChangeOrder[] changeOrders = m_conn.WebServiceManager.ChangeOrderService.FindChangeOrdersBySearchConditions(
                    conditions, null, ref bookmark, out status);

                if (changeOrders != null)
                {
                    foreach (ChangeOrder co in changeOrders)
                    {
                        VDF.Vault.Currency.Entities.ChangeOrder vdfCo = new VDF.Vault.Currency.Entities.ChangeOrder(m_conn, co);
                        retVal.Add(vdfCo);
                    }
                }
            }

            return(retVal);
        }
Exemple #4
0
        public List <Autodesk.Connectivity.WebServices.Item> InitVault()
        {
            List <Autodesk.Connectivity.WebServices.Item> parts = new List <Autodesk.Connectivity.WebServices.Item>();
            List <long> partIds  = new List <long>();
            string      bookmark = string.Empty;
            SrchStatus  status   = null;

            Vault.Results.LogInResult result = VaultLogin();
            v_Conn = result.Connection;

            while (status == null || parts.Count < status.TotalHits)
            {
                //Autodesk.Connectivity.WebServices.File[] results = result.Connection.WebServiceManager.DocumentService.FindFilesBySearchConditions(null, null, null, false, true, ref bookmark, out status);
                Autodesk.Connectivity.WebServices.Item[] results = result.Connection.WebServiceManager.ItemService.FindItemRevisionsBySearchConditions(null, null, false, ref bookmark, out status);

                if (results != null)
                {
                    parts.AddRange(results);
                }
                else
                {
                    break;
                }
                Console.WriteLine("Total Results: " + parts.Count.ToString() + " TotalHits: " + status.TotalHits.ToString());
            }

            ReadProperties(result.Connection);

            return(parts);
        }
Exemple #5
0
        public IEnumerable <CustEnt> GetAllCustomEntities(CustEntDef custEntDef)
        {
            var propDefs = _wsm.PropertyService.GetPropertyDefinitionsByEntityClassId("CUSTENT");
            var propDef  = propDefs.Single(p => p.SysName.Equals("CustomEntitySystemName"));

            var srcCond = new SrchCond
            {
                PropDefId = propDef.Id,
                PropTyp   = PropertySearchType.SingleProperty,
                SrchOper  = 3,
                SrchRule  = SearchRuleType.Must,
                SrchTxt   = custEntDef.Name
            };

            string     bookmark = null;
            SrchStatus status   = null;
            var        custEnts = new List <CustEnt>();

            while (status == null || custEnts.Count < status.TotalHits)
            {
                var results = _wsm.CustomEntityService.FindCustomEntitiesBySearchConditions(
                    new[] { srcCond }, null, ref bookmark, out status);

                if (results != null)
                {
                    custEnts.AddRange(results);
                }
                else
                {
                    break;
                }
            }

            return(custEnts);
        }
Exemple #6
0
        internal List <Autodesk.Connectivity.WebServices.File> GetVaultFilesByFileName(string fileName)
        {
            List <Autodesk.Connectivity.WebServices.File> foundFiles = new List <Autodesk.Connectivity.WebServices.File>();

            PropDef[] filePropDefs    = _webServiceManager.PropertyService.GetPropertyDefinitionsByEntityClassId("FILE");
            PropDef   fileNamePropDef = filePropDefs.Single(n => n.SysName == "FileName");
            SrchCond  fileNameCond    = new SrchCond()
            {
                PropDefId = fileNamePropDef.Id,
                PropTyp   = PropertySearchType.SingleProperty,
                SrchOper  = 3,
                SrchRule  = SearchRuleType.Must,
                SrchTxt   = fileName
            };
            string     bookmark = string.Empty;
            SrchStatus status   = null;

            while (status == null || foundFiles.Count < status.TotalHits)
            {
                Autodesk.Connectivity.WebServices.File[] results =
                    _webServiceManager.DocumentService.FindFilesBySearchConditions(
                        new SrchCond[] { fileNameCond }, null, null, false, true, ref bookmark, out status);
                if (results != null)
                {
                    foundFiles.AddRange(results);
                }
                else
                {
                    break;
                }
            }
            return(foundFiles);
        }
        public CustEnt[] getCustomentitiesbyPropName(VDF.Vault.Currency.Connections.Connection connection, string ObjType, string PropName, string srchop, string searchText)
        {
            try
            {
                //
                using (WebServiceManager serviceManager = connection.WebServiceManager) //using will log out after usage
                {
                    //get property details
                    var propDefs = getPropertyDefDetails(connection, ObjType, PropName);
                    result = connection.Vault.ToString();
                    DocumentService docServ = serviceManager.DocumentService;

                    SrchCond srchCond = new SrchCond()
                    {
                        PropDefId = propDefs.Id,
                        PropTyp   = PropertySearchType.AllProperties,
                        SrchOper  = SrchOperator(srchop), // is equal
                        SrchRule  = SearchRuleType.Must,
                        SrchTxt   = searchText.ToString()
                    };

                    //result = propDefs.Id.ToString();
                    string     bookmark = string.Empty;
                    SrchStatus status   = null;
                    custEntities = connection.WebServiceManager.CustomEntityService.FindCustomEntitiesBySearchConditions(new SrchCond[] { srchCond }, null, ref bookmark, out status);
                }
            }
            catch (SystemException ex)
            {
                result = ex.ToString();
            }
            return(custEntities);
        }
Exemple #8
0
 public static int getFilesinFolderCountID(VDF.Vault.Currency.Connections.Connection connection, string folderID)
 {
     try
     {
         filecoll = null;
         using (WebServiceManager wServ = connection.WebServiceManager)
         {
             string     bookmark = string.Empty;
             SrchStatus status   = null;
             filecoll = wServ.DocumentService.FindFilesBySearchConditions(null, null, new long[] { Convert.ToInt64(folderID) }, false, true, ref bookmark, out status);
             if (filecoll == null)
             {
                 count = 0;
             }
             else
             {
                 count = filecoll.Count();
             }
             //MessageBox.Show("Count" + filecoll.ToList<Autodesk.Connectivity.WebServices.File>().Count().ToString());
         }
     }
     catch (SystemException ex)
     {
         //statusMess = null;
         Debug.Write("\nError: " + ex.ToString());
         statusMess += "Error: \n" + ex.ToString();
     }
     return(count);
 }
Exemple #9
0
        private List <VDF.Vault.Currency.Entities.IEntity> DoFileSearch(SrchCond[] conditions)
        {
            string     bookmark = string.Empty;
            SrchStatus status   = null;

            //search for files
            List <VDF.Vault.Currency.Entities.IEntity> retVal = new List <VDF.Vault.Currency.Entities.IEntity>();

            while (status == null || retVal.Count < status.TotalHits)
            {
                FileFolder[] filefolders = m_conn.WebServiceManager.DocumentService.FindFileFoldersBySearchConditions(
                    conditions, null, null, true, true,
                    ref bookmark, out status);

                if (filefolders != null)
                {
                    foreach (FileFolder fileFolder in filefolders)
                    {
                        VDF.Vault.Currency.Entities.Folder folder =
                            new VDF.Vault.Currency.Entities.Folder(m_conn, fileFolder.Folder);
                        VDF.Vault.Currency.Entities.FileIteration file =
                            new VDF.Vault.Currency.Entities.FileIteration(
                                m_conn, folder, fileFolder.File);
                        retVal.Add(file);
                    }
                }
            }

            return(retVal);
        }
Exemple #10
0
        //private byte[] StreamToByteArray(System.IO.Stream stream)
        //{
        //    using (var memoryStream = new System.IO.MemoryStream())
        //    {
        //        stream.CopyTo(memoryStream);
        //        return memoryStream.ToArray();
        //    }
        //}

        private CustEnt GetClassCustEntByName(WebServiceManager wsm, string name)
        {
            var custEnts = new List <CustEnt>();

            var custEntDefs = wsm.CustomEntityService.GetAllCustomEntityDefinitions();
            var custEntDef  = custEntDefs.SingleOrDefault(c => c.DispName.Equals("Class"));

            if (custEntDef == null)
            {
                return(custEnts.FirstOrDefault());
            }

            var propDefs          = wsm.PropertyService.GetPropertyDefinitionsByEntityClassId("CUSTENT");
            var propDefDefinition = propDefs.Single(p => p.SysName.Equals("CustomEntitySystemName"));
            var propDefName       = propDefs.Single(p => p.SysName.Equals("Name"));

            var srcCondDefinition = new SrchCond
            {
                PropDefId = propDefDefinition.Id,
                PropTyp   = PropertySearchType.SingleProperty,
                SrchOper  = 3,
                SrchRule  = SearchRuleType.Must,
                SrchTxt   = custEntDef.Name
            };

            var srcCondName = new SrchCond
            {
                PropDefId = propDefName.Id,
                PropTyp   = PropertySearchType.SingleProperty,
                SrchOper  = 3,
                SrchRule  = SearchRuleType.Must,
                SrchTxt   = name
            };

            string     bookmark = null;
            SrchStatus status   = null;

            while (status == null || custEnts.Count < status.TotalHits)
            {
                var results = wsm.CustomEntityService.FindCustomEntitiesBySearchConditions(
                    new[] { srcCondDefinition, srcCondName }, null, ref bookmark, out status);

                if (results != null)
                {
                    custEnts.AddRange(results);
                }
                else
                {
                    break;
                }
            }

            return(custEnts.FirstOrDefault());
        }
Exemple #11
0
        private void RefreshItemList()
        {
            m_tableMap.Clear();
            m_dataTable.Clear();
            m_selectedItem   = null;
            m_gridLabel.Text = "Refreshing Grid";
            m_itemsGrid.Refresh();

            ItemService itemSvc = m_connection.WebServiceManager.ItemService;

            string      bookmark = null;
            List <Item> items    = new List <Item>();
            SrchStatus  status   = null;

            while (status == null || status.TotalHits > items.Count)
            {
                items.AddRange(itemSvc.FindItemRevisionsBySearchConditions(null, null, true, ref bookmark, out status));
            }


            if (items != null && items.Count > 0)
            {
                foreach (Item item in items)
                {
                    LfCycDef   lifeCycleDef = m_lifeCycleMap[item.LfCyc.LfCycDefId];
                    LfCycState state        = lifeCycleDef.StateArray.FirstOrDefault(lifecycleState => lifecycleState.Id == item.LfCycStateId);

                    DataRow newRow = m_dataTable.NewRow();
                    newRow["Item Number"]      = item.ItemNum;
                    newRow["Revision Number"]  = item.RevNum;
                    newRow["Title"]            = item.Title;
                    newRow["Life Cycle State"] = state.Name;

                    ItemFileAssoc [] associations = itemSvc.GetItemFileAssociationsByItemIds(new long [] { item.Id }, ItemFileLnkTypOpt.Primary);
                    if (associations != null)
                    {
                        foreach (ItemFileAssoc assoc in associations)
                        {
                            newRow["Primary File Link"] = assoc.FileName;
                            break;
                        }
                    }

                    m_tableMap[item.ItemNum] = item;
                    m_dataTable.Rows.Add(newRow);
                }
            }



            m_itemsGrid.Refresh();
            m_gridLabel.Text = "Item List";
        }
        private void FindButton_Click(object sender, System.EventArgs e)
        {
            //make sure search conditions have been added
            if (m_criteriaListBox.Items.Count > 0)
            {
                //clear out previous search results if they exist
                m_searchResultsListBox.Items.Clear();

                //build our array of SearchConditions to use for the file search
                SrchCond[] conditions = new SrchCond[m_criteriaListBox.Items.Count];

                for (int i = 0; i < m_criteriaListBox.Items.Count; i++)
                {
                    conditions[i] = ((ListBoxSrchCondItem)m_criteriaListBox.Items[i]).SrchCond;
                }

                string     bookmark = string.Empty;
                SrchStatus status   = null;

                //search for files
                List <File> fileList = new List <File>();

                while (status == null || fileList.Count < status.TotalHits)
                {
                    File[] files = m_connection.WebServiceManager.DocumentService.FindFilesBySearchConditions(
                        conditions, null, null, true, true,
                        ref bookmark, out status);

                    if (files != null)
                    {
                        fileList.AddRange(files);
                    }
                }

                if (fileList.Count > 0)
                {
                    //iterate through found files and display them in the search results list box
                    foreach (File file in fileList)
                    {
                        //create the list item that will wrap the File
                        ListBoxFileItem fileItem = new ListBoxFileItem(new VDF.Vault.Currency.Entities.FileIteration(m_connection, file));

                        m_searchResultsListBox.Items.Add(fileItem);
                    }
                }

                //update the items count label
                m_itemsCountLabel.Text = (fileList.Count > 0) ? fileList.Count + " Items" : "0 Items";
            }
        }
        public static List <FileIteration> InitVault(out List <FileIteration> parts)
        {
            parts = new List <FileIteration>();

            // For Login Sequence to work AdskLicensingSDK_#.dll must be present and referenced in
            // build events
            // xcopy "$(ProjectDir)..\..\..\..\bin\$(PlatformName)\AdskLicensingSDK_*.dll" "$(TargetDir)" /y
            // m_conn = Vault.Forms.Library.Login(null);
            // m_model = new Forms.Models.BrowseVaultNavigationModel(m_conn, true, true);

            List <File> files        = null;
            string      bookmark     = string.Empty;
            SrchStatus  status       = null;
            List <File> totalResults = new List <File>();

            Vault.Results.LogInResult result = VaultLogin();
            v_Conn = result.Connection;

            while (status == null || totalResults.Count < status.TotalHits)
            {
                File[] results = result.Connection.WebServiceManager.DocumentService.FindFilesBySearchConditions(null, null, null, false, true, ref bookmark, out status);

                if (results != null)
                {
                    totalResults.AddRange(results);
                }
                else
                {
                    break;
                }
            }

            ReadProperties(result.Connection);

            foreach (File f in totalResults)
            {
                try
                {
                    FileIteration fi = new Vault.Currency.Entities.FileIteration(result.Connection, f);
                    //PrintProperties(result.Connection, fi);
                    parts.Add(fi);
                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.Message);
                }
            }

            return(parts);
        }
Exemple #14
0
        public static FileFolder SearchVault(System.IO.FileInfo symFile)
        {
            // search the vault for the specified file
            // find the Filename property

            //string fname = getIptFileName(symFile.Name);
            string fname = (Path.GetFileNameWithoutExtension(symFile.Name) + ".ipt");

            Autodesk.DataManagement.Client.Framework.Vault.Currency.Properties.PropertyDefinition propDef = connection.PropertyManager.GetPropertyDefinitionBySystemName("ClientFileName");

            if (propDef == null)
            {
                throw new Exception("Error looking up FileName property");
            }

            SrchCond condition = new SrchCond();

            condition.SrchTxt   = fname;
            condition.SrchOper  = 3; //exact match
            condition.PropDefId = propDef.Id;
            condition.PropTyp   = PropertySearchType.SingleProperty;

            List <FileFolder> resultList = new List <FileFolder>();
            SrchStatus        status     = null;
            string            bookmark   = string.Empty;


            while (status == null || resultList.Count < status.TotalHits)
            {
                //FileFolder[] results = docSrv.FindFileFoldersBySearchConditions(
                FileFolder[] results = connection.WebServiceManager.DocumentService.FindFileFoldersBySearchConditions(
                    new SrchCond[] { condition }, null, null, true, true, ref bookmark, out status);


                if (results != null)
                {
                    resultList.AddRange(results);
                    return(resultList[0]);
                }
                else
                {
                    return(null);
                }
            }
            return(null);
        }
 public CustEnt[] getCustomentitiesbyPropNameMulti(VDF.Vault.Currency.Connections.Connection connection, SrchCond[]  srchConds)
 {
     try
     {
         //
         using (WebServiceManager serviceManager = connection.WebServiceManager) //using will log out after usage
         {
             string     bookmark = string.Empty;
             SrchStatus status   = null;
             custEntities = connection.WebServiceManager.CustomEntityService.FindCustomEntitiesBySearchConditions(srchConds, null, ref bookmark, out status);
         }
     }
     catch (SystemException ex)
     {
         result = ex.ToString();
     }
     return(custEntities);
 }
Exemple #16
0
 public static Autodesk.Connectivity.WebServices.File[] getFilesfromVaultFolder(VDF.Vault.Currency.Connections.Connection connection, string vaultFolder)
 {
     try
     {
         filecoll = null;
         using (WebServiceManager wServ = connection.WebServiceManager)
         {
             string     bookmark = string.Empty;
             SrchStatus status   = null;
             filecoll = wServ.DocumentService.FindFilesBySearchConditions(null, null, new long[] { wServ.DocumentService.GetFolderByPath(vaultFolder).Id }, false, true, ref bookmark, out status);
             //MessageBox.Show("Count" + filecoll.ToList<Autodesk.Connectivity.WebServices.File>().Count().ToString());
         }
     }
     catch (SystemException ex)
     {
         //statusMess = null;
         Debug.Write("\nError: " + ex.ToString());
         statusMess += "Error: \n" + ex.ToString();
     }
     return(filecoll);
 }
Exemple #17
0
        public JobOutcome Execute(IJobProcessorServices context, IJob job)
        {
            var wsm = context.Connection.WebServiceManager;

            #region Property Definitions
            var propDefs                  = wsm.PropertyService.GetPropertyDefinitionsByEntityClassId("FILE");
            var propDefInternalId         = propDefs.Single(n => n.DispName == "Internal ID");
            var propDefProvider           = propDefs.Single(n => n.DispName == "Provider");
            var propDefOriginalCreateDate = propDefs.Single(n => n.DispName == "Original Create Date");
            #endregion

            #region Search Conditions
            var srchCondInternalId = new SrchCond
            {
                PropDefId = propDefInternalId.Id,
                PropTyp   = PropertySearchType.SingleProperty,
                SrchOper  = 4, // Is empty
                SrchRule  = SearchRuleType.Must
            };

            var srchCondInternalProvider = new SrchCond
            {
                PropDefId = propDefProvider.Id,
                PropTyp   = PropertySearchType.SingleProperty,
                SrchOper  = 3, // Is exactly (or equals)
                SrchRule  = SearchRuleType.Must,
                SrchTxt   = "Inventor"
            };

            var srchCondDateTime = new SrchCond
            {
                PropDefId = propDefOriginalCreateDate.Id,
                PropTyp   = PropertySearchType.SingleProperty,
                SrchOper  = 7, // Greater than or equal to
                SrchRule  = SearchRuleType.Must,
                SrchTxt   = DateTime.Now.AddDays(-15).ToUniversalTime().ToString(
                    "MM/dd/yyyy HH:mm:ss")
            };
            #endregion

            string     bookmark = null;
            SrchStatus status   = null;
            var        files    = new List <File>();
            while (status == null || files.Count < status.TotalHits)
            {
                var results = wsm.DocumentService.FindFilesBySearchConditions(
                    new[] { srchCondInternalId, srchCondInternalProvider, srchCondDateTime },
                    null,
                    null,
                    false,
                    true,
                    ref bookmark,
                    out status);

                if (results != null)
                {
                    files.AddRange(results);
                }
                else
                {
                    break;
                }
            }

            foreach (var file in files)
            {
                var localFilePath = string.Format(@"C:\temp\{0}", file.Name);
                try
                {
                    #region Download file
                    var fileSize    = file.FileSize;
                    var maxPartSize = wsm.FilestoreService.GetMaximumPartSize();
                    var ticket      = wsm.DocumentService.GetDownloadTicketsByMasterIds(
                        new[] { file.MasterId })[0];
                    byte[] bytes;

                    using (var stream = new System.IO.MemoryStream())
                    {
                        var startByte = 0;
                        while (startByte < fileSize)
                        {
                            var endByte = startByte + maxPartSize;
                            if (endByte > fileSize)
                            {
                                endByte = fileSize;
                            }

                            using (var filePart = wsm.FilestoreService.DownloadFilePart(
                                       ticket.Bytes, startByte, endByte, true))
                            {
                                byte[] buffer = StreamToByteArray(filePart);
                                stream.Write(buffer, 0, buffer.Length);
                                startByte += buffer.Length;
                            }
                        }

                        bytes = new byte[stream.Length];
                        stream.Seek(0, System.IO.SeekOrigin.Begin);
                        stream.Read(bytes, 0, (int)stream.Length);

                        stream.Close();
                    }

                    System.IO.File.WriteAllBytes(localFilePath, bytes);
                    #endregion

                    #region Get InternalName
                    var internalId = Apprentice.GetInternalId(localFilePath);
                    #endregion

                    #region Update properties
                    var util = Autodesk.Connectivity.Explorer.ExtensibilityTools.ExplorerLoader.
                               LoadExplorerUtil(
                        wsm.WebServiceCredentials.ServerIdentities.DataServer,
                        wsm.WebServiceCredentials.VaultName,
                        context.Connection.UserID,
                        context.Connection.Ticket);

                    var properties = new Dictionary <PropDef, object>
                    {
                        { propDefInternalId, internalId }
                    };
                    util.UpdateFileProperties(file, properties);
                    #endregion
                }
                catch (Exception ex)
                {
                    Console.WriteLine(ex);
                }
                finally
                {
                    #region Delete local file
                    if (System.IO.File.Exists(localFilePath))
                    {
                        try
                        {
                            System.IO.File.Delete(localFilePath);
                        }
                        catch (Exception ex)
                        {
                            Console.WriteLine(ex);
                        }
                    }
                    #endregion
                }
            }

            return(JobOutcome.Success);
        }
        private List </*Tuple<ADSK.File, string, bool, bool>*/ VaultEagleLib.Model.DataStructures.DownloadItem> FindFilesChangedSinceLastSync(VDF.Vault.Currency.Connections.Connection connection, bool useLastSyncTime, DateTime lastSyncTime, string vaultRoot, int retries, NotifyIcon trayIcon, VaultEagleLib.SynchronizationItem[] items, Option <MCADCommon.LogCommon.DisposableFileLogger> logger)
        {
            string lastSyncTag = lastSyncTime.ToUniversalTime().ToString("MM/dd/yyyy HH:mm:ss", CultureInfo.InvariantCulture);

            logger.IfSomeDo(l => l.Trace("Fetching files with date modified after: " + lastSyncTag + "."));

            long modifiedId = connection.WebServiceManager.PropertyService.GetPropertyDefinitionsByEntityClassId("FILE").First(p => p.DispName == "Date Modified").Id;

            SrchCond filesCreatedAfterLastSyncTime = new SrchCond {
                SrchTxt = lastSyncTag, SrchRule = SearchRuleType.Must, SrchOper = 7, PropDefId = modifiedId, PropTyp = PropertySearchType.SingleProperty
            };


            // logger.Trace("Fetched: " + filesAndFolders.Count + " files before filtering.");

            //List<Tuple<ADSK.File, string, bool, bool>> fileAndPath = new List<Tuple<ADSK.File, string, bool, bool>>();
            List <VaultEagleLib.Model.DataStructures.DownloadItem> filesToDownload = new List <VaultEagleLib.Model.DataStructures.DownloadItem>();
            List <ADSK.File> addedFiles = new List <ADSK.File>();

            items = VaultEagleLib.SynchronizationItem.UpdateListWithTactonItems(items);
            List <string> Checked = new List <string>();
            int           i       = 0;

            trayIcon.Text = "0 of " + items.Count() + " download items to iterate over.";
            foreach (VaultEagleLib.SynchronizationItem item in items)
            {
                if (Checked.Contains(item.SearchPath.ToLower()))
                {
                    continue;
                }
                try
                {
                    Option <Folder> folder   = Option.None;
                    Option <string> fileName = Option.None;

                    if (!System.IO.Path.HasExtension(item.SearchPath))
                    {
                        try
                        {
                            folder = connection.WebServiceManager.DocumentService.GetFolderByPath(item.SearchPath).AsOption();
                        }
                        catch { }
                    }
                    else
                    {
                        try
                        {
                            if (item.SearchPath.Contains('.'))
                            {
                                int k = item.SearchPath.LastIndexOf('/');
                                if (k > 0 && connection.WebServiceManager.DocumentService.FindFoldersByPaths(new string[] { item.SearchPath.Substring(0, k) }).Count() > 0)
                                {
                                    folder   = connection.WebServiceManager.DocumentService.GetFolderByPath(item.SearchPath.Substring(0, k)).AsOption();
                                    fileName = item.SearchPath.Substring(k + 1).AsOption();
                                }
                            }
                        }
                        catch { }
                    }
                    if (folder.IsSome && folder.Get().Id > 0)
                    {
                        List <Tuple <FileFolder, Option <string> > > FileFolderAndComponentName = new List <Tuple <FileFolder, Option <string> > >();
                        List <FileFolder> filesAndFolders = new List <FileFolder>();
                        List <Folder>     folders         = new List <Folder>();
                        SrchStatus        status          = null;
                        string            bookmark        = string.Empty;
                        bool singleFile = false;
                        while (status == null || filesAndFolders.Count < status.TotalHits)
                        {
                            FileFolder[] results;
                            ADSK.File[]  files = connection.WebServiceManager.DocumentService.GetLatestFilesByFolderId(folder.Get().Id, false).Where(f => f.Name.Equals(fileName.Get(), StringComparison.InvariantCultureIgnoreCase)).ToArray();
                            if (fileName.IsSome && files.Count() > 0)
                            {
                                singleFile = true;
                                ADSK.File       file       = files.First();
                                ADSK.FileFolder fileFolder = new FileFolder();
                                fileFolder.File   = file;
                                fileFolder.Folder = folder.Get();
                                results           = new FileFolder[] { fileFolder };
                            }
                            else if (item.ComponentName.IsSome)
                            {
                                logger.IfSomeDo(l => l.Info("Could not find file: " + fileName + " for component: " + item.ComponentName.Get()));
                                break;
                            }
                            else if (item.Mirrors.Count() > 0 || !useLastSyncTime)
                            {
                                results = connection.WebServiceManager.DocumentService.FindFileFoldersBySearchConditions(new SrchCond[] { }, null, new long[] { folder.Get().Id }, item.Recursive, true, ref bookmark, out status);
                            }
                            else
                            {
                                results = connection.WebServiceManager.DocumentService.FindFileFoldersBySearchConditions(new SrchCond[] { filesCreatedAfterLastSyncTime }, null, new long[] { folder.Get().Id }, item.Recursive, true, ref bookmark, out status);
                            }


                            List <FileFolder> allChildren = new List <FileFolder>();
                            //**********************************************************************************************/
                            if (item.GetChildren)
                            {
                                foreach (FileFolder ff in results)
                                {
                                    foreach (ADSK.File childFile in MCADCommon.VaultCommon.FileOperations.GetAllChildren(ff.File.MasterId, new List <ADSK.File>(), connection))
                                    {
                                        FileFolder child = new FileFolder();

                                        child.File   = childFile;
                                        child.Folder = connection.WebServiceManager.DocumentService.GetFolderById(childFile.FolderId);
                                        allChildren.Add(child);
                                        Checked.Add((child.Folder.FullName + "/" + child.File.Name).ToLower());
                                    }
                                }
                            }

                            //***************************************************************************************************/

                            if (results != null)
                            {
                                filesAndFolders.AddRange(results);
                                FileFolderAndComponentName.AddRange(results.Select(r => new Tuple <FileFolder, Option <string> >(r, item.ComponentName)));
                            }
                            if (allChildren.Count > 0)
                            {
                                filesAndFolders.AddRange(allChildren);
                                FileFolderAndComponentName.AddRange(allChildren.Select(r => new Tuple <FileFolder, Option <string> >(r, item.ComponentName)));
                            }
                            Checked.Add(item.SearchPath.ToLower());
                            if (singleFile)
                            {
                                break;
                            }
                        }
                        status = null;
                        if (item.PatternsToSynchronize.Contains("/") || item.Mirrors.Count() > 0)
                        {
                            while (status == null || folders.Count < status.TotalHits)
                            {
                                Folder[] folderResults = connection.WebServiceManager.DocumentService.FindFoldersBySearchConditions(new SrchCond[] { }, null, new long[] { folder.Get().Id }, item.Recursive, ref bookmark, out status);

                                if (folderResults != null)
                                {
                                    folders.AddRange(folderResults);
                                }
                            }
                        }
                        FileFolderAndComponentName = FileFolderAndComponentName.OrderBy(f => f.Item1.Folder.FullName.Length).ToList();
                        FileFolderAndComponentName = FileFolderAndComponentName.Where(f => !f.Item1.File.Hidden).ToList();
                        filesToDownload.AddRange(item.GetFilesAndPathsForItem(connection, FileFolderAndComponentName, addedFiles, vaultRoot, item.GetChildren, retries));

                        if (item.PatternsToSynchronize.Contains("/"))
                        {
                            filesToDownload.AddRange(item.GetFoldersAndPathsForItem(folders, vaultRoot));
                        }

                        if (item.Mirrors.Count() > 0)
                        {
                            item.AddMirrorFolders(folders);
                        }

                        i++;
                        trayIcon.Text = i + " of " + items.Count() + " download items checked.";
                        // Console.WriteLine(i);
                    }
                    else
                    {
                        logger.IfSomeDo(l => l.Error("Incorrect input path: " + item.SearchPath + "."));
                    }
                }
                catch (Exception ex)
                {
                    logger.IfSomeDo(l => l.Error("Error with synchronization item: " + ex.Message + "."));
                }
            }
            //List<Tuple<ADSK.File, string, bool, bool>> filesAndPathsToDl = new List<Tuple<ADSK.File, string, bool, bool>>();
            List <VaultEagleLib.Model.DataStructures.DownloadItem> filesToDl = new List <VaultEagleLib.Model.DataStructures.DownloadItem>();

            /* filesAndPathsToDl = fileAndPath.Where(f => f.Item1 != null).ToList();
             * filesAndPathsToDl = filesAndPathsToDl.DistinctBy(f => f.Item1.MasterId).ToList();
             * filesAndPathsToDl.AddRange(fileAndPath.Where(f => f.Item1 == null).ToList()); */
            filesToDl = filesToDownload.Where(f => f is VaultEagleLib.Model.DataStructures.DownloadFile).ToList();
            filesToDl = filesToDl.DistinctBy(f => ((VaultEagleLib.Model.DataStructures.DownloadFile)f).File.MasterId).ToList();
            filesToDl.AddRange(filesToDownload.Where(f => !(f is VaultEagleLib.Model.DataStructures.DownloadFile)));

            return /*removeExcludedPaths*/ (filesToDl);//filesAndPathsToDl;
        }
Exemple #19
0
        private void ProcessItem(Item item, Autodesk.Connectivity.WebServices.File iptiamfile)
        {
            FilePath [] filepaths  = ServiceManager.DocumentService.FindFilePathsByNameAndChecksum(iptiamfile.Name, iptiamfile.Cksum);
            String      iptiampath = filepaths[0].Path.Replace("$", "C:/Vault WorkingFolder");

            String stepfilename = "C:/Vault WorkingFolder/Export Files/" + item.ItemNum + "-" + iptiamfile.FileRev.Label + ".stp";

            //checking if attachment exists..
            OnItemStatusUpdate(new ItemStatusUpdateEventArgs(item, "Checking attachments.."));
            Attmt[] atts = ServiceManager.ItemService.GetAttachmentsByItemId(item.Id);
            foreach (Attmt att in atts)
            {
                //getting file object of attachment..
                Autodesk.Connectivity.WebServices.File attmtfile = ServiceManager.DocumentService.GetFileById(att.FileId);
                //checking filename..
                if (attmtfile.Name == System.IO.Path.GetFileName(stepfilename))
                {
                    OnItemStatusUpdate(new ItemStatusUpdateEventArgs(item, "Step-file already attached"));
                    return;
                }
            }
            //no stepfile found as attachment
            //looking for step file in vault...
            OnItemStatusUpdate(new ItemStatusUpdateEventArgs(item, "Searching for step-file in vault.."));
            PropDef[] filePropDefs    = ServiceManager.PropertyService.GetPropertyDefinitionsByEntityClassId("FILE");
            PropDef   filenamePropDef = filePropDefs.Single(n => n.SysName == "Name");
            SrchCond  isFilename      = new SrchCond()
            {
                PropDefId = filenamePropDef.Id,
                PropTyp   = PropertySearchType.SingleProperty,
                SrchOper  = 3,
                SrchRule  = SearchRuleType.Must,
                SrchTxt   = System.IO.Path.GetFileName(stepfilename)
            };
            string     bookmark = string.Empty;
            SrchStatus status   = null;

            Autodesk.Connectivity.WebServices.File[] results = ServiceManager.DocumentService.FindFilesBySearchConditions(new SrchCond[] { isFilename }, null, null, false, true, ref bookmark, out status);

            Autodesk.Connectivity.WebServices.File newfile;

            if (results == null)
            {
                //no stepfile in vault, user must add
                OnItemStatusUpdate(new ItemStatusUpdateEventArgs(item, System.IO.Path.GetFileName(stepfilename) + " not found in vault"));
                return;



                /*
                 * //no stepfile in vault, downloading ipt and generating stepfile
                 * OnItemStatusUpdate(new ItemStatusUpdateEventArgs(item, "Retreiving files.."));
                 *
                 * ByteArray buffer;
                 * String fullpath;
                 * FilePathArray [] fparray = ServiceManager.DocumentService.GetLatestAssociatedFilePathsByMasterIds(new long [] {iptiamfile.MasterId}, FileAssociationTypeEnum.None, false, FileAssociationTypeEnum.Dependency, true, false, true, false);
                 * foreach (FilePath fp in fparray[0].FilePaths)
                 * {
                 *  fullpath = fp.Path.Replace("$", "C:/Vault WorkingFolder");
                 *  ServiceManager.DocumentService.DownloadFile(fp.File.Id, true, out buffer);
                 *  if (System.IO.File.Exists(fullpath) == true)
                 *  {
                 *      System.IO.File.SetAttributes(fullpath, FileAttributes.Normal);
                 *  }
                 *  System.IO.File.WriteAllBytes(fullpath, buffer.Bytes);
                 *  System.IO.File.SetAttributes(fullpath, FileAttributes.ReadOnly);
                 * }
                 *
                 * Inventor.Application m_inventorApp;
                 * OnItemStatusUpdate(new ItemStatusUpdateEventArgs(item, "Looking for Inventor.."));
                 * try //Try to get an active instance of Inventor
                 * {
                 *  try
                 *  {
                 *      m_inventorApp = System.Runtime.InteropServices.Marshal.GetActiveObject("Inventor.Application") as Inventor.Application;
                 *  }
                 *  catch
                 *  {
                 *      Type inventorAppType = System.Type.GetTypeFromProgID("Inventor.Application");
                 *
                 *      m_inventorApp = System.Activator.CreateInstance(inventorAppType) as Inventor.Application;
                 *
                 *      //Must be set visible explicitly
                 *      m_inventorApp.Visible = true;
                 *  }
                 * }
                 * catch
                 * {
                 *  OnItemStatusUpdate(new ItemStatusUpdateEventArgs(item, "couldn't create Inventor instance"));
                 *  return;
                 * }
                 * OnItemStatusUpdate(new ItemStatusUpdateEventArgs(item, "Opening file.."));
                 * _Document iptdocu = m_inventorApp.Documents.Open(iptiampath, true);
                 *
                 * //Inventor.ApprenticeServerComponent appserver;
                 * //appserver = new ApprenticeServerComponent();
                 * //Inventor.ApprenticeServerDocument appdocu;
                 * //appdocu = appserver.Open(iptiampath);
                 *
                 * OnItemStatusUpdate(new ItemStatusUpdateEventArgs(item, "Generating step-file.."));
                 *
                 * if (System.IO.File.Exists(stepfilename) == true)
                 * {
                 *  System.IO.File.SetAttributes(stepfilename, FileAttributes.Normal);
                 * }
                 *
                 * iptdocu.SaveAs(stepfilename, true);
                 *
                 * //FileSaveAs sa;
                 * //sa = appserver.FileSaveAs;
                 * //sa.AddFileToSave(appdocu, stepfilename);
                 * //sa.ExecuteSaveCopyAs();
                 *
                 * System.IO.File.SetAttributes(stepfilename, FileAttributes.ReadOnly);
                 *
                 * OnItemStatusUpdate(new ItemStatusUpdateEventArgs(item, "Closing part-file.."));
                 * iptdocu.Close(true);
                 * //appdocu.Close();
                 *
                 * //OnItemStatusUpdate(new ItemStatusUpdateEventArgs(item, "Deleting part-file.."));
                 * //System.IO.File.Delete(iptfilename);
                 *
                 * OnItemStatusUpdate(new ItemStatusUpdateEventArgs(item, "Adding step-file to vault.."));
                 * // add file to vault + attach
                 *
                 * Folder[] folders = ServiceManager.DocumentService.FindFoldersByPaths(new string[] { "$/Export Files" });
                 * long folderid = folders[0].Id;
                 * System.IO.FileInfo info = new FileInfo(stepfilename);
                 * buffer = new ByteArray();
                 * buffer.Bytes = System.IO.File.ReadAllBytes(stepfilename);
                 *
                 * //OnItemStatusUpdate(new ItemStatusUpdateEventArgs(item, "addfile"));
                 * try
                 * {
                 *  newfile = ServiceManager.DocumentService.AddFile(folderid, System.IO.Path.GetFileName(stepfilename), "Added by Martijns stepfileplugin", info.LastWriteTime, null, null, FileClassification.None, false, buffer);
                 * }
                 * catch (Exception ex)
                 * {
                 *  OnItemStatusUpdate(new ItemStatusUpdateEventArgs(item, "Failed"));
                 *  MessageBox.Show("Error: " + ex.Message);
                 *  return;
                 * }
                 * //1008 addfileexists
                 * //1009 addfile failed
                 */
            }
            else
            {
                if (results.Count() > 1)
                {
                    OnItemStatusUpdate(new ItemStatusUpdateEventArgs(item, "Failed"));
                    MessageBox.Show("Error: more then 1 file with the name " + System.IO.Path.GetFileName(stepfilename + " exist in vault!"));
                    return;
                }
                newfile = results[0];
            }
            //OnItemStatusUpdate(new ItemStatusUpdateEventArgs(item, "new attmt"));

            Attmt newattachment = new Attmt();

            newattachment.FileId = newfile.Id;
            newattachment.Pin    = false;

            //OnItemStatusUpdate(new ItemStatusUpdateEventArgs(item, "new edititem"));

            Array.Resize(ref atts, atts.Count() + 1);
            atts[atts.Count() - 1] = newattachment;

            Item edititem = ServiceManager.ItemService.EditItem(item.RevId);

            ServiceManager.ItemService.UpdateAndCommitItem(edititem, 0, false, null, null, null, atts, null, null, 2);

            OnItemStatusUpdate(new ItemStatusUpdateEventArgs(item, "Done"));
        }
        public override void Execute_Impl()
        {
            ThrowIfCancellationRequested();

            ChangeStatusMessage("Starting Partial Mirror...");

            // find the Create Date property
            PropDef[] props = Connection.WebServiceManager.PropertyService.FindPropertyDefinitionsBySystemNames(
                "FILE", new string [] { "CheckInDate" });

            if (props.Length != 1 || props[0].Id < 0)
            {
                throw new Exception("Error looking up CheckInDate property");
            }

            // grab all of the files added or checked in since the last sync time
            SrchCond condition = new SrchCond();

            condition.SrchTxt   = m_lastSyncTime.ToUniversalTime().ToString("MM/dd/yyyy HH:mm:ss");
            condition.SrchOper  = 7; // greater than or equal to
            condition.PropDefId = props[0].Id;
            condition.PropTyp   = PropertySearchType.SingleProperty;

            List <FileFolder> resultList = new List <FileFolder>();
            SrchStatus        status     = null;
            string            bookmark   = string.Empty;

            while (status == null || resultList.Count < status.TotalHits)
            {
                ThrowIfCancellationRequested();
                FileFolder[] results = Connection.WebServiceManager.DocumentService.FindFileFoldersBySearchConditions(
                    new SrchCond[] { condition },
                    new SrchSort[] { new SrchSort()
                                     {
                                         PropDefId = props[0].Id, SortAsc = false
                                     } },
                    null, true, false, ref bookmark, out status);

                if (results != null)
                {
                    resultList.AddRange(results);
                }
            }

            string localPath = OutputFolder;

            HashSet <long> mirroredFiles = new HashSet <long>();

            if (resultList.Count == 0)
            {
                return;
            }

            foreach (FileFolder result in resultList)
            {
                ThrowIfCancellationRequested();

                if (result == null || result.File.Cloaked || result.Folder.Cloaked)
                {
                    continue;
                }

                if (mirroredFiles.Contains(result.File.MasterId))
                {
                    continue;
                }

                string vaultFolder = result.Folder.FullName;
                if (vaultFolder == "$")
                {
                    vaultFolder = "";
                }
                else
                {
                    vaultFolder = vaultFolder.Substring(2);  // remove the $/ at the beginning
                }
                string localFolder = null;

                if (!UseWorkingFolder)
                {
                    localFolder = Path.Combine(localPath, vaultFolder);
                    if (!Directory.Exists(localFolder))
                    {
                        Directory.CreateDirectory(localFolder);
                    }
                    localFolder = Path.Combine(localFolder, result.File.Name);
                }

                AddFileToDownload(result.File, localFolder);

                mirroredFiles.Add(result.File.MasterId);
            }

            DownloadFiles();
        }