public static void Main()
    {
        List <Reference> references = Program.ActiveProjectShell.PrimaryMainForm.GetFilteredReferences();

        //if we need a ref to the active project
        SwissAcademic.Citavi.Project activeProject = Program.ActiveProjectShell.Project;

        foreach (Reference reference in references)
        {
            if (reference.Authors.Count == 3)
            {
                // just to be sure, regenerate BibTeX key...
                reference.GenerateBibTeXKey();

                Person thirdAuthor = reference.Authors[2];

                // check if the third lastname has more than one character...
                if ((thirdAuthor.LastName.Length > 1) && (thirdAuthor.LastName.Substring(1, 1) != "."))
                {
                    // now fix BibTeXKey
                    reference.BibTeXKey = reference.BibTeXKey.Insert(3, thirdAuthor.LastName.Substring(1, 1));
                }
            }
        }
    }
    public static void Main()
    {
        //if we need a ref to the active project
        SwissAcademic.Citavi.Project activeProject = Program.ActiveProjectShell.Project;

        Keyword[] cs = activeProject.Keywords.ToArray();
        Array.Sort(cs, new KeywordWithReferencesComparer());

        foreach (Keyword c in cs)
        {
            DebugMacro.WriteLine(c.FullName + "\t" + c.References.Count);
        }
    }
    public static void Main()
    {
        if (Program.ActiveProjectShell == null)
        {
            return;
        }

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

        Person[] ps = activeProject.Persons.ToArray();
        //Array.Sort(ps, new PersonComparerAlphabetic());
        Array.Sort(ps, new PersonComparerReferencesCount());

        foreach (Person p in ps)
        {
            DebugMacro.WriteLine(p.FullName + "\t" + p.References.Count);
        }
    }
Ejemplo n.º 4
0
    public static void Main()
    {
        if (Program.ProjectShells.Count == 0)
        {
            return;                                                     //no project open
        }
        if (IsBackupAvailable() == false)
        {
            return;                                                             //user wants to backup his/her project first
        }
        int counter = 0;

        try
        {
            string sourcePath;

            FolderBrowserDialog folderDialog = new FolderBrowserDialog();
            folderDialog.Description = "Select a root folder for the PDF files to be imported ...";
            DialogResult folderResult = folderDialog.ShowDialog();
            if (folderResult == DialogResult.OK)
            {
                sourcePath = folderDialog.SelectedPath;
            }
            else
            {
                return;
            }

            AttachmentAction action = AttachmentAction.Link;             //suggested: .Link or .Copy

            DirectoryInfo   dir       = new DirectoryInfo(sourcePath);
            List <FileInfo> fileInfos = Path2.GetFilesSafe(dir, "*.pdf", SearchOption.AllDirectories).ToList();

            List <Reference>             newReferences = new List <Reference>();
            SwissAcademic.Citavi.Project activeProject = Program.ActiveProjectShell.Project;

            List <string> filePaths = fileInfos.Select <FileInfo, string>(info => info.FullName).ToList();
            foreach (string filePath in filePaths)
            {
                DebugMacro.WriteLine("START IMPORT: " + filePath);
                List <Reference> referencesFromFile = new FileImportSupport().ImportFiles(activeProject, activeProject.Engine.TransformerManager, new List <string>()
                {
                    filePath
                }, action);

                if (referencesFromFile != null && referencesFromFile.Any())
                {
                    var referencesFromFileAdded = activeProject.References.AddRange(referencesFromFile);

                    var fileName = Path.GetFileName(filePath);
                    AddCategories(referencesFromFileAdded, filePath.Substring(sourcePath.Length, filePath.Length - sourcePath.Length - fileName.Length));
                    DebugMacro.WriteLine("SUCCESS");
                    counter++;
                }
                else
                {
                    DebugMacro.WriteLine("ERROR importing file");
                }
            }
        }         //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()
Ejemplo n.º 5
0
    public static void Main()
    {
        char splitter = ',';            //if you have any other separating character, like '|' or '/' you can adjust this here



        if (!Program.ProjectShells.Any())
        {
            return;                                                     //no project open
        }
        if (IsBackupAvailable() == false)
        {
            return;                                                     //user wants to backup his/her project first
        }
        SwissAcademic.Citavi.Project activeProject = Program.ActiveProjectShell.Project;

        //collect all keywords to be separated
        List <Keyword> keywordsToBeSplit = new List <Keyword>();

        foreach (Keyword keyword in activeProject.Keywords)
        {
            if (keyword.Name.Contains(splitter))
            {
                keywordsToBeSplit.Add(keyword);
            }
        }

        if (keywordsToBeSplit.Count == 0)
        {
            MessageBox.Show("No keywords to be split.");
            return;
        }


        foreach (Keyword keyword in keywordsToBeSplit)
        {
            //get references and knowledge items that need to be "tagged" with the "fractions"
            List <Reference> referencesToBeTagged = new List <Reference>();
            foreach (Reference reference in keyword.References)
            {
                referencesToBeTagged.Add(reference);
            }

            List <KnowledgeItem> knowledgeItemsToBeTagged = new List <KnowledgeItem>();
            foreach (KnowledgeItem knowledgeItem in keyword.KnowledgeItems)
            {
                knowledgeItemsToBeTagged.Add(knowledgeItem);
            }


            List <string>  keywordStringFragments = keyword.Name.Split(new char[] { splitter }, StringSplitOptions.RemoveEmptyEntries).ToList();
            List <Keyword> fragmentKeywords       = new List <Keyword>();
            //make sure the fragment strings exist as keywords
            foreach (string keywordStringFragment in keywordStringFragments)
            {
                fragmentKeywords.Add(activeProject.Keywords.Add(keywordStringFragment.Trim()));
            }


            //assign keyword fragment to reference-to-be-tagged
            foreach (Reference reference in referencesToBeTagged)
            {
                reference.Keywords.AddRange(fragmentKeywords);
            }


            //assign keyword fragment to knowledge-item-to-be-tagged
            foreach (KnowledgeItem knowledgeItem in knowledgeItemsToBeTagged)
            {
                knowledgeItem.Keywords.AddRange(fragmentKeywords);
            }
        }

        //finally we could delete the old "mega-keywords"
        activeProject.Keywords.RemoveRange(keywordsToBeSplit);

        MessageBox.Show("Done");
    }
Ejemplo n.º 6
0
    //This macro replaces all occurences of a British date "dd/mm/yyyy" by its ISO date equivalent "yyyy-MM-dd"
    //inside the reference fields "Year", "Date", "Date2" and "AccessDate"
    public static void Main()
    {
        string targetDateFormat = "{2}-{1}-{0}";                //{0}=day, {1}=month, {2}=year

        //US American:  "{1}/{0}/{2}"
        //German:       "{0}.{1}.{2}"
        //ISO:          "{2}-{1}-{0}

        if (Program.ProjectShells.Count == 0)
        {
            return;                                             //no project open
        }
        if (IsBackupAvailable() == false)
        {
            return;                                                     //user wants to backup his/her project first
        }
        SwissAcademic.Citavi.Project activeProject = Program.ActiveProjectShell.Project;
        if (activeProject == null)
        {
            return;
        }

        List <Reference> references = Program.ActiveProjectShell.Project.References.ToList();

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

        if (references == null || !references.Any())
        {
            return;
        }

        List <ReferencePropertyDescriptor> dateProperties = new List <ReferencePropertyDescriptor>()
        {
            ReferencePropertyDescriptor.Date,
            ReferencePropertyDescriptor.Date2,
            ReferencePropertyDescriptor.AccessDate,
            ReferencePropertyDescriptor.Year
        };

        Regex britishDateRegex = new Regex(@"(?<fulldate>(?<day>\d\d{1,2})/(?<month>\d\d{1,2})/(?<year>\d\d\d\d))");
        int   hitCounter       = 0;

        foreach (Reference reference in references)
        {
            foreach (ReferencePropertyDescriptor dateProperty in dateProperties)
            {
                string input = reference.GetValue(dateProperty.PropertyId) as string;
                if (string.IsNullOrEmpty(input))
                {
                    continue;
                }

                MatchCollection matches = britishDateRegex.Matches(input);
                if (matches == null || matches.Count == 0)
                {
                    continue;
                }


                foreach (Match match in matches)
                {
                    hitCounter++;
                    string britishDate = match.Groups["fulldate"].Value;
                    string year        = match.Groups["year"].Value;
                    string month       = match.Groups["month"].Value;
                    string day         = match.Groups["day"].Value;

                    string targetDate = string.Format(targetDateFormat, month, day, year);
                    string isoDate    =
                        input = Regex.Replace(input, britishDate, targetDate);

                    //DebugMacro.WriteLine("Input: {0}\tRecognized Year: {1}\tRecognized Month: {2}\tRecognized Day: {3}\tAmerican Date: {4}", input, year, month, day, targetDate);
                }

                reference.SetValue(dateProperty.PropertyId, input);
            }
        }

        MessageBox.Show(string.Format("Finished.\r\n\r\n{0} dates were converted from British to US date format.", hitCounter));
    }
    public static void Main()
    {
        //REQUIRES Citavi 5

        //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.Addresses.AttachmentsFolderPath;

        //MessageBox.Show(projectCitaviFilesFolderPath);

        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;
        }


        //C5 save to desktop unless SQLite project
        string activeProjectFolderPath = String.Empty;

        if (activeProject.DesktopProjectConfiguration.ProjectType == ProjectType.DesktopSQLite)
        {
            string activeProjectFilePath = activeProject.DesktopProjectConfiguration.SQLiteProjectInfo.FilePath;
            activeProjectFolderPath = Path.GetDirectoryName(activeProjectFilePath);
        }
        else
        {
            activeProjectFolderPath = Environment.GetFolderPath(Environment.SpecialFolder.Desktop) + @"\" + activeProject.Name;
            if (!Directory.Exists(activeProjectFolderPath))
            {
                Directory.CreateDirectory(activeProjectFolderPath);
            }
        }


        //MessageBox.Show(activeProjectFolderPath);

        //C5: Attachments path
        string citaviFilesPath = activeProject.Addresses.AttachmentsFolderPath;

        //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.Attachment)
                {
                    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.Attachment)
            {
                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));
        }
    }
