private void AddCriteriaButton_Click(object sender, System.EventArgs e)
        {
            //get a local reference of the currently selected PropertyDefinition object
            ListBoxPropDefItem propertyItem = m_propertyComboBox.SelectedItem as ListBoxPropDefItem;
            PropDef            property;

            property = (propertyItem == null) ? null : propertyItem.PropDef;

            //get local reference of the condition combo boxes currently selected item
            Condition condition = m_conditionComboBox.SelectedItem as Condition;

            if (property == null || condition == null)
            {
                return;
            }

            //create a SearchCondition object
            SrchCond searchCondition = new SrchCond();

            searchCondition.PropDefId = property.Id;
            searchCondition.PropTyp   = PropertySearchType.SingleProperty;
            searchCondition.SrchOper  = condition.Code;
            searchCondition.SrchTxt   = m_valueTextBox.Text;

            //create the list item to contain the condition
            ListBoxSrchCondItem searchItem = new ListBoxSrchCondItem(searchCondition, property);

            //add the SearchCondition object to the search criteria list box
            m_criteriaListBox.Items.Add(searchItem);
        }
示例#2
0
        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);
        }
示例#3
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);
        }
示例#4
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);
        }
示例#5
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());
        }
        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";
            }
        }
示例#7
0
        private void RunFind()
        {
            //make sure search conditions have been added
            if (m_criteriaListBox.Items.Count > 0)
            {
                //clear out previous search results if they exist
                ClearGrid();

                //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] = ((SrchCondItem)m_criteriaListBox.Items[i]).SrchCond;
                }

                List <VDF.Vault.Currency.Entities.IEntity> results = null;
                if (m_entityClassComboBox.SelectedItem == EntityClass.FILE)
                {
                    results = DoFileSearch(conditions);
                }
                else if (m_entityClassComboBox.SelectedItem == EntityClass.ITEM)
                {
                    results = DoItemSearch(conditions);
                }
                else if (m_entityClassComboBox.SelectedItem == EntityClass.CO)
                {
                    results = DoChangeOrderSearch(conditions);
                }
                else if (m_entityClassComboBox.SelectedItem == EntityClass.FLDR)
                {
                    results = DoFolderSearch(conditions);
                }
                else if (m_entityClassComboBox.SelectedItem == EntityClass.CUSTENT)
                {
                    results = DoCustEntSearch(conditions);
                }

                if (results != null && results.Count > 0)
                {
                    m_gridContent.AddContent(results);
                    m_itemsCountLabel.Text = results.Count + " entities found";
                    m_vaultBrowseControl.Refresh();
                }
                else
                {
                    m_itemsCountLabel.Text = "0 entities found";
                }
            }
        }
示例#8
0
        private void m_addCriteriaButton_Click(object sender, EventArgs e)
        {
            //get a local reference of the currently selected PropertyDefinition object
            PropDefItem propertyItem = m_propertyComboBox.SelectedItem as PropDefItem;
            PropDef     property;

            property = (propertyItem == null) ? null : propertyItem.PropDef;

            //get local reference of the condition combo boxes currently selected item
            Condition condition = m_conditionComboBox.SelectedItem as Condition;

            if (property == null || condition == null)
            {
                return;
            }

            SearchRuleType rule     = SearchRuleType.Must;
            RuleItem       ruleItem = m_ruleComboBox.SelectedItem as RuleItem;

            if (ruleItem != null)
            {
                rule = ruleItem.Rule;
            }


            //create a SearchCondition object
            SrchCond searchCondition = new SrchCond();

            searchCondition.PropDefId = property.Id;
            searchCondition.PropTyp   = PropertySearchType.SingleProperty;
            searchCondition.SrchOper  = condition.Code;
            if (checkBox1.Checked)
            {
                //here we would effectively need to perform a search for everything and then search those results.
                searchCondition.SrchTxt = m_valueComboBox.SelectedItem.ToString();
            }
            else
            {
                searchCondition.SrchTxt = m_valueTextBox.Text;
            }

            searchCondition.SrchRule = rule;


            //create the list item to contain the condition
            SrchCondItem searchItem = new SrchCondItem(searchCondition, property);

            //add the SearchCondition object to the search criteria list box
            m_criteriaListBox.Items.Add(searchItem);
        }
示例#9
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 SrchCondItem(SrchCond srchCond, PropDef propDef)
 {
     this.SrchCond = srchCond;
     this.PropDef  = propDef;
 }
示例#11
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"));
        }
        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;
        }
示例#13
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);
        }
        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();
        }