public static void Main()
    {
        //reference to the active project and the main window
        Form primaryMainForm = Program.ActiveProjectShell.PrimaryMainForm;

        if (primaryMainForm == null)
        {
            return;
        }

        SwissAcademic.Citavi.Project activeProject = Program.ActiveProjectShell.Project;
        if (activeProject == null)
        {
            return;
        }

        if (IsBackupAvailable() == false)
        {
            return;                                                                     //user wants to backup his/her project first
        }
        //if no reference filters applied, macro cannot operate
        if (Program.ActiveProjectShell.PrimaryMainForm.ReferenceEditorFilterSet.Filters.Count == 0)
        {
            string message = "This macro requires a selection of references to operate on.\r\n";
            message += "Please select some references with PDF files attached.";
            MessageBox.Show(message, "Citavi");
            return;
        }

        //path to the current project's CitaviFiles folder
        string citaviFilesPath = activeProject.GetFolderPath(CitaviFolder.CitaviFiles);

        List <Reference> references = Program.ActiveProjectShell.PrimaryMainForm.GetFilteredReferences();

        //List<Reference> references = CollectionUtility.ToList(activeProject.References);

        #region Generate list of file locations to move

        //first we create a list of files attached to the currently selected references,
        //having a PDF extension,
        //and existing inside the CitaviFiles folder
        List <FileMoveOperation> fileMoveOperations = new List <FileMoveOperation>();

        foreach (Reference reference in references)
        {
            foreach (Location location in reference.Locations)
            {
                if (location.LocationType != LocationType.ElectronicAddress)
                {
                    continue;
                }

                if (location.AddressUri.AddressInfo == ElectronicAddressInfo.CitaviFiles)
                {
                    if (Path.GetExtension(location.Address).Equals(".pdf", StringComparison.OrdinalIgnoreCase))
                    {
                        FileMoveOperation fileMoveOperation = new FileMoveOperation(location);
                        fileMoveOperations.Add(fileMoveOperation);
                        //MessageBox.Show(fileMoveOperation.SourcePath);
                        //MessageBox.Show(fileMoveOperation.OriginalFileName);
                    }
                }
            }
        }

        if (fileMoveOperations.Count == 0)
        {
            string message = string.Format("The {0} selected reference(s) do not have any PDF files attached, that are stored inside the CitaviFiles folder.", references.Count);
            MessageBox.Show(message, "Citavi");
            return;
        }

        #endregion Generate list of file locations to move

        #region Prompt user for target folder to move files to

        string targetFolderPath = string.Empty;

        using (var folderPicker = new CommonOpenFileDialog())
        {
            folderPicker.IsFolderPicker   = true;
            folderPicker.Title            = string.Format("Select the folder where you want to move the {0} PDF files to.", fileMoveOperations.Count);
            folderPicker.InitialDirectory = Program.Settings.InitialDirectories.GetInitialDirectory(SwissAcademic.Citavi.Settings.InitialDirectoryContext.LocalFile, null);
            if (folderPicker.ShowDialog() == CommonFileDialogResult.Ok)
            {
                targetFolderPath = folderPicker.FileName;
            }
            else
            {
                MessageBox.Show("Macro execution cancelled upon user's request.", "Citavi");
                return;
            }
        }



        #endregion Prompt user for target folder to move files to

        #region Copy the files to the new folder

        DirectoryInfo targetDirectory = new DirectoryInfo(targetFolderPath);

        foreach (FileMoveOperation fileMoveOperation in fileMoveOperations)
        {
            //avoid overwriting a possible existing file
            fileMoveOperation.TargetPath = Path2.GetUniqueFilePath(targetDirectory, fileMoveOperation.OriginalFileName);
            try
            {
                File.Copy(fileMoveOperation.SourcePath, fileMoveOperation.TargetPath, false);
                fileMoveOperation.CopySuccess = true;
            }
            catch (Exception exception)
            {
                fileMoveOperation.Errors.Add(exception);
                fileMoveOperation.CopySuccess = false;
            }
        }

        #endregion Copy the files to the new region

        #region Relink each reference to the new files

        foreach (FileMoveOperation fileMoveOperation in fileMoveOperations)
        {
            if (fileMoveOperation.CopySuccess)
            {
                try
                {
                    fileMoveOperation.TargetLocation       = fileMoveOperation.SourceLocation.Reference.Locations.Add(LocationType.ElectronicAddress, fileMoveOperation.TargetPath, string.Empty, false);
                    fileMoveOperation.TargetLocation.Notes = fileMoveOperation.SourceLocation.Notes;
                    fileMoveOperation.RelinkSuccess        = true;
                }
                catch (Exception exception)
                {
                    fileMoveOperation.Errors.Add(exception);
                    fileMoveOperation.RelinkSuccess = false;
                }
            }
        }

        #endregion Relink each reference to the new files

        #region Delete the original locations and move the files in the CitaviFiles folder to CitaviFiles\RecycleBin

        foreach (FileMoveOperation fileMoveOperation in fileMoveOperations)
        {
            if (fileMoveOperation.RelinkSuccess)
            {
                try
                {
                    Location locationToDelete = fileMoveOperation.SourceLocation;
                    Project  locationProject  = locationToDelete.Project;

                    if (locationToDelete == null)
                    {
                        continue;
                    }

                    ElectronicAddressUri addressUriToDelete = locationToDelete.AddressUri;
                    locationToDelete.Reference.Locations.Remove(locationToDelete);
                    Program.ActiveProjectShell.Save(primaryMainForm);


                    DirectoryInfo recycleBinDirectory = new DirectoryInfo(locationProject.GetFolderPath(CitaviFolder.RecycleBin));
                    string        deletedFilePath     = Path2.GetUniqueFilePath(recycleBinDirectory, fileMoveOperation.OriginalFileName);
                    File.Move(fileMoveOperation.SourcePath, deletedFilePath);

                    fileMoveOperation.DeleteSuccess = true;
                }
                catch (Exception exception)
                {
                    fileMoveOperation.Errors.Add(exception);
                    fileMoveOperation.DeleteSuccess = false;
                }
            }
        }

        #endregion Delete the original locations and move the files in the CitaviFiles folder to CitaviFiles\RecycleBin



        MessageBox.Show("Macro has finished execution.", "Citavi");
    }
    public static void Main()
    {
        //REQUIRES Citavi 4

        //reference to the active project and the main window
        System.Windows.Forms.Form primaryMainForm = Program.ActiveProjectShell.PrimaryMainForm;
        if (primaryMainForm == null)
        {
            return;
        }

        SwissAcademic.Citavi.Project activeProject = Program.ActiveProjectShell.Project;
        if (activeProject == null)
        {
            return;
        }

        string projectCitaviFilesFolderPath = activeProject.Engine.EngineInfo.GetFolderPath(CitaviFolder.CitaviFiles, activeProject);
        string compareFolderPath            = string.Empty;

        compareFolderPath = projectCitaviFilesFolderPath;
        //if you want to check files and their links to the current Citavi project from a different folder, use something like:
        //compareFolderPath = @"D:\MyFiles";


        var references     = activeProject.References.ToArray();
        var knowledgeItems = activeProject.AllKnowledgeItems.ToArray();



        List <string> pathsToFilesToCompare           = new List <string>();
        List <string> pathsToLinkedFiles              = new List <string>();
        List <string> pathsToLinkedFilesWithDeadLinks = new List <string>();

        string[] filePaths = Directory.GetFiles(compareFolderPath);
        pathsToFilesToCompare.AddRange(filePaths);
        if (pathsToFilesToCompare.Count == 0)
        {
            return;
        }


        //path to the current project's folder

        string activeProjectFolderPath = Path.GetDirectoryName(activeProject.ProjectInfo.FilePath);
        //MessageBox.Show(activeProjectFolderPath);

        //path to the current project's CitaviFiles folder
        string citaviFilesPath = activeProject.GetFolderPath(CitaviFolder.CitaviFiles);

        //MessageBox.Show(citaviFilesPath);

        //iterate through all electronic location files
        foreach (Reference reference in references)
        {
            foreach (Location location in reference.Locations)
            {
                if (location.LocationType != LocationType.ElectronicAddress)
                {
                    continue;
                }

                if (location.AddressUri.AddressInfo == ElectronicAddressInfo.CitaviFiles)
                {
                    string path = Path.Combine(citaviFilesPath, location.Address);
                    pathsToLinkedFiles.Add(path);
                    //MessageBox.Show("CitaviFiles:\r\n" + path);

                    if (!File.Exists(path))
                    {
                        pathsToLinkedFilesWithDeadLinks.Add(path);
                    }

                    continue;
                }
                else if (location.AddressUri.AddressInfo == ElectronicAddressInfo.RelativeFileUri)
                {
                    string path = location.AddressUri.AbsoluteUri.LocalPath;
                    pathsToLinkedFiles.Add(path);
                    //MessageBox.Show("RelativeFileUri:\r\n" + path);

                    if (!File.Exists(path))
                    {
                        pathsToLinkedFilesWithDeadLinks.Add(path);
                    }

                    continue;
                }
                else if (location.AddressUri.AddressInfo == ElectronicAddressInfo.AbsoluteFileUri)
                {
                    string path = location.Address;
                    pathsToLinkedFiles.Add(path);
                    //MessageBox.Show("AbsoluteFileUri:\r\n" + path);

                    if (!File.Exists(path))
                    {
                        pathsToLinkedFilesWithDeadLinks.Add(path);
                    }

                    continue;
                }

                //all others: not applicable
            }
        }



        //iterate through all knowledge item files
        foreach (KnowledgeItem knowledgeItem in knowledgeItems)
        {
            if (knowledgeItem.KnowledgeItemType != KnowledgeItemType.File)
            {
                continue;
            }

            if (knowledgeItem.AddressUri.AddressInfo == ElectronicAddressInfo.CitaviFiles)
            {
                string path = Path.Combine(citaviFilesPath, knowledgeItem.Address);
                pathsToLinkedFiles.Add(path);
                //MessageBox.Show("CitaviFiles:\r\n" + path);

                if (!File.Exists(path))
                {
                    pathsToLinkedFilesWithDeadLinks.Add(path);
                }

                continue;
            }
            else if (knowledgeItem.AddressUri.AddressInfo == ElectronicAddressInfo.RelativeFileUri)
            {
                string path = knowledgeItem.AddressUri.AbsoluteUri.LocalPath;
                pathsToLinkedFiles.Add(path);
                //MessageBox.Show("RelativeFileUri:\r\n" + path);

                if (!File.Exists(path))
                {
                    pathsToLinkedFilesWithDeadLinks.Add(path);
                }

                continue;
            }
            else if (knowledgeItem.AddressUri.AddressInfo == ElectronicAddressInfo.AbsoluteFileUri)
            {
                string path = knowledgeItem.Address;
                pathsToLinkedFiles.Add(path);
                //MessageBox.Show("AbsoluteFileUri:\r\n" + path);

                if (!File.Exists(path))
                {
                    pathsToLinkedFilesWithDeadLinks.Add(path);
                }

                continue;
            }
        }



        //sort the lists
        pathsToLinkedFiles.Sort();
        pathsToFilesToCompare.Sort();

        //make them unique
        pathsToLinkedFiles = pathsToLinkedFiles.Distinct().ToList();
        //pathsToFilesToCompare = pathsToFilesToCompare.Distinct().ToList(); unnecessary

        //generate list of differences between the two lists
        List <string> pathsToFilesNOTLinked = new List <string>();
        List <string> pathsToFilesLinked    = new List <string>();
        bool          found;

        foreach (string path in pathsToFilesToCompare)
        {
            found = false;

            foreach (string pathToFileLinked in pathsToLinkedFiles)
            {
                if (path.Equals(pathToFileLinked, StringComparison.OrdinalIgnoreCase))
                {
                    found = true;
                    break;
                }
            }

            if (!found)
            {
                pathsToFilesNOTLinked.Add(path);
            }
            else
            {
                pathsToFilesLinked.Add(path);
            }
        }

        string logPathsToLinkedFiles = Path.Combine(activeProjectFolderPath, "ALL_Files_LINKED_From_Project.txt");

        using (System.IO.StreamWriter file = new System.IO.StreamWriter(logPathsToLinkedFiles))
        {
            foreach (string path in pathsToLinkedFiles)
            {
                file.WriteLine(path);
            }
        }


        string logPathsToLinkedFilesWithDeadLinks = Path.Combine(activeProjectFolderPath, "ALL_Files_LINKED_From_Project_with_DEAD_Links.txt");

        using (System.IO.StreamWriter file = new System.IO.StreamWriter(logPathsToLinkedFilesWithDeadLinks))
        {
            foreach (string path in pathsToLinkedFilesWithDeadLinks)
            {
                file.WriteLine(path);
            }
        }



        string logPathsToFilesToCompare = Path.Combine(activeProjectFolderPath, "Particular_Files_Checked_For_Link_From_Project.txt");

        using (System.IO.StreamWriter file = new System.IO.StreamWriter(logPathsToFilesToCompare))
        {
            foreach (string path in pathsToFilesToCompare)
            {
                file.WriteLine(path);
            }
        }


        string logPathsToFilesLinked = Path.Combine(activeProjectFolderPath, "Particular_Files_LINKED_From_Project.txt");

        using (System.IO.StreamWriter file = new System.IO.StreamWriter(logPathsToFilesLinked))
        {
            foreach (string path in pathsToFilesLinked)
            {
                file.WriteLine(path);
            }
        }


        string logPathsToFilesNOTLinked = Path.Combine(activeProjectFolderPath, "Particular_Files_NOT_LINKED_From_Project.txt");

        using (System.IO.StreamWriter file = new System.IO.StreamWriter(logPathsToFilesNOTLinked))
        {
            foreach (string path in pathsToFilesNOTLinked)
            {
                file.WriteLine(path);
            }
        }



        var message2 = "Macro has finished execution.\r\nThe following files were created in your project's folder:\r\n\r\n";

        message2 += "ALL_Files_LINKED_From_Project.txt\r\n";
        message2 += "ALL_Files_LINKED_From_Project_with_DEAD_Links.txt\r\n";
        message2 += "Particular_Files_Checked_For_Link_From_Project.txt\r\n";
        message2 += "Particular_Files_LINKED_From_Project.txt\r\n";
        message2 += "Particular_Files_NOT_LINKED_From_Project.txt\r\n";
        message2 += "\r\nDo you want to open the project folder to inspect these files?";

        if (MessageBox.Show(message2, "Citavi", MessageBoxButtons.YesNo, MessageBoxIcon.Information, MessageBoxDefaultButton.Button1) == DialogResult.Yes)
        {
            System.Diagnostics.Process.Start("explorer.exe", string.Format("/select,\"{0}\"", logPathsToFilesNOTLinked));
        }
    }