Ejemplo n.º 8
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()
Ejemplo n.º 9
0
    //SetAllFilesPreviewBehaviourToSkipEntryPage 1.1
    public static void Main()
    {
        if (Program.ProjectShells.Count == 0)
        {
            return;                                                     //no project open
        }
        if (IsBackupAvailable() == false)
        {
            return;                                                             //user wants to backup his/her project first
        }
        int counter = 0;

        try
        {
            List <Reference>             references    = Program.ActiveProjectShell.PrimaryMainForm.GetFilteredReferences();
            SwissAcademic.Citavi.Project activeProject = Program.ActiveProjectShell.Project;

            List <Location> filesToShowImmediately = new List <Location>();

            foreach (Reference reference in references)
            {
                foreach (Location location in reference.Locations)
                {
                    //first we collect all files that are not set to be shown immediately yet
                    if (location.LocationType == LocationType.ElectronicAddress)
                    {
                        switch (location.AddressUri.AddressInfo)
                        {
                        case ElectronicAddressInfo.RemoteUri:
                        case ElectronicAddressInfo.AbsoluteFileUri:
                        case ElectronicAddressInfo.RelativeFileUri:
                        case ElectronicAddressInfo.CitaviFiles:
                        {
                            //MessageBox.Show(string.Format("Location:{0}\n\rPreview Behaviour:{1}\n\rLocal Path:{2}", location.ToString(), location.PreviewBehaviour.ToString(), location.AddressUri.AbsoluteUri.LocalPath.ToString()));
                            if (location.PreviewBehaviour != PreviewBehaviour.SkipEntryPage)
                            {
                                filesToShowImmediately.Add(location);
                            }
                            //if(location.AddressUri.AbsoluteUri.LocalPath == DriveType.Network) filesToShowImmediately.Add(location);
                        }
                        break;
                        }
                    }
                }
            }


            //now we change the PreviewBehaviour on all the collected files
            foreach (Location location in filesToShowImmediately)
            {
                if (location.PreviewBehaviour != PreviewBehaviour.SkipEntryPage)
                {
                    location.PreviewBehaviour = PreviewBehaviour.SkipEntryPage;
                    counter++;
                }
            }

            activeProject.Save(TrackPriority.Immediate);
        }         //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()
    public static void Main()
    {
        if (Program.ProjectShells.Count == 0)
        {
            return;                                                     //no project open
        }
        if (IsBackupAvailable() == false)
        {
            return;                                                             //user wants to backup his/her project first
        }
        int counter = 0;

        try
        {
            CommonParagraphAttributes paragraphFormat = new CommonParagraphAttributes();
            //*******************************************************************************************************************//
            //NOTE: YOU CAN ADAPT THE FOLLOWING ACCORDING TO YOUR NEEDS:

            //------------------ FONT -------------------------------------------------------------------------------------------//
            string fontName = "Segoe UI";                                       //NOTE: Name der Schriftart
            int    fontSize = 9;                                                //NOTE: Groesse in Punkt
            //-------------------------------------------------------------------------------------------------------------------//

            //------------------ PARAGRAPH ALIGNMENT ----------------------------------------------------------------------------//
            paragraphFormat.Alignment = Alignment.Left;                         //NOTE: Linksbuending

            //NOTE: OR:
            //paragraphFormat.Alignment = Alignment.Justify;		//NOTE: Blocksatz

            //NOTE: OR:
            //paragraphFormat.Alignment = Alignment.Center;		//NOTE: Zentriert

            //NOTE: OR:
            //paragraphFormat.Alignment = Alignment.Right;		//NOTE: Rechtsbuendig
            //-------------------------------------------------------------------------------------------------------------------//


            //------------------ LINE SPACING WITHIN PARAGRAPH ------------------------------------------------------------------//
            paragraphFormat.Spacing.LineSpacingType = LineSpacingType.One;              //NOTE: Einzeilig

            //NOTE: OR:
            //paragraphFormat.Spacing.LineSpacingType = LineSpacingType.OneAndHalf;		//NOTE: Anderthalbzeilig

            //NOTE: OR:
            //paragraphFormat.Spacing.LineSpacingType = LineSpacingType.Double;		//NOTE: Zweizeilig

            //NOTE: OR:
            //paragraphFormat.Spacing.LineSpacingType = LineSpacingType.Multiple;	//NOTE: Mehrfach
            //float n = 3F;         //NOTE: for threefold, always with F at the end !
            //paragraphFormat.Spacing.Line = Convert.ToInt32((n * 100F) - 100F);

            //NOTE: OR:
            //paragraphFormat.Spacing.LineSpacingType = LineSpacingType.Precise;	//NOTE: Exakt (in Punkt)
            //float pt = 12.5F;     //NOTE: in points, always with F at the end, do NOT change following line
            //paragraphFormat.Spacing.Line = Convert.ToInt32(MeasurementUnit.Points.ConvertValue(pt, MeasurementUnitType.Twips));

            //NOTE: OR:
            //paragraphFormat.Spacing.LineSpacingType = LineSpacingType.Minimum;	//NOTE: Mindestens (in Punkt)
            //float pt = 12.5F;     //NOTE: in points, always with F at the end, do NOT change the following line
            //paragraphFormat.Spacing.Line = Convert.ToInt32(MeasurementUnit.Points.ConvertValue(pt, MeasurementUnitType.Twips));
            //-------------------------------------------------------------------------------------------------------------------//


            //------------------ SPACING AFTER/BEFORE PARAGRAPH -----------------------------------------------------------------//
            float ptAfter = 6F;             //NOTE: in points, always with F at the end, do NOT change the following line
            paragraphFormat.Spacing.After = Convert.ToInt32(MeasurementUnit.Points.ConvertValue(ptAfter, MeasurementUnitType.Twips));

            //NOTE: AND/OR:
            //float ptBefore = 12F; //NOTE: in points, always with F at the end, do NOT change the following line
            //paragraphFormat.Spacing.Before = Convert.ToInt32(MeasurementUnit.Points.ConvertValue(ptBefore, MeasurementUnitType.Twips));
            //-------------------------------------------------------------------------------------------------------------------//


            //------------------ INDENTATION OF PARAGRAPH -----------------------------------------------------------------------//
            //NOTE: RESET - DO NOT REMOVE THE FOLLOWING LINES - THEY MUST ALWAYS BE APPLIED OTHERWISE YOU END UP WITH A WILD MIX
            paragraphFormat.Indentation.Left      = 0;
            paragraphFormat.Indentation.Right     = 0;
            paragraphFormat.Indentation.FirstLine = 0;

            //NOTE: LEFT
            //float cmLeft = 0F;            //NOTE: in cm, always with F at the end, do NOT edit the following lines, just remove comments
            //paragraphFormat.Indentation.Left = Convert.ToInt32(MeasurementUnit.Centimeters.ConvertValue(cmLeft, MeasurementUnitType.Twips));

            //NOTE: RIGHT
            //float cmRight = 0F;       //NOTE: in cm, always with F at the end, do NOT edit the following lines, just remove comments
            //paragraphFormat.Indentation.Right = Convert.ToInt32(MeasurementUnit.Centimeters.ConvertValue(cmRight, MeasurementUnitType.Twips));

            //NOTE: FIRSTLINE
            //float cmFirstLine = 1F;   //NOTE: in cm, always with F at the end, do NOT edit the following lines, just remove comments
            //paragraphFormat.Indentation.IndentationType = IndentationType.FirstLine;
            //paragraphFormat.Indentation.FirstLine = Convert.ToInt32(MeasurementUnit.Centimeters.ConvertValue(cmFirstLine, MeasurementUnitType.Twips));

            //NOTE: OR: HANGING
            //float cmHanging = 1F;     //NOTE: in cm, always with F at the end, do NOT edit the following lines, just remove comments
            //paragraphFormat.Indentation.IndentationType = IndentationType.Hanging;
            //paragraphFormat.Indentation.FirstLine = Convert.ToInt32(MeasurementUnit.Centimeters.ConvertValue(cmHanging, MeasurementUnitType.Twips));
            //-------------------------------------------------------------------------------------------------------------------//

            //*******************************************************************************************************************//
            //NOTE: DO NOT CHANGE ANYTHING BELOW THIS LINE


            //KnowledgeItem[] knowledgeItems = Program.ActiveProjectShell.Project.AllKnowledgeItems.ToArray();


            //reference to active project shell
            SwissAcademic.Citavi.Shell.ProjectShell activeShell = Program.ActiveProjectShell;

            //reference to active project
            SwissAcademic.Citavi.Project activeProject = activeShell.Project;

            //reference to primary main form
            SwissAcademic.Citavi.Shell.MainForm mainForm = activeShell.PrimaryMainForm;

            var references = mainForm.GetFilteredReferences();
            List <KnowledgeItem> knowledgeItemList = new List <KnowledgeItem>();
            foreach (Reference reference in references)
            {
                knowledgeItemList.AddRange(reference.Quotations);
            }
            KnowledgeItem[] knowledgeItems = knowledgeItemList.ToArray();

            object tag = null;
            foreach (KnowledgeItem knowledgeItem in knowledgeItems)
            {
                if (string.IsNullOrEmpty(knowledgeItem.Text))
                {
                    continue;
                }
                if (knowledgeItem.KnowledgeItemType != KnowledgeItemType.Text)
                {
                    continue;
                }

                counter++;

                //first we instantiate a new RTF Form ...
                //SwissAcademic.Citavi.Shell.RtfForm rtfForm = activeShell.ShowAbstractForm(reference);
                SwissAcademic.Citavi.Shell.ProjectShellForm rtfForm = activeShell.ShowKnowledgeItemFormForExistingItem(mainForm, knowledgeItem);

                //rtfForm.PerformCommand("FormatRemoveReturnsAndTabs", tag);


                //... then via reflection we get a reference to the WordProcessorControl therein ...
                Type t = rtfForm.GetType();

                FieldInfo fieldInfo = t.GetField("wordProcessor", BindingFlags.Instance | BindingFlags.NonPublic);
                if (fieldInfo == null)
                {
                    continue;
                }

                WordProcessorControl wordProcessor = (WordProcessorControl)fieldInfo.GetValue(rtfForm);
                if (wordProcessor == null)
                {
                    continue;
                }

                //... and do the formatting:
                wordProcessor.SelectAll();
                if (!string.IsNullOrEmpty(fontName))
                {
                    wordProcessor.Selection.FontName = fontName;
                }
                if (fontSize != 0)
                {
                    wordProcessor.Selection.FontSize = Convert.ToInt32(SwissAcademic.MeasurementUnit.Points.ConvertValue(fontSize, SwissAcademic.MeasurementUnitType.Twips));
                }
                wordProcessor.Selection.SetCommonParagraphAttributes(paragraphFormat);

                rtfForm.PerformCommand("Save", tag);
                rtfForm.Close();
            }
        }         //end try

        catch (Exception exception)
        {
            MessageBox.Show(exception.ToString());
        }

        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()
Ejemplo n.º 11
0
        public static void ChangeShorthands()
        {
            bool handled;

            List <Reference> references = new List <Reference>();

            SwissAcademic.Citavi.Project activeProject = Program.ActiveProjectShell.Project;

            List <Reference> activeProjectReferencesList = new List <Reference>();

            // We copy the active project references in a list so that the changes don't affect the order of the list we later loop through

            foreach (Reference reference in activeProject.References)
            {
                if (reference.ReferenceType != ReferenceType.CourtDecision)
                {
                    continue;
                }
                activeProjectReferencesList.Add(reference);
            }

            // Select the references to be renamed

            DialogResult dialogResult = MessageBox.Show("Do you want to modify the value of the short title (citation key) field of the selected references (including their parallel reporters)?",
                                                        "Change Short Title (Citation Key)", MessageBoxButtons.OKCancel);

            if (dialogResult == DialogResult.OK)
            {
                List <Reference> selectedReferences = Program.ActiveProjectShell.PrimaryMainForm.GetSelectedReferences();
                foreach (Reference reference in selectedReferences)
                {
                    references.Add(reference);
                }
            }
            else if (dialogResult == DialogResult.Cancel)
            {
                return;
            }

            string shortTitleString;
            int    i = 0;

            List <Reference> dateChangedList = new List <Reference>();

            List <string> shortTitlesList = new List <string>();

            foreach (Reference currentReference in references)
            {
                string data;
                string ret = ReferenceForms.NewCitationKeyForm("Please enter the new citation key:", out data);

                shortTitleString                       = currentReference.ShortTitle.ToStringSafe();
                currentReference.CitationKey           = ret;
                currentReference.CitationKeyUpdateType = UpdateType.Manual;
                i = i + 1;
                shortTitlesList.Add(shortTitleString);
                dateChangedList.Add(currentReference);

                string Date = currentReference.Date;

                foreach (Reference reference in activeProjectReferencesList)
                {
                    if (reference == currentReference)
                    {
                        continue;
                    }

                    if (reference.Periodical == null)
                    {
                        continue;
                    }
                    if (!currentReference.Organizations.SequenceEqual(reference.Organizations))
                    {
                        continue;
                    }
                    if (currentReference.Title != reference.Title)
                    {
                        continue;
                    }
                    if (String.IsNullOrEmpty(currentReference.Title) && (String.IsNullOrEmpty(currentReference.SpecificField2) || currentReference.SpecificField2 != reference.SpecificField2))
                    {
                        continue;
                    }
                    shortTitleString = reference.ShortTitle.ToStringSafe();
                    shortTitlesList.Add(shortTitleString);
                    reference.CitationKey           = ret;
                    reference.CitationKeyUpdateType = UpdateType.Manual;
                    dateChangedList.Add(reference);
                    i = i + 1;
                    continue;
                }
            }
            DialogResult showFailed = MessageBox.Show(i.ToStringSafe() +
                                                      " references have been changed:\n   •" +
                                                      String.Join("\n   • ", shortTitlesList) +
                                                      "\nWould you like to show a selection of references where the short title (citation key) has been adjusted?",
                                                      "Citavi Macro", MessageBoxButtons.YesNo, MessageBoxIcon.Information);

            if (showFailed == DialogResult.Yes)
            {
                var filter = new ReferenceFilter(dateChangedList, "Date changed", false);
                Program.ActiveProjectShell.PrimaryMainForm.ReferenceEditorFilterSet.Filters.ReplaceBy(new List <ReferenceFilter> {
                    filter
                });
            }
        }
    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");
    }
Ejemplo n.º 13
0
    public static void Main()
    {
        //Private Sammlung > Bibliothek
        bool removePrivateCollectionLocation = true;         //will remove the location information in a private collection after adding it as a library location

        if (IsBackupAvailable() == false)
        {
            return;
        }
        if (Program.ActiveProjectShell == null)
        {
            return;
        }
        if (Program.ActiveProjectShell.PrimaryMainForm == null)
        {
            return;
        }

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

        if (references == null || !references.Any())
        {
            MessageBox.Show("Please filter for references whose locations in private collection should be transformed into library locations");
            return;
        }

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

        int referenceCounter = 0;
        int locationCounter  = 0;

        //List<Reference> selectedReferences = Program.ActiveProjectShell.Refer
        foreach (Reference reference in references)
        {
            List <Location> referenceLocations = reference.Locations.ToList();
            if (referenceLocations == null || !referenceLocations.Any())
            {
                continue;
            }

            List <Location> referencePrivateLocations = referenceLocations.Where(item => item.LocationType == LocationType.PrivateCollection).ToList();
            if (referencePrivateLocations == null || !referencePrivateLocations.Any())
            {
                continue;
            }
            referenceCounter++;             //count references that DO have private locations

            foreach (Location l in referencePrivateLocations)
            {
                locationCounter++;                 //count private locations converted into library locations
                string address   = l.Address.ToString();
                string signature = l.CallNumber;
                string note      = l.Notes;


                Library library = activeProject.Libraries.FindKey(address);
                if (library == null)
                {
                    library = activeProject.Libraries.Add(address);
                }

                Location newLocation = reference.Locations.Add(library, signature);
                newLocation.Notes = note;

                if (removePrivateCollectionLocation)
                {
                    reference.Locations.Remove(l);
                }
            }
        }

        string message = string.Format("Macro finished execution.\r\n\r\nWith {0} reference(s) an overall number of {1} locations in a private collection were converted into library locations.",
                                       referenceCounter.ToString(),
                                       locationCounter.ToString());

        MessageBox.Show(message, "Citavi", MessageBoxButtons.OK);
    }
Ejemplo n.º 14
0
    public static void Main()
    {
        //if we need a ref to the active project
        if (Program.ActiveProjectShell == null)
        {
            return;
        }
        SwissAcademic.Citavi.Project activeProject = Program.ActiveProjectShell.Project;

        if (activeProject == null)
        {
            DebugMacro.WriteLine("No active project.");
            return;
        }

        /*if this macro should ALWAYS affect all titles in active project, choose first option
         * if this macro should affect just filtered rows if there is a filter applied and ALL if not, choose second option
         * if this macro should affect just selected rows, choose third option */

        //ProjectReferenceCollection references = Program.ActiveProjectShell.Project.References;
        //List<Reference> references = Program.ActiveProjectShell.PrimaryMainForm.GetFilteredReferences();
        List <Reference> references = Program.ActiveProjectShell.PrimaryMainForm.GetSelectedReferences();

        if (references == null || !references.Any())
        {
            DebugMacro.WriteLine("No references selected.");
            return;
        }

        int countNotProvisional = 0;
        int countProvisional    = 0;
        int countReferences     = 0;

        foreach (Reference reference in references)
        {
            countReferences = countReferences + 1;

            string budgetCode     = "Budget?";
            string specialistName = "Michael Freiberg";
            string edition        = "p";
            string price          = "? €";
            string taskType       = "?";
            string orderNote      = "-";
            string normalizedISBN = reference.Isbn.Isbn13.ToString();
            string buchhandelURL  = "https://www.buchhandel.de/jsonapi/products?filter[products][query]=(is=" + normalizedISBN + ")";

            // Get availability information of the title from "buchhandel.de"
            try {
                Cursor.Current = Cursors.WaitCursor;

                DebugMacro.WriteLine("Getting availability information from " + buchhandelURL);
                WebClient client = new WebClient();
                client.Headers["Accept"] = "application/vnd.api+json";
                var jsonString = client.DownloadString(buchhandelURL);
                // DebugMacro.WriteLine(jsonString);


                // Get budget code from groups
                List <SwissAcademic.Citavi.Group> refGroups = reference.Groups.ToList();

                foreach (SwissAcademic.Citavi.Group refGroup in refGroups)
                {
                    Match match = Regex.Match(refGroup.Name, @"budget\:\s*(.+)", RegexOptions.IgnoreCase);
                    if (match.Success)
                    {
                        budgetCode = match.Groups[1].Value;
                    }
                }

                // Quick and dirty extraction of price information via RegEx.
                // Parsing of JSON response would be preferred, but I could not handle
                // the concepts of System.Runtime.Serialization and System.Runtime.Serialization.Json;



                // Get first match. Book price in Austria.
                Match matchPrice = Regex.Match(jsonString, @"\""value\""\:(\d+\.\d+)");
                if (matchPrice.Success)
                {
                    var priceAT = matchPrice.Groups[1].Value;
                    // DebugMacro.WriteLine(priceAT);
                }

                // Get second match. Book price in Germany.
                matchPrice = matchPrice.NextMatch();
                if (matchPrice.Success)
                {
                    var priceDE = matchPrice.Groups[1].Value;
                    price = Regex.Replace(priceDE, @"\.", ",") + " €";
                    // DebugMacro.WriteLine(priceDE);
                }

                Match matchAvail = Regex.Match(jsonString, @"\""provisional\""\:true");
                if (matchAvail.Success)
                {
                    reference.Groups.Add("Noch nicht erschienen");
                    countProvisional = countProvisional + 1;
                }
                else
                {
                    countNotProvisional = countNotProvisional + 1;

                    foreach (SwissAcademic.Citavi.Group refGroup in refGroups)
                    {
                        Match match = Regex.Match(refGroup.Name, @"Noch nicht erschienen", RegexOptions.IgnoreCase);
                        if (match.Success)
                        {
                            reference.Groups.Remove(refGroup);
                        }
                    }

                    taskType  = "Bestellen";
                    orderNote = "Verfügbar. " + edition + " " + price;


                    TaskItem order = reference.Tasks.Add(taskType);

                    // Assign specialist.
                    ContactInfo taskAssignee = activeProject.Contacts.GetMembers().FirstOrDefault <ContactInfo>(item => item.FullName.Equals(specialistName));
                    if (taskAssignee == null)
                    {
                        DebugMacro.WriteLine("No such contact.");
                        return;
                    }
                    order.AssignedTo = taskAssignee.Key;

                    order.Notes = orderNote;
                }
            }
            catch (Exception e) {
                Cursor.Current = Cursors.Default;
                DebugMacro.WriteLine("Could not read file from " + buchhandelURL + ": " + e.Message);
                return;
            }
        }

        // Message upon completion
        string message = "{0} Titel wurden geprüft. {1} sind noch nicht erschienen. {2} sind lieferbar.";

        message = string.Format(message, countReferences.ToString(), countProvisional.ToString(), countNotProvisional.ToString());
        MessageBox.Show(message, "Bericht", MessageBoxButtons.OK, MessageBoxIcon.Information);
    }
Ejemplo n.º 15
0
    public static void Main()
    {
        //if this macro should ALWAYS affect all titles in active project, choose first option
        //if this macro should affect just filtered rows if there is a filter applied and ALL if not, choose second option

        //ProjectReferenceCollection references = Program.ActiveProjectShell.Project.References;
        List <Reference> references = Program.ActiveProjectShell.PrimaryMainForm.GetSelectedReferences();

        //if we need a ref to the active project
        SwissAcademic.Citavi.Project activeProject = Program.ActiveProjectShell.Project;


        if (references.Count == 2)
        {
            if (references[0].ReferenceType == references[1].ReferenceType)
            {
                string originalTitle = references[0].Title;

                // CreatedOn, check which one is older and then take that CreatedOn and CreatedBy
                if (DateTime.Compare(references[0].CreatedOn, references[1].CreatedOn) > 0)
                {
                    // second reference is older
                    // CreatedOn is write-protected. We therefore switch the references...
                    Reference newer = references[0];
                    references[0] = references[1];
                    references[1] = newer;
                }

                // ModifiedOn is write-protected. It will be updated anyways now.

                // Abstract, naive approach...
                if (references[0].Abstract.Text.Trim().Length < references[1].Abstract.Text.Trim().Length)
                {
                    references[0].Abstract.Text = references[1].Abstract.Text;
                }

                // AccessDate, take newer one
                //TODO: accessdate would need to be parsed
                // right now, we just check if there is one, we take it, otherwise we leave it empty.
                if (references[0].AccessDate.Length < references[1].AccessDate.Length)
                {
                    references[0].AccessDate = references[1].AccessDate;
                }

                // Additions
                references[0].Additions = MergeOrCombine(references[0].Additions, references[1].Additions);

                // CitationKey, check if CitationKeyUpdateType is 0 at one reference if yes, take that one
                if ((references[0].CitationKeyUpdateType == UpdateType.Automatic) && (references[1].CitationKeyUpdateType == UpdateType.Manual))
                {
                    references[0].CitationKey           = references[1].CitationKey;
                    references[0].CitationKeyUpdateType = references[1].CitationKeyUpdateType;
                }

                // CoverPath
                if (references[0].CoverPath.LinkedResourceType == LinkedResourceType.Empty)
                {
                    references[0].CoverPath = references[1].CoverPath;
                }

                // CustomFields (1-9)
                references[0].CustomField1 = MergeOrCombine(references[0].CustomField1, references[1].CustomField1);
                references[0].CustomField2 = MergeOrCombine(references[0].CustomField2, references[1].CustomField2);
                references[0].CustomField3 = MergeOrCombine(references[0].CustomField3, references[1].CustomField3);
                references[0].CustomField4 = MergeOrCombine(references[0].CustomField4, references[1].CustomField4);
                references[0].CustomField5 = MergeOrCombine(references[0].CustomField5, references[1].CustomField5);
                references[0].CustomField6 = MergeOrCombine(references[0].CustomField6, references[1].CustomField6);
                references[0].CustomField7 = MergeOrCombine(references[0].CustomField7, references[1].CustomField7);
                references[0].CustomField8 = MergeOrCombine(references[0].CustomField8, references[1].CustomField8);
                references[0].CustomField9 = MergeOrCombine(references[0].CustomField9, references[1].CustomField9);

                // Date (string type
                references[0].Date = MergeOrCombine(references[0].Date, references[1].Date);

                // Date2 (string type)
                references[0].Date2 = MergeOrCombine(references[0].Date2, references[1].Date2);

                // DOI
                references[0].Doi = MergeOrCombine(references[0].Doi, references[1].Doi);

                // Edition
                references[0].Edition = MergeOrCombine(references[0].Edition, references[1].Edition);

                // EndPage
                if (references[0].PageRange.ToString() == "")
                {
                    references[0].PageRange = references[1].PageRange;
                }

                // Evaluation, naive approach...
                if (references[0].Evaluation.Text.Trim().Length < references[1].Evaluation.Text.Trim().Length)
                {
                    references[0].Evaluation.Text = references[1].Evaluation.Text;
                }

                // HasLabel1 and HasLabel2
                if (references[1].HasLabel1)
                {
                    references[0].HasLabel1 = references[1].HasLabel1;
                }
                if (references[1].HasLabel2)
                {
                    references[0].HasLabel2 = references[1].HasLabel2;
                }

                // ISBN
                references[0].Isbn = MergeOrCombine(references[0].Isbn.ToString(), references[1].Isbn.ToString());

                // Language
                references[0].Language = MergeOrCombine(references[0].Language, references[1].Language);

                // Notes
                references[0].Notes = MergeOrCombine(references[0].Notes, references[1].Notes);

                // Number
                references[0].Number = MergeOrCombine(references[0].Number, references[1].Number);

                // NumberOfVolumes
                references[0].NumberOfVolumes = MergeOrCombine(references[0].NumberOfVolumes, references[1].NumberOfVolumes);

                // OnlineAddress
                references[0].OnlineAddress = MergeOrCombine(references[0].OnlineAddress, references[1].OnlineAddress);

                // OriginalCheckedBy
                references[0].OriginalCheckedBy = MergeOrCombine(references[0].OriginalCheckedBy, references[1].OriginalCheckedBy);

                // OriginalPublication
                references[0].OriginalPublication = MergeOrCombine(references[0].OriginalPublication, references[1].OriginalPublication);

                // PageCount (text)
                //TODO: apparently it is a calculated field
                // PageCountNumeralSystem (int=0)
                //TODO: apparently it is a calculated field
                // PageRangeNumberingType (int=0)
                //TODO: apparently it is a calculated field
                // PageRangeNumeralSystem (int=0)
                //TODO: apparently it is a calculated field

                // ParallelTitle
                references[0].ParallelTitle = MergeOrCombine(references[0].ParallelTitle, references[1].ParallelTitle);

                // PeriodicalID, naive approach...
                if ((references[0].Periodical == null) || (((references[0].Periodical != null) && (references[1].Periodical != null)) && (references[0].Periodical.ToString().Length < references[1].Periodical.ToString().Length)))
                {
                    references[0].Periodical = references[1].Periodical;
                }

                // PlaceOfPublication
                references[0].PlaceOfPublication = MergeOrCombine(references[0].PlaceOfPublication, references[1].PlaceOfPublication);

                // Price
                references[0].Price = MergeOrCombine(references[0].Price, references[1].Price);

                // PubMedID
                references[0].PubMedId = MergeOrCombine(references[0].PubMedId, references[1].PubMedId);

                // Rating (take average)
                references[0].Rating = (short)Math.Floor((decimal)((references[0].Rating + references[1].Rating) / 2));

                // (!) ReferenceType (not supported)

                // SequenceNumber (take the one of first, as second reference will be deleted)

                // ShortTitle, check if ShortTitleUpdateType is 0 at one reference if yes, take that one
                if ((references[0].ShortTitleUpdateType == UpdateType.Automatic) && (references[1].ShortTitleUpdateType == UpdateType.Manual))
                {
                    references[0].ShortTitle = references[1].ShortTitle;
                }
                else if ((references[0].ShortTitleUpdateType == UpdateType.Manual) && (references[1].ShortTitleUpdateType == UpdateType.Manual))
                {
                    references[0].ShortTitle = MergeOrCombine(references[0].ShortTitle, references[1].ShortTitle);
                }

                // SourceOfBibliographicInformation
                references[0].SourceOfBibliographicInformation = MergeOrCombine(references[0].SourceOfBibliographicInformation, references[1].SourceOfBibliographicInformation);

                // SpecificFields (1-7)
                references[0].SpecificField1 = MergeOrCombine(references[0].SpecificField1, references[1].SpecificField1);
                references[0].SpecificField2 = MergeOrCombine(references[0].SpecificField2, references[1].SpecificField2);
                references[0].SpecificField3 = MergeOrCombine(references[0].SpecificField3, references[1].SpecificField3);
                references[0].SpecificField4 = MergeOrCombine(references[0].SpecificField4, references[1].SpecificField4);
                references[0].SpecificField5 = MergeOrCombine(references[0].SpecificField5, references[1].SpecificField5);
                references[0].SpecificField6 = MergeOrCombine(references[0].SpecificField6, references[1].SpecificField6);
                references[0].SpecificField7 = MergeOrCombine(references[0].SpecificField7, references[1].SpecificField7);

                // StartPage
                //TODO: see page range

                // StorageMedium
                references[0].StorageMedium = MergeOrCombine(references[0].StorageMedium, references[1].StorageMedium);

                // Subtitle
                references[0].Subtitle = MergeOrCombine(references[0].Subtitle, references[1].Subtitle);

                // SubtitleTagged
                //TODO: we are not merging SubtitleTagged as that changes the Subtitle as well
                //references[0].SubtitleTagged = MergeOrCombine(references[0].SubtitleTagged, references[1].SubtitleTagged);

                // TableOfContents, naive approach...
                if ((references[0].TableOfContents == null) || (((references[0].TableOfContents != null) && (references[1].TableOfContents != null)) && (references[0].TableOfContents.ToString().Length < references[1].TableOfContents.ToString().Length)))
                {
                    references[0].TableOfContents.Text = references[1].TableOfContents.Text;
                }

                // TextLinks
                references[0].TextLinks = MergeOrCombine(references[0].TextLinks, references[1].TextLinks);

                // Title
                references[0].Title = MergeOrCombine(references[0].Title, references[1].Title);

                // TitleTagged
                //TODO: we are not merging TitleTagged as that changes the Title as well
                //references[0].TitleTagged = MergeOrCombine(references[0].TitleTagged, references[1].TitleTagged);

                // TitleInOtherLanguages
                references[0].TitleInOtherLanguages = MergeOrCombine(references[0].TitleInOtherLanguages, references[1].TitleInOtherLanguages);

                // TitleSupplement
                references[0].TitleSupplement = MergeOrCombine(references[0].TitleSupplement, references[1].TitleSupplement);

                // TitleSupplementTagged
                //TODO: we are not merging TitleSupplementTagged as that changes the TitleSupplement as well
                //references[0].TitleSupplementTagged = MergeOrCombine(references[0].TitleSupplementTagged, references[1].TitleSupplementTagged);

                // TranslatedTitle
                references[0].TranslatedTitle = MergeOrCombine(references[0].TranslatedTitle, references[1].TranslatedTitle);

                // UniformTitle
                references[0].UniformTitle = MergeOrCombine(references[0].UniformTitle, references[1].UniformTitle);

                // Volume
                references[0].Volume = MergeOrCombine(references[0].Volume, references[1].Volume);

                // Year
                references[0].Year = MergeOrCombine(references[0].Year, references[1].Year);

                // ReservedData
                //TODO: apparently cannot be set

                // RecordVersion (?)
                //TODO: apparently cannot be set


                // FOREIGN KEY fields

                // Locations
                foreach (Location location in references[1].Locations)
                {
                    if (!references[0].Locations.Contains(location))
                    {
                        references[0].Locations.Add(location);
                    }
                }

                // Groups
                references[0].Groups.AddRange(references[1].Groups);

                // Quotations
                references[0].Quotations.AddRange(references[1].Quotations);

                // ReferenceAuthors
                //references[0].Authors.AddRange(references[1].Authors);
                foreach (Person author in references[1].Authors)
                {
                    if (!references[0].Authors.Contains(author))
                    {
                        references[0].Authors.Add(author);
                    }
                }

                // ReferenceCategory
                references[0].Categories.AddRange(references[1].Categories);

                // ReferenceCollaborator
                foreach (Person collaborator in references[1].Collaborators)
                {
                    if (!references[0].Collaborators.Contains(collaborator))
                    {
                        references[0].Collaborators.Add(collaborator);
                    }
                }

                // ReferenceEditor
                foreach (Person editor in references[1].Editors)
                {
                    if (!references[0].Editors.Contains(editor))
                    {
                        references[0].Editors.Add(editor);
                    }
                }

                // ReferenceKeyword
                foreach (Keyword keyword in references[1].Keywords)
                {
                    if (!references[0].Keywords.Contains(keyword))
                    {
                        references[0].Keywords.Add(keyword);
                    }
                }

                // ReferenceOrganization
                foreach (Person organization in references[1].Organizations)
                {
                    if (!references[0].Organizations.Contains(organization))
                    {
                        references[0].Organizations.Add(organization);
                    }
                }

                // ReferenceOthersInvolved
                foreach (Person otherinvolved in references[1].OthersInvolved)
                {
                    if (!references[0].OthersInvolved.Contains(otherinvolved))
                    {
                        references[0].OthersInvolved.Add(otherinvolved);
                    }
                }

                // ReferencePublisher
                foreach (Publisher publisher in references[1].Publishers)
                {
                    if (!references[0].Publishers.Contains(publisher))
                    {
                        references[0].Publishers.Add(publisher);
                    }
                }

                // ReferenceReference
                // adding ChildReferences does not work
                //references[0].ChildReferences.AddRange(references[1].ChildReferences);
                Reference[] childReferences = references[1].ChildReferences.ToArray();
                foreach (Reference child in childReferences)
                {
                    child.ParentReference = references[0];
                }

                // SeriesTitle, naive approach
                if ((references[0].SeriesTitle == null) || (((references[0].SeriesTitle != null) && (references[1].SeriesTitle != null)) && (references[0].SeriesTitle.ToString().Length < references[1].SeriesTitle.ToString().Length)))
                {
                    references[0].SeriesTitle = references[1].SeriesTitle;
                }


                // change crossreferences
                foreach (EntityLink entityLink in references[1].EntityLinks)
                {
                    if (entityLink.Source == references[1])
                    {
                        entityLink.Source = references[0];
                    }
                    else if (entityLink.Target == references[1])
                    {
                        entityLink.Target = references[0];
                    }
                }


                // write Note that the reference has been merged
                if (references[0].Notes.Trim().Length > 0)
                {
                    references[0].Notes += " |";
                }
                references[0].Notes += " This reference has been merged with a duplicate by CitaviBot.";

                // DONE! remove second reference
                activeProject.References.Remove(references[1]);
            }
            else
            {
                MessageBox.Show("Currently this script only supports merging two references of the same type. Please convert and try again.");
            }
        }
        else
        {
            MessageBox.Show("Currently this script only supports merging two references. Please select two and try again.");
        }
    }
    public static void Main()
    {
        if (Program.ProjectShells.Count == 0)
        {
            return;                                                     //no project open
        }
        if (IsBackupAvailable() == false)
        {
            return;                                                             //user wants to backup his/her project first
        }
        int counter = 0;

        try
        {
            //IMPORTANT: We need a List<Reference>, NOT the internal ProjectReferenceCollection, because the latter would trigger erratic errors of the kind
            //"collection was modified, enumeration operation may not execute"

            //if this macro should ALWAYS affect all titles in active project, choose first option
            //if this macro should affect just filtered rows if there is a filter applied and ALL if not, choose second option

            //List<Reference> references = CollectionUtility.ToList<Reference>(Program.ActiveProjectShell.Project.References);
            List <Reference> references = Program.ActiveProjectShell.PrimaryMainForm.GetFilteredReferences();

            //if we need a ref to the active project
            SwissAcademic.Citavi.Project activeProject = Program.ActiveProjectShell.Project;

            List <Location> filesToShowImmediately = new List <Location>();

            foreach (Reference reference in references)
            {
                foreach (Location location in reference.Locations)
                {
                    //first we collect all files that are not set to be shown immediately yet
                    if (location.LocationType == LocationType.ElectronicAddress)
                    {
                        switch (location.AddressUri.AddressInfo)
                        {
                        case ElectronicAddressInfo.RemoteUri:
                        case ElectronicAddressInfo.AbsoluteFileUri:
                        case ElectronicAddressInfo.RelativeFileUri:
                        case ElectronicAddressInfo.Attachment:
                        {
                            //MessageBox.Show(string.Format("Location:{0}\n\rPreview Behaviour:{1}\n\rLocal Path:{2}", location.ToString(), location.PreviewBehaviour.ToString(), location.AddressUri.AbsoluteUri.LocalPath.ToString()));
                            if (location.PreviewBehaviour != PreviewBehaviour.ShowEntryPage)
                            {
                                filesToShowImmediately.Add(location);
                            }
                            //if(location.AddressUri.AbsoluteUri.LocalPath == DriveType.Network) filesToShowImmediately.Add(location);
                        }
                        break;
                        }
                    }
                }
            }


            //now we change the PreviewBehaviour on all the collected files
            foreach (Location location in filesToShowImmediately)
            {
                if (location.PreviewBehaviour != PreviewBehaviour.ShowEntryPage)
                {
                    location.PreviewBehaviour = PreviewBehaviour.ShowEntryPage;
                    counter++;
                }
            }

            activeProject.Save();
        }         //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()
    public static void Main()
    {
        //****************************************************************************************************************
        // UPDATE BIBLIOGRAPHIC DATA FROM PMID OR DOI-SEARCH
        // Version 2.1 -- 2015-01-12
        //
        // This macro iterates through the references in a selection ("filter").
        // If they have a DOI or PMID, it downloads bibliographical data and owverwrites the reference's data.
        // PMID is given priority over DOI, i.e. if both are present, data will be loaded from PubMed.
        //
        //
        // EDIT HERE
        // Variables to be changed by user

        bool overwriteAbstract        = false;                  // if true, existing Abstract will be replaced
        bool overwriteTableOfContents = false;                  // if true, existing TOC will be replaced
        bool overwriteKeywords        = false;                  // if true, existing Keywords will be replaced
        bool clearNotes = true;                                 // if true, Notes field will be emptied


        // DO NOT EDIT BELOW THIS LINE
        // ****************************************************************************************************************

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

        try
        {
            List <Reference> references = Program.ActiveProjectShell.PrimaryMainForm.GetFilteredReferences();
            var referencesWithDoi       = references.Where(reference => !string.IsNullOrEmpty(reference.PubMedId) | !string.IsNullOrEmpty(reference.Doi)).ToList();

            SwissAcademic.Citavi.Project activeProject = Program.ActiveProjectShell.Project;

            var identifierSupport = new ReferenceIdentifierSupport();


            foreach (Reference reference in referencesWithDoi)
            {
                // Look up PMID. If that fails, look up DOI. If no data is found, move on.
                var lookedUpReference = identifierSupport.FindReference(activeProject, new ReferenceIdentifier()
                {
                    Type = ReferenceIdentifierType.PubMedId, Value = reference.PubMedId
                }, true, null);
                if (lookedUpReference == null)
                {
                    lookedUpReference = identifierSupport.FindReference(activeProject, new ReferenceIdentifier()
                    {
                        Type = ReferenceIdentifierType.Doi, Value = reference.Doi
                    }, true, null);
                }
                if (lookedUpReference == null)
                {
                    continue;
                }


                //merge reference & lookedUpReference, overwriting bibliographic data of the former
                List <ReferencePropertyId> omitData = new List <ReferencePropertyId>();
                omitData.Add(ReferencePropertyId.CoverPath);
                omitData.Add(ReferencePropertyId.Locations);

                if (!overwriteAbstract)
                {
                    omitData.Add(ReferencePropertyId.Abstract);
                }
                if (!overwriteTableOfContents)
                {
                    omitData.Add(ReferencePropertyId.TableOfContents);
                }
                if (!overwriteKeywords)
                {
                    omitData.Add(ReferencePropertyId.Keywords);
                }

                reference.MergeReference(lookedUpReference, true, omitData);

                counter++;

                if (!string.IsNullOrEmpty(reference.Notes) && clearNotes)
                {
                    reference.Notes = string.Empty;                                                                             //empty notes field
                }
                if (activeProject.Engine.Settings.BibTeXCitationKey.IsTeXEnabled)
                {
                    reference.BibTeXKey = activeProject.BibTeXKeyAssistant.GenerateKey(reference);
                }
                if (activeProject.Engine.Settings.BibTeXCitationKey.IsCitationKeyEnabled)
                {
                    reference.CitationKey = activeProject.CitationKeyAssistant.GenerateKey(reference);
                }
            }
        }         //end try

        finally
        {
            MessageBox.Show(string.Format("Macro has finished execution.\r\n{0} references were updated.", counter.ToString()), "Citavi", MessageBoxButtons.OK, MessageBoxIcon.Information);
        } //end finally
    }     //end main()
    public static async void Main()
    {
        //****************************************************************************************************************
        // UPDATE BIBLIOGRAPHIC DATA FROM PMID OR DOI-SEARCH
        // Version 2.4 -- 2019-12-06
        //			-- updated to work with Citavi 6 (only version 6.3.15 or newer!)
        //
        // This macro iterates through the references in a selection ("filter").
        // If they have a PMID or DOI or ISBN, it downloads bibliographical data and owverwrites the reference's data.
        //
        // PMID is given priority over DOI , i.e. if both are present, data will be loaded from PubMed, then
        // Crossref. then the selected catalogues.
        //
        //
        // EDIT HERE
        // Variables to be changed by user

        bool overwriteAbstract        = false;     // if true, existing Abstract will be replaced
        bool overwriteTableOfContents = false;     // if true, existing TOC will be replaced
        bool overwriteKeywords        = false;     // if true, existing Keywords will be replaced
        bool clearNotes = true;                    // if true, Notes field will be emptied

        bool useIsbn = true;                       // if true, the ISBN field will also be used to query data

        int wait = 4;                              // timeout in seconds

        // DO NOT EDIT BELOW THIS LINE
        // ****************************************************************************************************************

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

        try
        {
            List <Reference>             references    = Program.ActiveProjectShell.PrimaryMainForm.GetFilteredReferences();
            SwissAcademic.Citavi.Project activeProject = Program.ActiveProjectShell.Project;

            foreach (Reference reference in references)
            {
                if (String.IsNullOrEmpty(reference.PubMedId) &&
                    String.IsNullOrEmpty(reference.Doi) &&
                    String.IsNullOrEmpty(reference.Isbn.ToString()))
                {
                    continue;
                }

                DebugMacro.WriteLine("Checking reference " + reference.ShortTitle);

                var cts = new CancellationTokenSource(TimeSpan.FromSeconds(wait));

                Reference lookedUpReference = null;

                if (!String.IsNullOrEmpty(reference.PubMedId))
                {
                    try
                    {
                        ReferenceIdentifier refIdentPmid = new ReferenceIdentifier()
                        {
                            Value = reference.PubMedId, Type = ReferenceIdentifierType.PubMedId
                        };
                        var identifierSupport = new ReferenceIdentifierSupport();
                        lookedUpReference = await identifierSupport.FindReferenceAsync(activeProject, refIdentPmid, cts.Token);
                    }
                    catch (System.OperationCanceledException e)
                    {
                        DebugMacro.WriteLine("Timeout.");
                        continue;
                    }
                    catch (Exception e)
                    {
                        DebugMacro.WriteLine("An error occured: " + e.ToString());
                        continue;
                    }
                }
                else if (!String.IsNullOrEmpty(reference.Doi))
                {
                    try
                    {
                        ReferenceIdentifier refIdentDoi = new ReferenceIdentifier()
                        {
                            Value = reference.Doi, Type = ReferenceIdentifierType.Doi
                        };
                        var identifierSupport = new ReferenceIdentifierSupport();
                        lookedUpReference = await identifierSupport.FindReferenceAsync(activeProject, refIdentDoi, cts.Token);
                    }
                    catch (System.OperationCanceledException e)
                    {
                        DebugMacro.WriteLine("Timeout.");
                        continue;
                    }
                    catch (Exception e)
                    {
                        DebugMacro.WriteLine("An error occured: " + e.ToString());
                        continue;
                    }
                }
                else if (!String.IsNullOrEmpty(reference.Isbn.ToString()) && useIsbn)
                {
                    try
                    {
                        ReferenceIdentifier refIdentIsbn = new ReferenceIdentifier()
                        {
                            Value = reference.Isbn, Type = ReferenceIdentifierType.Isbn
                        };
                        var identifierSupport = new ReferenceIdentifierSupport();
                        lookedUpReference = await identifierSupport.FindReferenceAsync(activeProject, refIdentIsbn, cts.Token);
                    }
                    catch (System.OperationCanceledException e)
                    {
                        DebugMacro.WriteLine("Timeout.");
                        continue;
                    }
                    catch (Exception e)
                    {
                        DebugMacro.WriteLine("An error occured: " + e.ToString());
                        continue;
                    }
                }

                // if nothing is found, move on
                if (lookedUpReference == null)
                {
                    continue;
                }


                //merge reference & lookedUpReference, overwriting bibliographic data of the former
                List <ReferencePropertyId> omitData = new List <ReferencePropertyId>();
                omitData.Add(ReferencePropertyId.CoverPath);
                omitData.Add(ReferencePropertyId.Locations);


                if (!overwriteAbstract)
                {
                    omitData.Add(ReferencePropertyId.Abstract);
                }
                if (!overwriteTableOfContents)
                {
                    omitData.Add(ReferencePropertyId.TableOfContents);
                }
                if (!overwriteKeywords)
                {
                    omitData.Add(ReferencePropertyId.Keywords);
                }

                reference.MergeReference(lookedUpReference, true, omitData.ToArray());

                counter++;

                if (!string.IsNullOrEmpty(reference.Notes) && clearNotes)
                {
                    reference.Notes = string.Empty;                                                         //empty notes field
                }
                if (activeProject.Engine.Settings.BibTeXCitationKey.IsTeXEnabled)
                {
                    reference.BibTeXKey = activeProject.BibTeXKeyAssistant.GenerateKey(reference);
                }
                if (activeProject.Engine.Settings.BibTeXCitationKey.IsCitationKeyEnabled)
                {
                    reference.CitationKey = activeProject.CitationKeyAssistant.GenerateKey(reference);
                }
            }
        } //end try

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