Exemplo n.º 3
0
    public static void Main()
    {
        //This macro iterates through all linked PDF files and checks for a DOI inside the file.
        //If the reference that the file is linked to does not have a DOI already, it is added to the record.

        if (!Program.ProjectShells.Any())
        {
            return;                                                     //no project open
        }
        if (IsBackupAvailable() == false)
        {
            return;                                                     //user wants to backup his/her project first
        }
        int counter = 0;

        try
        {
            SwissAcademic.Citavi.Project activeProject = Program.ActiveProjectShell.Project;
            string citaviFilesPath = activeProject.GetFolderPath(CitaviFolder.CitaviFiles);


            var fileLocations = activeProject.AllLocations.Where(location =>
                                                                 location.LocationType == LocationType.ElectronicAddress &&
                                                                 (
                                                                     location.AddressUri.AddressInfo == ElectronicAddressInfo.CitaviFiles ||
                                                                     location.AddressUri.AddressInfo == ElectronicAddressInfo.AbsoluteFileUri ||
                                                                     location.AddressUri.AddressInfo == ElectronicAddressInfo.RelativeFileUri
                                                                 )
                                                                 ).ToList();


            var supporter = new ReferenceIdentifierSupport();


            foreach (Location location in fileLocations)
            {
                if (location.Reference == null)
                {
                    continue;
                }
                if (!string.IsNullOrEmpty(location.Reference.Doi))
                {
                    continue;                                                                //if DOI is already available, we do not scan the PDF
                }
                string path = string.Empty;
                switch (location.AddressUri.AddressInfo)
                {
                case ElectronicAddressInfo.CitaviFiles:
                    path = Path.Combine(citaviFilesPath, location.Address);
                    //DebugMacro.WriteLine("CitaviFiles: " + path);
                    break;

                case ElectronicAddressInfo.RelativeFileUri:
                    path = location.AddressUri.AbsoluteUri.LocalPath;
                    //DebugMacro.WriteLine("RelativeFileUri: " + path);
                    break;

                case ElectronicAddressInfo.AbsoluteFileUri:
                    path = location.Address;
                    //DebugMacro.WriteLine("AbsoluteFileUri: " + path);
                    break;

                default:
                    continue;
                }

                if (string.IsNullOrEmpty(path))
                {
                    continue;
                }
                if (!File.Exists(path))
                {
                    continue;
                }
                if (!Path.GetExtension(path).Equals(".pdf", StringComparison.OrdinalIgnoreCase))
                {
                    continue;
                }

                var matches = supporter.FindIdentifierInFile(path, ReferenceIdentifierType.Doi, false);
                if (matches.Count == 0)
                {
                    continue;
                }
                var match = matches.ElementAt(0);

                if (string.IsNullOrEmpty(location.Reference.Doi))
                {
                    //DebugMacro.WriteLine(match.ToString());
                    location.Reference.Doi = match.ToString();
                    counter++;
                }
            }
        }         //end try

        finally
        {
            MessageBox.Show(string.Format("Macro has finished execution.\r\n{0} changes were made.", counter.ToString()), "Citavi", MessageBoxButtons.OK, MessageBoxIcon.Information);
        } //end finally
    }     //end main()