Beispiel #1
0
    /// <summary>
    /// You can use 'Main' or 'MainAsync' it doesn`t matter.
    /// </summary>
    public static async Task MainAsync()
    {
        /// <summary>
        ///  This code is an example how you can get data from citavi.
        /// </summary>
        MainForm         mainForm   = Program.ActiveProjectShell.PrimaryMainForm;
        List <Reference> references = mainForm.GetFilteredReferences().ToList();

        try
        {
            /// <summary>
            /// GenericProgressDialog is huge customizable. You can use 'RunFunc()' or 'RunAction' instead of 'RunTask()'. They are much signatures with differente parameters you can use ;)
            /// </summary>
            await GenericProgressDialog.RunTask(mainForm, DoSomeThingWithReferencesOverALongPeriodAsync, references);
        }
        catch (OperationCanceledException)
        {
            // Here you can handle user cancelling if you use cancellationToken.ThrowIfCancellationRequested()
            DebugMacro.WriteLine("Cancelled");
            return;
        }
        catch (Exception)
        {
            // Here you can handle unexpected exceptions
            DebugMacro.WriteLine("Unexpected exception");
            return;
        }

        // Here you can handle stuff if the process finished
        DebugMacro.WriteLine("Completed");
    }
Beispiel #2
0
    static void CheckText(string entity, string text, string name, Guid id, string property)
    {
        if (text.Length > bytes)
        {
            string output = string.Format("{0}: {1}({2}) - {3} > {4}MB. Größe: {5}MB", entity, name, id, property, mb, text.Length / 1024 / 1024);

            DebugMacro.WriteLine(output);
        }
    }
Beispiel #3
0
    public static void Main()
    {
        //EXPORT from C5
        string citaviVersion = SwissAcademic.Environment.InformationalVersion.ToString(4);

        DebugMacro.WriteLine(citaviVersion);
        if (!(citaviVersion.StartsWith("5") || citaviVersion.StartsWith("4.9.")))
        {
            return;
        }

        ProjectShell activeProjectShell = Program.ActiveProjectShell;

        if (activeProjectShell == null)
        {
            return;                                     //no open project shell
        }
        Project activeProject = Program.ActiveProjectShell.Project;

        if (activeProject == null)
        {
            return;
        }

        Form primaryMainForm = activeProjectShell.PrimaryMainForm;

        if (primaryMainForm == null)
        {
            return;
        }

        string xmlFile  = string.Empty;
        string ctv3File = string.Empty;

        string initialDirectory = Program.Engine.DesktopEngineConfiguration.GetFolderPath(CitaviFolder.Projects, activeProject);

        //ask for file name & path
        using (SaveFileDialog saveFileDialog = new SaveFileDialog())
        {
            saveFileDialog.Filter           = "XML files (*.xml)|*.xml|All files (*.*)|*.*";
            saveFileDialog.InitialDirectory = initialDirectory;
            saveFileDialog.Title            = "Enter an XML file name for export of Citavi project data.";

            if (saveFileDialog.ShowDialog(primaryMainForm) != DialogResult.OK)
            {
                return;
            }
            xmlFile = saveFileDialog.FileName;
        }


        var compatibility = ProjectXmlExportCompatibility.Citavi4;

        ProjectToXml.Write(xmlFile, activeProject, CancellationToken.None, null, null, compatibility);
        MessageBox.Show("Finished");
    }
Beispiel #4
0
    public static void Export(String path)
    {
        Project activeProject = Program.ActiveProjectShell.Project;
        string  FOLDERPATH    = path + "\\keywords.json";

        try
        {
            System.IO.File.WriteAllBytes(FOLDERPATH, new byte[0]);
            char[] charsToTrim = { ' ', '“', '”', };
            int    count       = 0;

            using (System.IO.StreamWriter file = new System.IO.StreamWriter(FOLDERPATH, true))
            {
                file.WriteLine("{\r\n\"keywords\":[");


                foreach (Keyword key in activeProject.Keywords)
                {
                    string temp = "";
                    if (count > 0)
                    {
                        temp = ",\r\n" +
                               "{\r\n" +
                               "\"Keyword\":\"" + key.FullName.Trim(charsToTrim).Replace("\"", "\\\"") + "\"\r\n" +
                               ", \"Notes\":\"" + key.Notes.Trim(charsToTrim).Replace("\"", "\\\"") + "\"\r\n" +
                               "}";
                    }
                    else
                    {
                        temp = "{\r\n" +
                               "\"Keyword\":\"" + key.FullName.Trim(charsToTrim).Replace("\"", "\\\"") + "\"\r\n" +
                               ", \"Notes\":\"" + key.Notes.Trim(charsToTrim).Replace("\"", "\\\"") + "\"\r\n" +
                               "}";
                    }



                    file.WriteLine(temp);


                    count++;
                }


                file.WriteLine("]\r\n}");
            }
            DebugMacro.WriteLine("Success");
        }
        catch (Exception e)
        {
            DebugMacro.WriteLine("Exception:" + e.Message);
            DebugMacro.WriteLine(e.StackTrace);
        }
    }
    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);
        }
    }
Beispiel #6
0
    }     //end main()

    private static void AddCategories(IEnumerable <Reference> references, string categoryHierarchy)
    {
        DebugMacro.WriteLine(categoryHierarchy);

        List <string> categoryStrings = categoryHierarchy.Split(new Char[] { Path.DirectorySeparatorChar }, StringSplitOptions.RemoveEmptyEntries).ToList();

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


        #region Add Categories to Project if required

        Project  project = references.First().Project;
        string   currentCategoryString = categoryStrings.FirstOrDefault();
        Category currentCategory       = project.Categories.FirstOrDefault(item => item.Name.Equals(currentCategoryString, StringComparison.Ordinal));
        if (currentCategory == null)
        {
            currentCategory = project.Categories.Add(currentCategoryString);
        }

        for (int i = 1; i < categoryStrings.Count; i++)
        {
            currentCategoryString = categoryStrings.ElementAt(i);
            Category existingCategory = currentCategory.Categories.FirstOrDefault(item => item.Name.Equals(currentCategoryString, StringComparison.Ordinal));
            if (existingCategory == null)
            {
                currentCategory = currentCategory.Categories.Add(currentCategoryString);
            }
            else
            {
                currentCategory = existingCategory;
            }
        }

        #endregion

        #region Add Category to Reference

        foreach (Reference reference in references)
        {
            reference.Categories.Add(currentCategory);
        }

        #endregion
    }
    public static void Main()
    {
        if (Program.ActiveProjectShell == null)
        {
            return;
        }
        Project activeProject = Program.ActiveProjectShell.Project;

        if (activeProject == null)
        {
            DebugMacro.WriteLine("No active project.");
            return;
        }
        List <Reference> references = Program.ActiveProjectShell.PrimaryMainForm.GetFilteredReferences();

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

        ContactInfo taskAssignee = activeProject.Contacts.GetMembers().FirstOrDefault <ContactInfo>(item => item.FullName.Equals("Jane Doe"));

        if (taskAssignee == null)
        {
            DebugMacro.WriteLine("No such contact.");
            return;
        }
        DateTime?     dueDate  = new DateTime(2019, 12, 31);
        KnownTaskName taskName = KnownTaskName.ExcerptQuotations;

        //string taskName = "Do something else with these references.";

        foreach (Reference reference in references)
        {
            //reference.Tasks.Clear();
            TaskItem task = reference.Tasks.Add(taskName);
            task.AssignedTo = taskAssignee.Key;
            task.DueDate    = dueDate;
        }


        DebugMacro.WriteLine("Done.");
    }
    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);
        }
    }
    private static void CreateFolderStructure(string fullPath)
    {
        if (!Directory.Exists(fullPath))
        {
            bool tryAgain = true;
            while (tryAgain)
            {
                try
                {
                    DirectoryInfo di = Directory.CreateDirectory(fullPath);
                    DebugMacro.WriteLine("Folder created: " + di.FullName);
                    tryAgain = false;
                }
                catch (Exception e)
                {
                    tryAgain = false;
                    DialogResult directoryError = MessageBox.Show("An error occurred creating a folder: " + e.Message,
                                                                  "Error creating folder", MessageBoxButtons.AbortRetryIgnore,
                                                                  MessageBoxIcon.Error, MessageBoxDefaultButton.Button1);

                    if (directoryError == DialogResult.Abort)
                    {
                        return;
                    }
                    else if (directoryError == DialogResult.Retry)
                    {
                        tryAgain = true;
                    }
                    else
                    {
                        break;
                    };
                }
            }
        }
    }
    public static void Main()
    {
        ProjectShell activeProjectShell = Program.ActiveProjectShell;

        if (activeProjectShell == null)
        {
            return;                                     //no open project shell
        }
        Project targetProject = Program.ActiveProjectShell.Project;

        if (targetProject == null)
        {
            return;
        }

        Form primaryMainForm = activeProjectShell.PrimaryMainForm;

        if (primaryMainForm == null)
        {
            return;
        }

        string sourceCTV6File   = string.Empty;
        string initialDirectory = Program.Engine.DesktopEngineConfiguration.GetFolderPath(CitaviFolder.Projects);

        DebugMacro.WriteLine(initialDirectory);

        //System.Environment.GetFolderPath(System.Environment.SpecialFolder.Desktop
        var openFileDialog = new OpenFileDialog()
        {
            Filter           = "Citavi Project Files|*.ctv6",
            CheckFileExists  = true,
            CheckPathExists  = true,
            Multiselect      = false,
            InitialDirectory = initialDirectory
        };

        if (openFileDialog.ShowDialog(primaryMainForm) != DialogResult.OK)
        {
            return;
        }

        string sourceProjectFile = openFileDialog.FileName;

        DebugMacro.WriteLine(sourceProjectFile);

        Project sourceProject = GetProject(sourceProjectFile).Result;

        if (sourceProject == null)
        {
            return;
        }


        IEnumerable <Category> targetCategories = targetProject.AllCategories.AsEnumerable <Category>();
        IEnumerable <Category> sourceCategories = sourceProject.AllCategories.AsEnumerable <Category>();

        foreach (Category targetCategory in targetCategories)
        {
            Category sourceCategory = sourceCategories.FindCategory(targetCategory);
            if (sourceCategory == null)
            {
                continue;
            }

            IEnumerable <KnowledgeItem> sourceCategoryKnowledgeItems = sourceCategory.KnowledgeItems.AsEnumerable <KnowledgeItem>();

            foreach (KnowledgeItem sourceKnowledgeItem in sourceCategoryKnowledgeItems)
            {
                //if exists in target KI collection, then move to bottom
                KnowledgeItem targetKnowledgeItem = targetCategory.KnowledgeItems.FindKnowledgeItem(sourceKnowledgeItem);
                if (targetKnowledgeItem == null)
                {
                    continue;
                }

                targetCategory.KnowledgeItems.MoveToBottom(targetKnowledgeItem);
            }
        }


        MessageBox.Show("Done");
    }
Beispiel #11
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()
Beispiel #12
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);
    }
    public static void Export(String path)
    {
        Project activeProject = Program.ActiveProjectShell.Project;
        string  FOLDERPATH    = path + "\\categories.json";

        try
        {
            System.IO.File.WriteAllBytes(FOLDERPATH, new byte[0]);
            char[] charsToTrim = { ' ', '“', '”', };

            int count = 0;
            using (System.IO.StreamWriter file = new System.IO.StreamWriter(FOLDERPATH, true))
            {
                file.WriteLine("{\r\n\"categories\":[");

                foreach (Category cat in activeProject.AllCategories)
                {
                    string parent;
                    string parentClassifier;
                    if (cat.IsRootCategory)
                    {
                        parent           = "";
                        parentClassifier = "";
                    }
                    else
                    {
                        parent           = cat.ParentCategory.Name.ToString();
                        parentClassifier = cat.Parent.Classification.ToString();
                    }

                    string temp = "";
                    if (count > 0)
                    {
                        temp = ",{\r\n" +
                               "\"Index\":" + cat.Index + ",\r\n" +
                               "\"Name\":\"" + cat.Name.Trim(charsToTrim).Replace("\"", "\\\"") + "\",\r\n" +
                               "\"Classifier\":\"" + cat.Classification + "\",\r\n" +
                               "\"ParentName\":\"" + parent.Trim(charsToTrim).Replace("\"", "\\\"") + "\",\r\n" +
                               "\"ParentClassifier\":\"" + parentClassifier + "\",\r\n" +
                               "\"Level\":" + cat.Level + "\r\n" +
                               "}";
                    }
                    else
                    {
                        temp = "{\r\n" +
                               "\"Index\":" + cat.Index + ",\r\n" +
                               "\"Name\":\"" + cat.Name.Trim(charsToTrim).Replace("\"", "\\\"") + "\",\r\n" +
                               "\"Classifier\":\"" + cat.Classification + "\",\r\n" +
                               "\"ParentName\":\"" + parent.Trim(charsToTrim).Replace("\"", "\\\"") + "\",\r\n" +
                               "\"ParentClassifier\":\"" + parentClassifier + "\",\r\n" +
                               "\"Level\":" + cat.Level + "\r\n" +
                               "}";
                    }



                    file.WriteLine(temp);

                    count++;
                }

                file.WriteLine("]\r\n}");

                DebugMacro.WriteLine("Success");
            }
        }
        catch (Exception ex)
        {
            DebugMacro.WriteLine("Exception:" + ex.Message);
            DebugMacro.WriteLine(ex.StackTrace);
        }
    }
Beispiel #14
0
    public static void Main()
    {
        //****************************************************************************************************************
        // UPDATE BIBLIOGRAPHIC DATA FROM PMID OR DOI-SEARCH
        // Version 2.2 -- 2019-04-09
        //    -- updated to work with Citavi 6
        //
        // 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();
            List <Reference> referencesWithDoi = references.Where(reference => !string.IsNullOrEmpty(reference.PubMedId) || !string.IsNullOrEmpty(reference.Doi)).ToList();

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

            var    identifierSupport = new ReferenceIdentifierSupport();
            string message           = "Updating reference {0} of {1} - '{2}' ... {3}";
            int    currentRef        = 0;
            int    overallRefs       = referencesWithDoi.Count();

            foreach (Reference reference in referencesWithDoi)
            {
                currentRef++;


                // Look up PMID. If that fails, look up DOI. If no data is found, move on.
                DebugMacro.WriteLine(string.Format(message, currentRef.ToString(), overallRefs.ToString(), reference.ShortTitle, ""));
                Reference lookedUpReference = identifierSupport.FindReference(activeProject.Engine, activeProject, new ReferenceIdentifier()
                {
                    Type = ReferenceIdentifierType.PubMedId, Value = reference.PubMedId
                });
                if (lookedUpReference == null)
                {
                    lookedUpReference = identifierSupport.FindReference(activeProject.Engine, activeProject, new ReferenceIdentifier()
                    {
                        Type = ReferenceIdentifierType.Doi, Value = reference.Doi
                    });
                    if (lookedUpReference == null)
                    {
                        DebugMacro.WriteLine(string.Format(message, currentRef.ToString(), overallRefs.ToString(), reference.ShortTitle, "No data found!"));
                        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 void Main()
    {
        //****************************************************************************************************************
        // List Keywords for Each Category in a Text File
        // 1.0 -- 2015-07-30
        //

        // This macro writes a text file containing a list of all Keywords used in References assigned to a certain
        // category.
        //
        //
        // EDIT HERE
        // Variables to be changed by user


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

        ProjectShell activeProjectShell = Program.ActiveProjectShell;

        if (activeProjectShell == null)
        {
            return;                                     //no open project shell
        }
        Project activeProject = Program.ActiveProjectShell.Project;

        if (activeProject == null)
        {
            return;
        }

        Form primaryMainForm = activeProjectShell.PrimaryMainForm;

        if (primaryMainForm == null)
        {
            return;
        }

        if (Program.ProjectShells.Count == 0)
        {
            return;                                                     //no project open
        }
        string file = string.Empty;


        string initialDirectory = Environment.GetFolderPath(Environment.SpecialFolder.Personal);

        using (SaveFileDialog saveFileDialog = new SaveFileDialog())
        {
            saveFileDialog.Filter           = "Plain Text (*.txt)|*.txt|All files (*.*)|*.*";
            saveFileDialog.InitialDirectory = initialDirectory;
            saveFileDialog.Title            = "Enter a file name for the output file.";

            if (saveFileDialog.ShowDialog(primaryMainForm) != DialogResult.OK)
            {
                return;
            }
            file = saveFileDialog.FileName;
        }


        StreamWriter sw = null;

        try
        {
            sw = File.AppendText(file);
        }
        catch (Exception e)
        {
            DebugMacro.WriteLine("Error creating file: " + e.Message.ToString());
            return;
        }


        // write line with categories to file
        string headline = activeProject.Name + " -- Categories and Keywords ";

        headline = headline + "\n";
        sw.WriteLine(headline);


        //iterate over all references in the current filter (or over all, if there is no filter)
        List <Reference> references = Program.ActiveProjectShell.PrimaryMainForm.GetFilteredReferences();


        //reference to all Categories in the project
        Category[] allCategories = activeProject.AllCategories.ToArray();
        Array.Sort(allCategories);

        //reference to all Keywords in the project
        Keyword[] allKeywords = activeProject.Keywords.ToArray();
        Array.Sort(allKeywords);

        // abort if no categories/references present
        if (!allCategories.Any() || !references.Any() || !allKeywords.Any())
        {
            DebugMacro.WriteLine("No categories/keywords or references in current project.");
            return;
        }



        // check each category in turn and gather keywords

        foreach (Category category in allCategories)
        {
            List <Keyword> categoryKeywords = new List <Keyword>();

            foreach (Reference reference in references)
            {
                foreach (Category referenceCategory in reference.Categories)
                {
                    if (referenceCategory.Equals(category))
                    {
                        foreach (Keyword kw in reference.Keywords)
                        {
                            categoryKeywords.Add(kw);
                        }
                    }
                }
            }


            // Clean and Sort list of Keywords
            List <Keyword> categoryKeywordsUnique = categoryKeywords.Distinct().ToList();
            categoryKeywordsUnique.Sort();


            // write output to file

            sw.WriteLine(category.ToString() + "\n");

            if (categoryKeywordsUnique.Count > 0)
            {
                foreach (Keyword key in categoryKeywordsUnique)
                {
                    sw.WriteLine("\t" + key.ToString());
                }
            }
            else
            {
                sw.WriteLine("\t" + "---");
            }

            // clear Keywords for new Category
            categoryKeywords.Clear();
            categoryKeywordsUnique.Clear();
            sw.WriteLine("\n");
        }

        // close file
        sw.Close();

        // Message upon completion
        string message = "File written to " + file;

        MessageBox.Show(message, "Macro", MessageBoxButtons.OK, MessageBoxIcon.Information);
    }
Beispiel #16
0
    public static void Main()
    {
        //****************************************************************************************************************
        // CHANGE NUMERAL SYSTEM FOR ALL KNOWLEDGE ITEMS OF THE SELECTED REFERENCES
        // 1.1 -- 2018-05-29 added ".ToList()" to foreach loop on reference.Quotations to avoid "enumeration changed" errors
        // 1.0 -- 2017-12-12
        //
        // This macro sets the numeral system to "arabic" for all knowledge items that currently have no numeral system
        // specified.

        //
        // EDIT HERE
        // Variables to be changed by user



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

        if (Program.ProjectShells.Count == 0)
        {
            return;                                                     //no project open
        }
        if (IsBackupAvailable() == false)
        {
            return;                                                             //user wants to backup his/her project first
        }
        int foundCounter  = 0;
        int changeCounter = 0;
        int errorCounter  = 0;


        //iterate over all references in the current filter (or over all, if there is no filter)
        List <Reference> references = Program.ActiveProjectShell.PrimaryMainForm.GetFilteredReferences();

        //reference to active Project
        Project activeProject = Program.ActiveProjectShell.Project;

        if (activeProject == null)
        {
            return;
        }


        foreach (Reference reference in references)
        {
            foreach (KnowledgeItem knowledgeItem in reference.Quotations.ToList())
            {
                if (knowledgeItem.Reference == null)
                {
                    continue;                                  // ignore Ideas
                }
                if (knowledgeItem.QuotationType == QuotationType.Highlight)
                {
                    continue;                                                                         // ignore highlights
                }
                foundCounter++;
                var knowledgeItemPageRange = knowledgeItem.PageRange;
                try
                {
                    if (knowledgeItem.PageRange.NumeralSystem == NumeralSystem.Omit)
                    {
                        PageRange newPageRange = knowledgeItemPageRange.Update(NumeralSystem.Arabic);
                        knowledgeItem.PageRange = newPageRange;
                        changeCounter++;
                    }
                }
                catch (Exception e)
                {
                    MessageBox.Show("An error occurred: " + e.Message, "Citavi Macro", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    DebugMacro.WriteLine(e.ToString());
                    errorCounter++;
                    return;
                }
            }
        }

        //activeProject.Save();

        // Message upon completion
        string message = " {0} knowledge item(s) found\n {1} knowledge item(s) changed\n {2} knowledge item(s) with errors";

        message = string.Format(message, foundCounter.ToString(), changeCounter.ToString(), errorCounter.ToString());
        MessageBox.Show(message, "Macro", MessageBoxButtons.OK, MessageBoxIcon.Information);
    }
Beispiel #17
0
    public static void Export(String path)
    {
        Project activeProject = Program.ActiveProjectShell.Project;
        string  FOLDERPATH    = path + "\\knowledgeItems.json";

        try
        {
            System.IO.File.WriteAllBytes(FOLDERPATH, new byte[0]);

            int    count       = 0;
            char[] charsToTrim = { ' ', '“', '”', };
            using (System.IO.StreamWriter file = new System.IO.StreamWriter(FOLDERPATH, true))
            {
                file.WriteLine("{\r\n\"knowledgeItems\":[");

                foreach (KnowledgeItem item in activeProject.AllKnowledgeItemsFiltered)
                {
                    PropertyInfo[] properties = item.GetType().GetProperties();


                    string allProps = "";

                    foreach (var prop in properties)
                    {
                        var    valueIsText = true;
                        string key         = prop.Name;
                        string value       = prop.GetValue(item).ToStringSafe();

                        if (prop.Name == "EntityLinks")
                        {
                            valueIsText = false;
                            var v = ((IEnumerable <EntityLink>)prop.GetValue(item)).ToList();
                            if (v.Count == 0)
                            {
                                value = "[]";
                            }

                            else
                            {
                                value = "[";
                                foreach (var link in v)
                                {
                                    if (link.Target is Annotation ann)
                                    {
                                        value += $"{{\"Id\":\"{ann.Id.ToString()}\"";
                                        value += $",\"Location_Id\":\"{ann.Location.Id.ToString()}\"";
                                        value += $",\"Location_FullName\":\"{ann.Location.FullName}\"";

                                        var q = ann.Quads.Select(i => $"{{\"IsContainer\":\"{i.IsContainer}\",\"Page_Idx\":\"{i.PageIndex}\",\"X1\":\"{i.X1}\",\"X2\":\"{i.X2}\",\"Y1\":\"{i.Y1}\",\"Y2\":\"{i.Y2}\"}}").Aggregate((i, j) => i + "," + j);
                                        value += $",\"Quads\":[{q}]";
                                        value += "},";
                                    }
                                }

                                value += "]";
                            }
                        }
                        else if (prop.Name == "Groups")
                        {
                            valueIsText = false;
                            var v = (KnowledgeItemGroupCollection)prop.GetValue(item);
                            if (v.Count == 0)
                            {
                                value = "[]";
                            }
                            else
                            {
                                value = "[" + v.Select(c => "\"" + c.FullName + "\"").Aggregate((i, j) => i + "," + j) + "]";
                            }
                        }
                        else if (prop.Name == "Categories")
                        {
                            valueIsText = false;
                            var v = (KnowledgeItemCategoryCollection)prop.GetValue(item);
                            if (v.Count == 0)
                            {
                                value = "[]";
                            }
                            else
                            {
                                value = "[" + v.Select(c => "\"" + c.Classification + "\"").Aggregate((i, j) => i + "," + j) + "]";
                            }
                        }
                        else if (prop.Name == "Keywords")
                        {
                            valueIsText = false;
                            var v = (KnowledgeItemKeywordCollection)prop.GetValue(item);
                            if (v.Count == 0)
                            {
                                value = "[]";
                            }
                            else
                            {
                                value = "[" + v.Select(c => "\"" + c.Name + "\"").Aggregate((i, j) => i + "," + j) + "]";
                            }
                        }

                        if (!prop.Name.Equals("IsPropertyChangeNotificationSuspended") &&
                            !prop.Name.Equals("StaticIds") &&
                            !prop.Name.Equals("TextRtf"))
                        {
                            if (!allProps.Equals(""))
                            {
                                allProps += ",\r\n";
                            }

                            if (valueIsText)
                            {
                                value = value.Trim(charsToTrim).Replace("\"", "\\\"");
                            }

                            if (valueIsText)
                            {
                                allProps += "\"" + key + "\":\"" + value + "\"";
                            }
                            else
                            {
                                allProps += "\"" + key + "\":" + value + "";
                            }
                        }
                    }



                    string temp = "";
                    if (count > 0)
                    {
                        temp = ",{\r\n" +
                               allProps + "\r\n" +
                               "}";
                    }
                    else
                    {
                        temp = "{\r\n" +
                               allProps + "\r\n" +
                               "}";
                    }



                    file.WriteLine(temp);

                    count++;
                }


                file.WriteLine("]\r\n}");
            }
            DebugMacro.WriteLine("Success");
        }
        catch (Exception e)
        {
            DebugMacro.WriteLine("Exception:" + e.Message);
            DebugMacro.WriteLine(e.StackTrace);
        }
    }
    public static void Main()
    {
        //****************************************************************************************************************
        // EXPORT ATTACHMENTS TO CATEGORY FOLDER STRUCTURE
        // V1.0 -- 2016-09-21
        // V1.1	-- 2016-09-29	- handle non-[Citavi] attachments
        // V1.2 -- 2016-09-30	- check for valid file names
        // V1.3 -- 2016-10-13   - switch for creation of all category folders (regardless of content)
        //						- check if [Local] or [LAN] attachment is reachable before trying to copy it
        // V1.4 -- 2019-06-04   - export attachments that do not have a category to an additional folder

        // EDIT HERE
        // Variables to be changed by user

        bool createFoldersForAllCategories = false; // set to false if only category folders for references with attachments are required

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

        if (Program.ProjectShells.Count == 0)
        {
            return;                                         //no project open
        }
        int changeCounter = 0;
        int errorCounter  = 0;

        //iterate over all references in the current filter (or over all, if there is no filter)
        List <Reference> references = Program.ActiveProjectShell.PrimaryMainForm.GetFilteredReferences();

        if (references == null)
        {
            return;
        }

        //reference to active Project
        Project activeProject = Program.ActiveProjectShell.Project;

        if (activeProject == null)
        {
            return;
        }

        //get root folder to export to
        string exportPath;
        FolderBrowserDialog folderDialog = new FolderBrowserDialog();

        folderDialog.Description  = "Please select root folder for export";
        folderDialog.SelectedPath = System.Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
        if (folderDialog.ShowDialog() == DialogResult.OK)
        {
            exportPath = folderDialog.SelectedPath;
        }
        else
        {
            return;
        }


        // create category structure as folder structure if all categories are required

        if (createFoldersForAllCategories)
        {
            DebugMacro.WriteLine("Creating category folder structure ...");

            List <Category> allCategories    = activeProject.AllCategories.ToList();
            List <string>   allCategoryPaths = new List <string>();

            foreach (Category category in allCategories)
            {
                string[] categoryPaths = category.GetPath(true).Split(new string[] { " > " }, StringSplitOptions.None);
                for (int i = 0; i < categoryPaths.Length; i++)
                {
                    categoryPaths[i] = MakeValidFileName(categoryPaths[i]);
                }
                string categoryPath = String.Join(@"\", categoryPaths);
                allCategoryPaths.Add(categoryPath);
            }

            foreach (string categoryPath in allCategoryPaths)
            {
                string fullPath = exportPath + @"\" + categoryPath;
                CreateFolderStructure(fullPath);
            }
        }

        // export reference Attachments
        DebugMacro.WriteLine("Processing references ...");
        foreach (Reference reference in references)
        {
            DebugMacro.WriteLine("Processing " + reference.ShortTitle + " ... ");

            //establish whether or not there are ATTACHMENTS
            List <Location>             referenceAttachments = new List <Location>();
            ReferenceLocationCollection referenceLocations   = reference.Locations;
            foreach (Location location in referenceLocations)
            {
                if (location.LocationType == LocationType.ElectronicAddress &&
                    (location.AddressUri.AddressInfo == ElectronicAddressInfo.Attachment ||
                     location.AddressUri.AddressInfo == ElectronicAddressInfo.AbsoluteFileUri ||
                     location.AddressUri.AddressInfo == ElectronicAddressInfo.RelativeFileUri)
                    )
                {
                    referenceAttachments.Add(location);
                }
            }
            if (referenceAttachments == null || referenceAttachments.Count == 0)
            {
                continue;
            }

            DebugMacro.WriteLine("Number of attachments found: " + referenceAttachments.Count.ToString());

            //establish Category tree
            List <string> referenceCategoryPaths = new List <string>();
            foreach (Category category in reference.Categories)
            {
                string[] categoryPaths = category.GetPath(true).Split(new string[] { " > " }, StringSplitOptions.None);
                for (int i = 0; i < categoryPaths.Length; i++)
                {
                    categoryPaths[i] = MakeValidFileName(categoryPaths[i]);
                }
                string categoryPath = String.Join(@"\", categoryPaths);
                referenceCategoryPaths.Add(categoryPath);
            }
            if (!referenceCategoryPaths.Any())
            {
                referenceCategoryPaths.Add("0 No category");
            }

            // create folders if necessary ...

            foreach (string referenceCategoryPath in referenceCategoryPaths)
            {
                string fullPath = exportPath + @"\" + referenceCategoryPath;
                CreateFolderStructure(fullPath);
                // ... and export attachments

                foreach (Location referenceAttachment in referenceAttachments)
                {
                    string sourcePath      = referenceAttachment.AddressUri.AbsoluteUri.GetLocalPathSafe();
                    string destinationPath = fullPath + @"\" + Path.GetFileName(sourcePath);
                    DebugMacro.WriteLine("Copying " + sourcePath + " --> " + destinationPath);

                    //check if source exists
                    if (!File.Exists(sourcePath))
                    {
                        DebugMacro.WriteLine("Source file not found.");
                        errorCounter++;
                        continue;
                    }

                    bool tryAgain = true;
                    while (tryAgain)
                    {
                        try
                        {
                            File.Copy(sourcePath, destinationPath, true);
                            changeCounter++;
                            tryAgain = false;
                        }
                        catch (Exception e)
                        {
                            tryAgain = false;
                            DialogResult directoryError = MessageBox.Show("An error occurred creating a folder: " + e.Message,
                                                                          "Error creating folder", MessageBoxButtons.AbortRetryIgnore,
                                                                          MessageBoxIcon.Error, MessageBoxDefaultButton.Button1);

                            if (directoryError == DialogResult.Abort)
                            {
                                return;
                            }
                            else if (directoryError == DialogResult.Retry)
                            {
                                tryAgain = true;
                            }
                            else
                            {
                                errorCounter++;
                                break;
                            };
                        }
                    }
                }
            }
        }


        activeProject.Save();

        // Message upon completion
        string message = "Finished.\n {0} files copied\n {1} errors occurred";

        message = string.Format(message, changeCounter.ToString(), errorCounter.ToString());
        MessageBox.Show(message, "Macro", MessageBoxButtons.OK, MessageBoxIcon.Information);
    }
    private static DataTable Sheet2DataTable(string fileName, string sheetName, int maxRowCount)
    {
        DataTable       dataTable  = new DataTable();
        OleDbDataReader dataReader = null;
        DataRow         row        = null;

        string selectString = @"SELECT * FROM ["
                              + "{0}"
                              + "]";

        try
        {
            using (OleDbConnection connection = new OleDbConnection(GetConnectionString(fileName)))
            {
                connection.Open();
                object[] o = new Object[] { null, null, null, "TABLE" };
                using (DataTableReader dataReader2 = connection.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, o).CreateDataReader())
                {
                    while (dataReader2.Read())
                    {
                        string sheetName2 = dataReader2["TABLE_NAME"].ToString();
                        if (sheetName2.EndsWith("$") ||
                            sheetName2.EndsWith("$_") ||
                            sheetName2.EndsWith("$'") ||
                            sheetName2.EndsWith("$'_"))
                        {
                            sheetName2 = sheetName2.Remove(sheetName2.IndexOf("$"));
                        }
                        if (sheetName2.StartsWith("'"))
                        {
                            sheetName2 = sheetName2.Remove(0, 1);
                        }
                        if (sheetName == sheetName2)
                        {
                            sheetName = dataReader2["TABLE_NAME"].ToString();
                            break;
                        }
                    }
                }
            }

            DebugMacro.WriteLine(string.Format("Trying to populate Datatable from Worksheet '{0}'", sheetName));

            using (OleDbConnection connection = new OleDbConnection(GetConnectionString(fileName)))
            {
                connection.Open();
                using (OleDbCommand command = new OleDbCommand(string.Format(selectString, sheetName), connection))
                {
                    dataReader = command.ExecuteReader();

                    while (dataReader.Read())
                    {
                        row = dataTable.NewRow();
                        for (int i = 0; i < dataReader.FieldCount; i++)
                        {
                            if (dataTable.Columns.Count == i)
                            {
                                string name = dataReader.GetName(i);
                                if (dataTable.Columns.Contains(name))
                                {
                                    dataTable.Columns.Add("Column" + i.ToString());
                                }
                                else
                                {
                                    dataTable.Columns.Add(name);
                                }
                            }
                            if (dataReader[i] != DBNull.Value)
                            {
                                row[i] = dataReader[i].ToString();
                            }
                            else
                            {
                                row[i] = string.Empty;
                            }
                        }
                        dataTable.Rows.Add(row);
                        maxRowCount--;
                        if (maxRowCount == 0)
                        {
                            break;
                        }
                    }
                }
            }

            row = dataTable.NewRow();
            foreach (DataColumn column in dataTable.Columns)
            {
                row[column] = column.ColumnName;
            }
            dataTable.Rows.InsertAt(row, 0);

            #region Clean


            bool isEmpty = true;
            for (int i = 0; i < dataTable.Columns.Count; i++)
            {
                isEmpty = true;
                for (int i1 = 0; i1 < dataTable.Rows.Count; i1++)
                {
                    if (!string.IsNullOrEmpty(dataTable.Rows[i1][i].ToString()))
                    {
                        isEmpty = false;
                        i1      = dataTable.Rows.Count;
                    }
                }
                if (isEmpty)
                {
                    dataTable.Columns.RemoveAt(i);
                    i--;
                }
            }
            for (int i = 0; i < dataTable.Rows.Count; i++)
            {
                isEmpty = true;
                for (int i1 = 0; i1 < dataTable.Columns.Count; i1++)
                {
                    if (!string.IsNullOrEmpty(dataTable.Rows[i][i1].ToString()))
                    {
                        isEmpty = false;
                        i1      = dataTable.Columns.Count;
                    }
                }
                if (isEmpty)
                {
                    dataTable.Rows.RemoveAt(i);
                    i--;
                }
            }
            #endregion
        }
        catch (Exception ignored)
        {
            MessageBox.Show(ignored.Message);
        }
        finally
        {
            if (dataReader != null && !dataReader.IsClosed)
            {
                dataReader.Close();
            }
        }
        return(dataTable);
    }
    public static void Main()
    {
        bool createMissingReference     = true;
        ReferencePropertyId targetField = ReferencePropertyId.CustomField1;
        string worksheetNameToImport    = "";      //leave empty "" to import first worksheet

        if (IsBackupAvailable() == false)
        {
            return;
        }

        Project   project   = Program.ActiveProjectShell.Project;
        DataTable dataTable = new DataTable();


        string filter           = SwissAcademic.Resources.FileDialogFilters.Excel;
        string fileName         = "";
        string initialDirectory = @"C:\Users\<your name>\Documents";

        //IMPORTANT: Make sure you provide the name of the columns as in the first row of your excel sheet
        string columnNameShortTitle = "Kurztitel";                      //required - needed to identify a reference in the active project
        string columnNameLabel      = "Label";                          //required - field content to import


        //string sheetName in ExcelFetcher.GetWorksheets(_dataExchangeProperty.FileName)
        using (OpenFileDialog dialog = new OpenFileDialog())
        {
            dialog.Filter           = filter;
            dialog.InitialDirectory = initialDirectory;
            dialog.Title            = "Choose EXCEL file with qutations to import";
            if (dialog.ShowDialog() == DialogResult.OK)
            {
                fileName = dialog.FileName;
            }
            else
            {
                return;
            }
        }

        if (string.IsNullOrEmpty(worksheetNameToImport))
        {
            DebugMacro.WriteLine(string.Format("Trying to import first worksheet from '{0}'", fileName));
        }
        else
        {
            DebugMacro.WriteLine(string.Format("Trying to import worksheet '{0}' from '{1}'", worksheetNameToImport, fileName));
        }

        //GetExistingSheetName will either confirm the handed-over sheet "Datenbank"
        //OR just return the first sheet OR empty string if there is no sheet in the workbook
        string sheetName = GetExistingSheetName(worksheetNameToImport, fileName);

        if (string.IsNullOrEmpty(sheetName))
        {
            return;
        }

        dataTable = Sheet2DataTable(fileName, sheetName, -1);
        if (dataTable == null)
        {
            DebugMacro.WriteLine("An error occurred: No datatable was populated.");
        }
        else
        {
            DebugMacro.WriteLine("Datatable successfully populated.");
        }


        //explore columns ...
        DataColumn columnShortTitle = null;         //required
        DataColumn columnLabel      = null;

        //... and generate pointers to specific columns in DataTable
        foreach (DataColumn col in dataTable.Columns)
        {
            if (columnShortTitle == null && col.ToString() == columnNameShortTitle)
            {
                columnShortTitle = col;
                continue;
            }
            if (columnLabel == null && col.ToString() == columnNameLabel)
            {
                columnLabel = col;
                continue;
            }
        }         //end inspecting columns



        //if no shorttitle column return
        if (columnShortTitle == null)
        {
            MessageBox.Show("Could not find required column '" + columnNameShortTitle + "' containing the short title.", "Citavi", MessageBoxButtons.OK, MessageBoxIcon.Warning);
            return;
        }

        if (columnLabel == null)
        {
            MessageBox.Show("Could not find required column '" + columnNameLabel + "' containing the label.", "Citavi", MessageBoxButtons.OK, MessageBoxIcon.Warning);
            return;
        }



        for (int i = 1; i < dataTable.Rows.Count; i++)
        {
            string shortTitle = dataTable.Rows[i][columnShortTitle].ToString();
            string label      = dataTable.Rows[i][columnLabel].ToString();


            //Lambdas don't work in here for some reason
            //Reference parentReference = project.References.Find(item => item.ShortTitle == dataTable.Rows[i][columnShortTitle].ToString);


            if (string.IsNullOrEmpty(shortTitle))
            {
                //no ShortTitle provided, no import possible
                DebugMacro.WriteLine(string.Format("Importing row {0} ... {1}", i.ToString(), "impossible as ShortTitle is empty"));
            }
            else
            {
                //ShortTitle was provided, let's see if we can locate the reference inside the project
                Reference parentReference = GetReferenceWithShortTitle(shortTitle);
                if (parentReference == null)
                {
                    if (createMissingReference)
                    {
                        DebugMacro.WriteLine(string.Format("Importing row {0} ... {1} '{2}'", i.ToString(), "creating new reference with short title", shortTitle));
                        //no such reference, generate it
                        parentReference            = new Reference(project, ReferenceType.Unknown, shortTitle);
                        parentReference.ShortTitle = shortTitle;
                        project.References.Add(parentReference);
                    }
                    else
                    {
                        DebugMacro.WriteLine(string.Format("Importing row {0} ... {1} '{2}'", i.ToString(), "impossible as no reference exists with short title", shortTitle));
                    }
                }
                else
                {
                    DebugMacro.WriteLine(string.Format("Importing row {0} ... {1} '{2}'", i.ToString(), "into existing reference with short title", shortTitle));
                }

                //we now have a parentReference
                if (parentReference != null && !string.IsNullOrEmpty(label))
                {
                    parentReference.SetValue(targetField, label);
                }
            }
        }         //end


        MessageBox.Show("Macro has finished execution.", "Citavi", MessageBoxButtons.OK, MessageBoxIcon.Information);
    }     //static void Main()
    public static void Main()
    {
        //****************************************************************************************************************
        // CHANGE NUMERAL SYSTEM FOR ALL SELECTED REFERENCES
        // 1.0 -- 2017-12-12
        //
        // This macro changes the numeral system of the page ranges from "no numbering type" or "None (as entered)" to Arabic.
        //
        // EDIT HERE
        // Variables to be changed by user



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

        if (Program.ProjectShells.Count == 0)
        {
            return;                                                     //no project open
        }
        if (IsBackupAvailable() == false)
        {
            return;                                                             //user wants to backup his/her project first
        }
        int foundCounter  = 0;
        int changeCounter = 0;
        int errorCounter  = 0;


        //iterate over all references in the current filter (or over all, if there is no filter)
        List <Reference> references = Program.ActiveProjectShell.PrimaryMainForm.GetFilteredReferences();

        //reference to active Project
        Project activeProject = Program.ActiveProjectShell.Project;

        if (activeProject == null)
        {
            return;
        }


        foreach (Reference reference in references)
        {
            foundCounter++;
            var referencePageRange = reference.PageRange;
            try
            {
                if (reference.PageRange.NumeralSystem == NumeralSystem.Omit)
                {
                    PageRange newPageRange = referencePageRange.Update(NumeralSystem.Arabic);
                    reference.PageRange = newPageRange;
                    changeCounter++;
                }
            }
            catch (Exception e)
            {
                MessageBox.Show("An error occurred: " + e.Message, "Citavi Macro", MessageBoxButtons.OK, MessageBoxIcon.Error);
                DebugMacro.WriteLine(e.ToString());
                errorCounter++;
                return;
            }
        }

        //activeProject.Save();

        // Message upon completion
        string message = " {0} reference(s) found\n {1} reference(s) changed\n {2} reference(s) with errors";

        message = string.Format(message, foundCounter.ToString(), changeCounter.ToString(), errorCounter.ToString());
        MessageBox.Show(message, "Macro", MessageBoxButtons.OK, MessageBoxIcon.Information);
    }
Beispiel #22
0
    public static void Main()
    {
        //****************************************************************************************************************
        // This macro checks URLs for validity and sets AccessDate to today's date or the error message of the URL check
        // Version 1.5 -- 2016-01-19
        //
        //
        // EDIT HERE

        int    timeOut       = 3000;  // time in milliseconds until URL check is aborted
        string setToDate     = null;  // if not null, string is used for AccessDate, e.g. setToDate = "05.02.2013", otherwise today's date;
        bool   setDateAlways = false; // if true, AccessDate is set regardless of outcome of URL check

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

        if (Program.ProjectShells.Count == 0)
        {
            return;                                                     //no project open
        }
        if (IsBackupAvailable() == false)
        {
            return;                                                             //user wants to backup his/her project first
        }
        string dateTimeFormat = Program.Engine.Settings.General.DateTimeFormat;
        string newAccessDate  = setToDate;

        if (setToDate == null)
        {
            newAccessDate = DateTime.Today.ToString(dateTimeFormat);
        }

        //iterate over all references in the current filter (or over all, if there is no filter)
        List <Reference> references                = Program.ActiveProjectShell.PrimaryMainForm.GetFilteredReferences();
        List <Reference> referencesWithUrl         = references.Where(reference => !String.IsNullOrEmpty(reference.OnlineAddress)).ToList();
        List <Reference> referencesWithInvalidUrls = new List <Reference>();

        //reference to active Project
        Project activeProject = Program.ActiveProjectShell.Project;

        int    loopCounter    = 0;
        int    changeCounter  = 0;
        int    invalidCounter = 0;
        string urlResult      = null;

        //Welcome message
        DebugMacro.WriteLine(String.Format("Checking links for {0} reference(s) with URLs out of {1} reference(s) in total.", referencesWithUrl.Count.ToString(), references.Count.ToString()));

        foreach (Reference reference in referencesWithUrl)
        {
            loopCounter++;
            DebugMacro.WriteLine(String.Format("Checking {0} of {1}: {2}", loopCounter.ToString(), referencesWithUrl.Count.ToString(), reference.ShortTitle));

            // get URL to check
            string url = reference.OnlineAddress;
            DebugMacro.WriteLine(string.Format("Processing URL '{0}'", url));

            string oldAccessDate = reference.AccessDate;             // get previous last access date

            // Check URL and set fields

            bool urlExists = RemoteFileExists(url, timeOut, out urlResult);

            if (urlExists)
            {
                DebugMacro.WriteLine("URL is valid.");
                reference.Notes     += String.Format(" *** Link {0} checked on {1}: {2}; original access date: {3} ***", reference.OnlineAddress, DateTime.Now.ToString(), urlResult, oldAccessDate);
                reference.AccessDate = newAccessDate;
                changeCounter++;
            }
            else
            {
                DebugMacro.WriteLine("URL is NOT valid: " + urlResult);
                reference.Notes += String.Format(" *** Link {0} checked on {1}: {2}; original access date: {3} ***", reference.OnlineAddress, DateTime.Now.ToString(), urlResult, oldAccessDate);
                if (setDateAlways)
                {
                    reference.AccessDate = newAccessDate;
                }
                invalidCounter++;
                referencesWithInvalidUrls.Add(reference);
            }
        }

        string message = "{0} links checked:\n{1} URLs valid\n{2} URLs not reachable\n Would you like to show a selection with references having an unreachable Online Address?";

        message = string.Format(message, referencesWithUrl.Count.ToString(), changeCounter.ToString(), invalidCounter.ToString());
        DialogResult showSelection = MessageBox.Show(message, "Report", MessageBoxButtons.YesNo, MessageBoxIcon.Information);

        if (showSelection == DialogResult.Yes && referencesWithInvalidUrls.Count > 0)
        {
            ReferenceFilter        filter           = new ReferenceFilter(referencesWithInvalidUrls, "References with invalid URLs", false);
            List <ReferenceFilter> referenceFilters = new List <ReferenceFilter>();
            referenceFilters.Add(filter);
            Program.ActiveProjectShell.PrimaryMainForm.ReferenceEditorFilterSet.Filters.ReplaceBy(referenceFilters);
        }
        else
        {
            return;
        }
    }
Beispiel #23
0
    public static void Main()
    {
        //****************************************************************************************************************
        // REMOVE ALL WEB LOCATIONS
        // 1.1 -- 20156-05-17
        //          -- 1.1: keeps OnlineAddress location by default
        //
        // Removes all [Web] locations for a reference (DOI link can be kept optionally)
        //
        //
        // EDIT HERE
        // Variables to be changed by user

        bool keepDoi           = true; // if false, also DOI links will be removed
        bool keepOnlineAddress = true; // if true, Location will be kept if the URL is stored in the references OnlineAddress field

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

        if (Program.ProjectShells.Count == 0)
        {
            return;                                                     //no project open
        }
        if (IsBackupAvailable() == false)
        {
            return;                                                             //user wants to backup his/her project first
        }
        int foundCounter  = 0;
        int changeCounter = 0;
        int errorCounter  = 0;


        //iterate over all references in the current filter (or over all, if there is no filter)
        List <Reference> references = Program.ActiveProjectShell.PrimaryMainForm.GetFilteredReferences();

        //reference to active Project
        Project activeProject = Program.ActiveProjectShell.Project;

        if (activeProject == null)
        {
            return;
        }


        foreach (Reference reference in references)
        {
            if (reference.Locations == null || reference.Locations.Count == 0)
            {
                continue;
            }

            List <Location> locationsToBeRemoved = new List <Location>();
            foreach (Location location in reference.Locations)
            {
                if (location.LocationType == LocationType.ElectronicAddress)
                {
                    if (location.AddressUri.AddressInfo == ElectronicAddressInfo.RemoteUri)
                    {
                        if (keepOnlineAddress && location.Address == reference.OnlineAddress)
                        {
                            continue;
                        }
                        else if (keepDoi && location.AddressUri.AbsoluteUri.Host == "dx.doi.org")
                        {
                            continue;
                        }
                        else
                        {
                            locationsToBeRemoved.Add(location);
                            foundCounter++;
                        }
                    }
                }
            }

            try
            {
                reference.Locations.RemoveRange(locationsToBeRemoved);
                changeCounter += locationsToBeRemoved.Count;
            }
            catch (Exception e)
            {
                errorCounter += locationsToBeRemoved.Count;
                DebugMacro.WriteLine(reference.ShortTitle + " - An error occurred: " + e.Message);
            }
        }

        activeProject.Save();

        // Message upon completion
        string message = " {0} locations(s) found\n {1} locations(s) removed\n {2} locations(s) with errors";

        message = string.Format(message, foundCounter.ToString(), changeCounter.ToString(), errorCounter.ToString());
        MessageBox.Show(message, "Macro", MessageBoxButtons.OK, MessageBoxIcon.Information);
    }
    public static void Main()
    {
        #region UserVariable
        string journalUrl = @"ftp://ftp.ncbi.nih.gov/pubmed/J_Entrez.txt"; // URL for journal list text file


        #endregion



        if (Program.ProjectShells.Count == 0)
        {
            return;                                                     //no project open
        }
        Project activeProject = Program.ActiveProjectShell.Project;

        List <Periodical> journalCollection = new List <Periodical>();
        string            completeList;

        try
        {
            // Get list of journals from website
            Cursor.Current = Cursors.WaitCursor;
            DebugMacro.WriteLine("Reading list of journals from " + journalUrl);
            WebClient    client       = new WebClient();
            Stream       stream       = client.OpenRead(journalUrl);
            StreamReader streamReader = new StreamReader(stream);
            completeList = streamReader.ReadToEnd();
        }
        catch (Exception e)
        {
            Cursor.Current = Cursors.Default;
            DebugMacro.WriteLine("Could not read file from " + journalUrl + ": " + e.Message);
            return;
        }

        // split into individual Journals


        try
        {
            Cursor.Current = Cursors.WaitCursor;

            string[]      entrySplitters           = { @"--------------------------------------------------------" };
            List <string> individualJournalEntries = new List <string>(completeList.Split(entrySplitters, StringSplitOptions.RemoveEmptyEntries));

            DebugMacro.WriteLine("{0} journal entries found.", individualJournalEntries.Count.ToString());
            DebugMacro.WriteLine("Parsing entries ...");


            int counter = 0;

            Regex splitEntry = new Regex(@"^(?:JrId: )(?<JournalId>\d+?)(?:\nJournalTitle: )(?<JournalTitle>.*?)(?:\nMedAbbr: )(?<Abbreviation2>.*?)(?:\nISSN \(Print\): )(?<IssnPrint>.*?)(?:\nISSN \(Online\): )(?<IssnOnline>.*?)(?:\nIsoAbbr: )(?<Abbreviation1>.*?)(?:\nNlmId: )(?<NlmId>.*?)$",
                                         RegexOptions.CultureInvariant | RegexOptions.Compiled | RegexOptions.Multiline);

            foreach (string journalEntry in individualJournalEntries)
            {
                counter++;

                string journalTitle;
                string abbreviation1; // this one should have full stops
                string abbreviation2; // this one shouldn't
                string abbreviation3; // this one should be any all uppercase acronym after a colon in JournalTitle
                string issnPrint;
                string issnOnline;
                string nlmId;

                // split into fields
                Match m = splitEntry.Match(journalEntry);

                //if (String.IsNullOrEmpty(m.Groups["JournalId"].Value)) continue; // nothing here

                journalTitle  = m.Groups["JournalTitle"].Value;
                abbreviation1 = m.Groups["Abbreviation1"].Value;
                abbreviation2 = m.Groups["Abbreviation2"].Value;
                issnPrint     = m.Groups["IssnPrint"].Value; // to be validated
                issnOnline    = m.Groups["IssnOnline"].Value;
                nlmId         = m.Groups["NlmId"].Value;

                // check format of abbreviation1
                if (String.IsNullOrEmpty(abbreviation1))
                {
                    abbreviation1 = abbreviation2;
                }
                if (!abbreviation1.Contains(".") && !String.IsNullOrEmpty(abbreviation1))
                {
                    string[]      journalTitleWords          = journalTitle.ToLowerInvariant().Split(new char[] { ' ', '.', ';', ',', ':', '&', '-' }, StringSplitOptions.RemoveEmptyEntries);
                    string[]      abbreviation1Words         = abbreviation1.Split(' ');
                    List <string> abbreviation1WithFullStops = new List <string>();


                    foreach (string word in abbreviation1Words)
                    {
                        if (word.StartsWith("(") || word.EndsWith(")"))
                        {
                            abbreviation1WithFullStops.Add(word);
                        }
                        else if (!Array.Exists(journalTitleWords, x => x == word.ToLowerInvariant()))
                        {
                            abbreviation1WithFullStops.Add(word + ".");
                        }
                        else
                        {
                            abbreviation1WithFullStops.Add(word);
                        }
                    }

                    abbreviation1 = String.Join(" ", abbreviation1WithFullStops);
                }

                // try to establish Abbreviation3
                abbreviation3 = Regex.Match(journalTitle, @"(?:: )[A-Z]{2,6}$").ToString();



                Periodical journal = new Periodical(activeProject, journalTitle);
                if (!String.IsNullOrEmpty(abbreviation1))
                {
                    journal.StandardAbbreviation = abbreviation1;
                }
                if (!String.IsNullOrEmpty(abbreviation2))
                {
                    journal.UserAbbreviation1 = abbreviation2;
                }
                if (!String.IsNullOrEmpty(abbreviation3))
                {
                    journal.UserAbbreviation2 = abbreviation3;
                }

                if (!string.IsNullOrEmpty(issnPrint) && IsValidISSN(issnPrint))
                {
                    journal.Issn = issnPrint;
                }
                else if (!string.IsNullOrEmpty(issnOnline) && IsValidISSN(issnOnline))
                {
                    journal.Issn = issnOnline;
                }

                if (!string.IsNullOrEmpty(issnPrint) && IsValidISSN(issnPrint) && !string.IsNullOrEmpty(issnOnline) && IsValidISSN(issnOnline))
                {
                    journal.Notes = "ISSN (Online): " + issnOnline;
                }

                if (!String.IsNullOrEmpty(nlmId))
                {
                    journal.Notes = journal.Notes + "\nNlmID: " + nlmId;
                }

                journalCollection.Add(journal);
            }
            activeProject.Periodicals.AddRange(journalCollection);
        }
        catch (Exception e)
        {
            Cursor.Current = Cursors.Default;
            DebugMacro.WriteLine("An error occurred importing the journal data: " + e.Message);
            return;
        }



        finally
        {
            Cursor.Current = Cursors.Default;
            var saveOptions = new DesktopDatabaseSaveOptions();
            saveOptions.ForceMultiUserUpdate = true;
            activeProject.Save(saveOptions);

            Cursor.Current = Cursors.Default;

            if (journalCollection != null)
            {
                MessageBox.Show(journalCollection.Count.ToString() + " journal(s) were imported (not counting duplicates)", "Citavi", MessageBoxButtons.OK, MessageBoxIcon.Information);
                journalCollection = null;
            }
        }
    }     //end Main()
    public static void Main()
    {
        #region UserVariable
        string journalUrl = @"http://journal-abbreviations.library.ubc.ca/dump.php"; // URL for journal list text file


        #endregion



        if (Program.ProjectShells.Count == 0)
        {
            return;                                                     //no project open
        }
        Project activeProject = Program.ActiveProjectShell.Project;

        List <Periodical> journalCollection = new List <Periodical>();
        string            completeList;
        try
        {
            // Get list of journals from website
            Cursor.Current = Cursors.WaitCursor;
            DebugMacro.WriteLine("Reading list of journals from " + journalUrl);
            WebClient    client       = new WebClient();
            Stream       stream       = client.OpenRead(journalUrl);
            StreamReader streamReader = new StreamReader(stream);
            completeList = streamReader.ReadToEnd();
        }
        catch (Exception e)
        {
            Cursor.Current = Cursors.Default;
            DebugMacro.WriteLine("Could not read file from " + journalUrl + ": " + e.Message);
            return;
        }


        // split into individual Journals
        int counter    = 0;
        int refCounter = 0;


        try
        {
            Cursor.Current = Cursors.WaitCursor;

            // prepare data
            completeList = Regex.Match(completeList, @"(<tbody>.*?<\\/tbody)").ToString();
            completeList = Regex.Replace(completeList, @"\\/", @"/");


            MatchCollection journals = Regex.Matches(completeList, "(?<=<tr>).*?(?=</tr>)");
            DebugMacro.WriteLine("{0} journal entries found.", journals.Count.ToString());
            DebugMacro.WriteLine("Parsing entries ...");

            foreach (Match journalAndAbbrev in journals)
            {
                string journalTitle  = String.Empty;
                string abbreviation1 = String.Empty; // this one should have full stops
                string abbreviation2 = String.Empty; // this one shouldn't
                string abbreviation3;                // this one should be any all uppercase acronym after a colon in JournalTitl

                MatchCollection journalData = Regex.Matches(journalAndAbbrev.ToString(), "(?<=<td>).*?(?=</td>)");
                if (journalData.Count < 2)
                {
                    continue;
                }

                abbreviation1 = journalData[0].Value;
                journalTitle  = Regex.Replace(journalData[1].Value, @"\bfur\b", "für");

                // generate abbreviation2 by removing full stops from abbreviation1
                string[] abbreviation1Words = abbreviation1.Split(' ');
                for (int i = 0; i < abbreviation1Words.Length; i++)
                {
                    abbreviation1Words[i] = abbreviation1Words[i].TrimEnd('.');
                }
                abbreviation2 = String.Join(" ", abbreviation1Words);


                // try to establish Abbreviation3
                abbreviation3 = Regex.Match(journalTitle, @"(?:: )[A-Z]{2,6}$").ToString();



                Periodical journal = new Periodical(activeProject, journalTitle);
                if (!String.IsNullOrEmpty(abbreviation1))
                {
                    journal.StandardAbbreviation = abbreviation1;
                }
                if (!String.IsNullOrEmpty(abbreviation2))
                {
                    journal.UserAbbreviation1 = abbreviation2;
                }
                if (!String.IsNullOrEmpty(abbreviation3))
                {
                    journal.UserAbbreviation2 = abbreviation3;
                }

                journalCollection.Add(journal);
            }

            DialogResult updateReferences = MessageBox.Show(
                @"Would you like to update journal information for references in current selection (all references if no selection is active)?",
                "Citavi Macro", MessageBoxButtons.YesNo, MessageBoxIcon.Question,
                MessageBoxDefaultButton.Button2);


            // update references that have identical titles
            if (updateReferences == DialogResult.Yes)
            {
                List <Reference> references = Program.ActiveProjectShell.PrimaryMainForm.GetFilteredReferences();
                foreach (Reference reference in references)
                {
                    if (reference.Periodical == null)
                    {
                        continue;
                    }
                    if (journalCollection.Any(item => item.Name == reference.Periodical.Name) && !String.IsNullOrEmpty(reference.Periodical.Name))
                    {
                        reference.Periodical = journalCollection.Where(item => item.Name == reference.Periodical.Name).FirstOrDefault();
                        refCounter++;
                    }
                }
                activeProject.Periodicals.AddRange(journalCollection);
            }
            else
            {
                activeProject.Periodicals.AddRange(journalCollection);
            }
        }
        catch (Exception e)
        {
            Cursor.Current = Cursors.Default;
            DebugMacro.WriteLine("An error occurred importing the journal data: " + e.ToString());
            return;
        }

        finally
        {
            Cursor.Current = Cursors.Default;
            var saveOptions = new DesktopDatabaseSaveOptions();
            saveOptions.ForceMultiUserUpdate = true;
            activeProject.Save(saveOptions);

            Cursor.Current = Cursors.Default;

            if (journalCollection != null)
            {
                MessageBox.Show(journalCollection.Count.ToString() + " journal(s) were imported (not counting duplicates)\n " + refCounter.ToString() + " reference(s) were changed.", "Citavi", MessageBoxButtons.OK, MessageBoxIcon.Information);
                journalCollection = null;
            }
        }
    }     //end Main()
Beispiel #26
0
    public static void Main()
    {
        //****************************************************************************************************************
        // Normalize Capitalization of All Upper Case Author Names
        // 1.2 -- 2018-01-22
        //
        // This macro checks all author names if they are stored in capital letters (SMITH, JOHN A.) and normalises
        // the name to mixed case (Smith, John A.).
        //
        // v1.1 - names with captial last names only are also normalized if option is set
        // v1.2 - better error handling

        // EDIT HERE
        // Variables to be changed by user

        bool prefixSuffixFirstCapitalLetter = false; // capitalize the first letter of name prefixes/suffixes
        bool normalizeCapitalLastname       = true;  // if true macro will work if only last name is in capital letters, e.g. "HUBER, David"

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


        int counter = 0;

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

        //get names and exit if none are present
        Person[] authors = activeProject.Persons.ToArray();
        if (!authors.Any())
        {
            return;
        }

        // RegEx search and replace in every category name
        foreach (Person author in authors)
        {
            // get full name and check if it is all upper case
            string originalAuthorFullName = author.FullName.ToString();
            string originalAuthorLastName = author.LastName.ToString();

            if (originalAuthorFullName == author.FullName.ToUpper() ||
                (originalAuthorLastName == author.LastName.ToUpper() && normalizeCapitalLastname))
            {
                counter++;

                // get name parts as strings
                string authorPrefix     = author.Prefix.ToString();
                string authorFirstName  = author.FirstName.ToString();
                string authorMiddleName = author.MiddleName.ToString();
                string authorLastName   = author.LastName.ToString();
                string authorSuffix     = author.Suffix.ToString();

                string authorFirstNameNormal  = String.Empty;
                string authorMiddleNameNormal = String.Empty;
                string authorLastNameNormal   = String.Empty;

                try
                {
                    // normalise the strings to initial upper case
                    if (!String.IsNullOrEmpty(authorFirstName))
                    {
                        authorFirstNameNormal = authorFirstName.ToLower().ToInitialUpper();
                    }
                    if (!String.IsNullOrEmpty(authorMiddleName))
                    {
                        authorMiddleNameNormal = authorMiddleName.ToLower().ToInitialUpper();
                    }
                    if (!String.IsNullOrEmpty(authorLastName))
                    {
                        authorLastNameNormal = authorLastName.ToLower().ToInitialUpper();
                    }
                }
                catch (Exception e)
                {
                    DebugMacro.WriteLine("An error occurred with " + author.FullName + ": " + e.Message);
                    counter--;
                    continue;
                }


                // Prefix/Suffix get initial lower case unless prefixSuffixFirstCapitalLetter is true
                string authorPrefixNormal = String.Empty;
                string authorSuffixNormal = String.Empty;

                if (prefixSuffixFirstCapitalLetter == true)
                {
                    try
                    {
                        if (!String.IsNullOrEmpty(authorPrefix))
                        {
                            authorPrefixNormal = authorPrefix.ToLower().ToInitialUpper();
                        }
                        if (!String.IsNullOrEmpty(authorSuffix))
                        {
                            authorSuffixNormal = authorSuffix.ToLower().ToInitialUpper();
                        }
                    }
                    catch (Exception e)
                    {
                        DebugMacro.WriteLine("An error occurred with " + author.FullName + ": " + e.Message);
                        counter--;
                        continue;
                    }
                }
                else
                {
                    authorPrefixNormal = authorPrefix.ToLower();
                    authorSuffixNormal = authorSuffix.ToLower();
                }

                // change author
                if (!String.IsNullOrEmpty(authorPrefixNormal))
                {
                    author.Prefix = authorPrefixNormal;
                }
                if (!String.IsNullOrEmpty(authorFirstNameNormal))
                {
                    author.FirstName = authorFirstNameNormal;
                }
                if (!String.IsNullOrEmpty(authorMiddleNameNormal))
                {
                    author.MiddleName = authorMiddleNameNormal;
                }
                if (!String.IsNullOrEmpty(authorLastNameNormal))
                {
                    author.LastName = authorLastNameNormal;
                }
                if (!String.IsNullOrEmpty(authorSuffixNormal))
                {
                    author.Suffix = authorSuffixNormal;
                }
            }
        }

        // Message upon completion
        string message = "{0} names have been normalised.";

        message = string.Format(message, counter.ToString());
        MessageBox.Show(message, "Citavi Macro", MessageBoxButtons.OK, MessageBoxIcon.Information);
    }
Beispiel #27
0
    public static void Main()
    {
        //****************************************************************************************************************
        // Select Knowledge Items without Entity Links (Annotations)
        // 1.0 - 2020-07-28
        //
        //
        // EDIT HERE
        // Variables to be changed by user


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

        if (Program.ProjectShells.Count == 0)
        {
            return;                                                     //no project open
        }
        //reference to active Project
        Project activeProject = Program.ActiveProjectShell.Project;

        List <KnowledgeItem> allKis = activeProject.AllKnowledgeItems.ToList();

        List <KnowledgeItem> noEntityLink = new List <KnowledgeItem>();

        try
        {
            foreach (KnowledgeItem ki in allKis)
            {
                if (ki.QuotationType == QuotationType.None || ki.QuotationType == QuotationType.Highlight)
                {
                    continue;
                }
                if (ki.EntityLinks == null || ki.EntityLinks.Count() == 0)
                {
                    noEntityLink.Add(ki);
                }
            }


            if (noEntityLink.Count > 0)
            {
                noEntityLink = noEntityLink.Distinct().ToList();
                KnowledgeItemFilter        kiFilter  = new KnowledgeItemFilter(noEntityLink, "Knowledge items without entity links", false);
                List <KnowledgeItemFilter> kiFilters = new List <KnowledgeItemFilter>();
                kiFilters.Add(kiFilter);
                Program.ActiveProjectShell.PrimaryMainForm.KnowledgeOrganizerFilterSet.Filters.ReplaceBy(kiFilters);
            }
        }
        catch (Exception e)
        {
            DebugMacro.WriteLine("An error occurred: " + e.Message);
        }
        finally
        {
            if (noEntityLink.Count == 0)
            {
                MessageBox.Show("No such KI found.", "Macro", MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
            else
            {
                MessageBox.Show(string.Format("{0} reference(s) in new selection", noEntityLink.Count), "Macro", MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
        }
    }
Beispiel #28
0
    public static void Main()
    {
        //****************************************************************************************************************
        // EXPORT ATTACHMENTS TO CATEGORY FOLDER STRUCTURE
        // V1.5 -- 2019-05-29   - option for creating Location in Citavi for each exported file
        // v1.6 -- 2019-06-04   - folder for attachments without categories

        // EDIT HERE
        // Variables to be changed by user

        bool createFoldersForAllCategories  = true; // set to false if only category folders for references with attachments are required
        bool createLocationForExportedFiles = true; // create a new Location in the Citavi project that points to the exported file
                                                    // local projects only

        string noCategoryFolder = "0 No Category";  // Name of the folder for attachments without categories

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

        if (Program.ProjectShells.Count == 0)
        {
            return;                                                 //no project open
        }
        int foundCounter  = 0;
        int changeCounter = 0;
        int errorCounter  = 0;

        //iterate over all references in the current filter (or over all, if there is no filter)
        List <Reference> references = Program.ActiveProjectShell.PrimaryMainForm.GetFilteredReferences();

        if (references == null)
        {
            return;
        }

        //reference to active Project
        Project activeProject  = Program.ActiveProjectShell.Project;
        bool    isCloudProject = activeProject.DesktopProjectConfiguration.ProjectType == ProjectType.DesktopCloud;

        if (activeProject == null)
        {
            return;
        }

        //get root folder to export to
        string exportPath;
        FolderBrowserDialog folderDialog = new FolderBrowserDialog();

        folderDialog.Description  = "Please select root folder for export";
        folderDialog.SelectedPath = System.Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
        if (folderDialog.ShowDialog() == DialogResult.OK)
        {
            exportPath = folderDialog.SelectedPath;
        }
        else
        {
            return;
        }


        // create category structure as folder structure if all categories are required

        if (createFoldersForAllCategories)
        {
            DebugMacro.WriteLine("Creating category folder structure ...");

            List <Category> allCategories    = activeProject.AllCategories.ToList();
            List <string>   allCategoryPaths = new List <string>();

            foreach (Category category in allCategories)
            {
                string[] categoryPaths = category.GetPath(true).Split(new string[] { " > " }, StringSplitOptions.None);
                for (int i = 0; i < categoryPaths.Length; i++)
                {
                    categoryPaths[i] = MakeValidFileName(categoryPaths[i]);
                }
                string categoryPath = String.Join(@"\", categoryPaths);
                allCategoryPaths.Add(categoryPath);
            }

            foreach (string categoryPath in allCategoryPaths)
            {
                string fullPath = exportPath + @"\" + categoryPath;
                CreateFolderStructure(fullPath);
            }
        }

        // export reference Attachments

        foreach (Reference reference in references)
        {
            DebugMacro.WriteLine("Processing references ...");
            DebugMacro.WriteLine("Processing " + reference.ShortTitle + " ... ");

            //establish whether or not there are ATTACHMENTS
            List <Location>             referenceAttachments = new List <Location>();
            ReferenceLocationCollection referenceLocations   = reference.Locations;
            foreach (Location location in referenceLocations)
            {
                if (location.LocationType == LocationType.ElectronicAddress &&
                    (location.Address.LinkedResourceType == LinkedResourceType.AttachmentRemote ||
                     location.Address.LinkedResourceType == LinkedResourceType.AttachmentFile ||
                     location.Address.LinkedResourceType == LinkedResourceType.AbsoluteFileUri ||
                     location.Address.LinkedResourceType == LinkedResourceType.RelativeFileUri))
                {
                    referenceAttachments.Add(location);
                }
            }
            if (referenceAttachments == null || referenceAttachments.Count == 0)
            {
                continue;
            }

            DebugMacro.WriteLine("Number of attachments found: " + referenceAttachments.Count.ToString());

            //establish Category tree
            List <string> referenceCategoryPaths = new List <string>();
            foreach (Category category in reference.Categories)
            {
                string[] categoryPaths = category.GetPath(true).Split(new string[] { " > " }, StringSplitOptions.None);
                for (int i = 0; i < categoryPaths.Length; i++)
                {
                    categoryPaths[i] = MakeValidFileName(categoryPaths[i]);
                }
                string categoryPath = String.Join(@"\", categoryPaths);
                referenceCategoryPaths.Add(categoryPath);
            }
            if (!referenceCategoryPaths.Any())
            {
                referenceCategoryPaths.Add(noCategoryFolder);
            }

            // create folders if necessary ...

            foreach (string referenceCategoryPath in referenceCategoryPaths)
            {
                string fullPath = exportPath + @"\" + referenceCategoryPath;

                CreateFolderStructure(fullPath);

                // ... and export attachments

                foreach (Location referenceAttachment in referenceAttachments)
                {
                    //string sourcePath = referenceAttachment.AddressUri.AbsoluteUri.GetLocalPathSafe();

                    Uri    sourceUri       = referenceAttachment.Address.Resolve();
                    string sourcePath      = sourceUri.LocalPath;
                    string destinationPath = String.Empty;

                    if (referenceAttachment.Address.LinkedResourceType == LinkedResourceType.AttachmentRemote)
                    {
                        if (referenceAttachment.Address.LinkedResourceStatus != LinkedResourceStatus.Attached)
                        {
                            continue;
                        }
                        if (referenceAttachment.Address.CachingStatus != CachingStatus.Available)
                        {
                            continue;
                        }

                        destinationPath = fullPath + @"\" + referenceAttachment.FullName;
                    }
                    else
                    {
                        destinationPath = fullPath + @"\" + Path.GetFileName(sourcePath);
                    }

                    DebugMacro.WriteLine("Copying " + sourcePath + " --> " + destinationPath);

                    //check if source exists
                    if (!File.Exists(sourcePath))
                    {
                        DebugMacro.WriteLine("Source file not found.");
                        errorCounter++;
                        continue;
                    }

                    bool tryAgain = true;
                    bool success  = false;
                    while (tryAgain)
                    {
                        try
                        {
                            File.Copy(sourcePath, destinationPath, true);
                            changeCounter++;
                            tryAgain = false;
                            success  = true;
                        }
                        catch (Exception e)
                        {
                            tryAgain = false;
                            DialogResult directoryError = MessageBox.Show("An error occurred creating a folder: " + e.Message,
                                                                          "Error creating folder", MessageBoxButtons.AbortRetryIgnore,
                                                                          MessageBoxIcon.Error, MessageBoxDefaultButton.Button1);

                            if (directoryError == DialogResult.Abort)
                            {
                                return;
                            }
                            else if (directoryError == DialogResult.Retry)
                            {
                                tryAgain = true;
                            }
                            else
                            {
                                errorCounter++;
                                break;
                            };
                        }
                    }

                    if (createLocationForExportedFiles && success && !isCloudProject)
                    {
                        CreateLocation(reference, destinationPath);
                    }
                }
            }
        }



        // Message upon completion
        string message = "Finished.\n {0} files copied\n {1} thought files created\n {2} errors occurred";

        message = string.Format(message, changeCounter.ToString(), foundCounter.ToString(), errorCounter.ToString());
        MessageBox.Show(message, "Macro", MessageBoxButtons.OK, MessageBoxIcon.Information);
    }
    public static void Main()
    {
        //****************************************************************************************************************
        // ADD REFERENCE CATEGORIES, KEYWORDS AND GROUPS TO KNOWLEDGE ITEMS AND VICE VERSA
        // 2.0 -- 2017-03-16
        //
        //
        // EDIT HERE
        // Variables to be changed by user

        // choose direction
        int direction = 1; // 1 for reference -> knowledge item, 2 for knowledge item -> reference

        // set one or several of the following to true
        bool setCategories = false;
        bool setKeywords   = false;
        bool setGroups     = false;

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

        if (Program.ProjectShells.Count == 0)
        {
            return;                                                     //no project open
        }
        if (IsBackupAvailable() == false)
        {
            return;                                                             //user wants to backup his/her project first
        }
        // wrong direction
        if (direction != 1 && direction != 2)
        {
            DebugMacro.WriteLine("Direction not set correctly, please change line 29 in the code!");
            return;
        }

        //iterate over all references in the current filter (or over all, if there is no filter)
        List <Reference> references = Program.ActiveProjectShell.PrimaryMainForm.GetFilteredReferences();

        //reference to active Project
        Project activeProject = Program.ActiveProjectShell.Project;

        if (activeProject == null)
        {
            return;
        }


        //counters

        int categoryCounter = 0;
        int keywordCounter  = 0;
        int groupCounter    = 0;
        int errorCounter    = 0;

        foreach (Reference reference in references)
        {
            foreach (KnowledgeItem knowledgeItem in reference.Quotations)
            {
                if (knowledgeItem.Reference == null)
                {
                    continue;                                                  // ignore Ideas
                }
                if (knowledgeItem.QuotationType == QuotationType.Highlight)
                {
                    continue;                                                                         // ignore highlights
                }
                if (setCategories)
                {
                    try
                    {
                        List <Category> kiCategories  = knowledgeItem.Categories.ToList();
                        List <Category> refCategories = knowledgeItem.Reference.Categories.ToList();

                        List <Category> mergedCategories = kiCategories.Union(refCategories).ToList();
                        mergedCategories.Sort();

                        switch (direction)
                        {
                        case 1:
                            knowledgeItem.Categories.Clear();
                            knowledgeItem.Categories.AddRange(mergedCategories);
                            categoryCounter++;
                            break;

                        case 2:
                            reference.Categories.Clear();
                            reference.Categories.AddRange(mergedCategories);
                            categoryCounter++;
                            break;
                        }
                    }
                    catch (Exception e)
                    {
                        string errorString = String.Format("An error occurred with knowledge item '{0}' in reference {1}:\n  {2}", knowledgeItem.CoreStatement, reference.ShortTitle, e.Message);
                        DebugMacro.WriteLine(errorString);
                        errorCounter++;
                    }
                }

                if (setKeywords)
                {
                    try
                    {
                        List <Keyword> kiKeywords  = knowledgeItem.Keywords.ToList();
                        List <Keyword> refKeywords = reference.Keywords.ToList();

                        List <Keyword> mergedKeywords = kiKeywords.Union(refKeywords).ToList();
                        mergedKeywords.Sort();

                        switch (direction)
                        {
                        case 1:
                            knowledgeItem.Keywords.Clear();
                            knowledgeItem.Keywords.AddRange(mergedKeywords);
                            keywordCounter++;
                            break;

                        case 2:
                            reference.Keywords.Clear();
                            reference.Keywords.AddRange(mergedKeywords);
                            keywordCounter++;
                            break;
                        }
                    }

                    catch (Exception e)
                    {
                        string errorString = String.Format("An error occurred with knowledge item '{0}' in reference {1}:\n  {2}", knowledgeItem.CoreStatement, reference.ShortTitle, e.Message);
                        DebugMacro.WriteLine(errorString);
                        errorCounter++;
                    }
                }

                if (setGroups)
                {
                    try
                    {
                        List <Group> kiGroups  = knowledgeItem.Groups.ToList();
                        List <Group> refGroups = reference.Groups.ToList();

                        List <Group> mergedGroups = kiGroups.Union(refGroups).ToList();
                        mergedGroups.Sort();

                        switch (direction)
                        {
                        case 1:
                            knowledgeItem.Groups.Clear();
                            knowledgeItem.Groups.AddRange(mergedGroups);
                            groupCounter++;
                            break;

                        case 2:
                            reference.Groups.Clear();
                            reference.Groups.AddRange(mergedGroups);
                            groupCounter++;
                            break;
                        }
                    }
                    catch (Exception e)
                    {
                        string errorString = String.Format("An error occurred with knowledge item '{0}' in reference {1}:\n  {2}", knowledgeItem.CoreStatement, reference.ShortTitle, e.Message);
                        DebugMacro.WriteLine(errorString);
                        errorCounter++;
                    }
                }
            }
        }

        activeProject.Save();

        // Message upon completion
        string message = String.Empty;

        switch (direction)
        {
        case 1:
            message = "On {0} knowledge items categories have been changed,\n on {1} knowledge items keywords have been changed,\n on {2} knowledge items groups have been changed.\n {3} errors occurred.";
            break;

        case 2:
            message = "On {0} references categories have been changed,\n on {1} references keywords have been changed,\n on {2} references groups have been changed.\n {3} errors occurred.";
            break;
        }

        message = string.Format(message, categoryCounter.ToString(), keywordCounter.ToString(), groupCounter.ToString(), errorCounter.ToString());

        MessageBox.Show(message, "Macro", MessageBoxButtons.OK, MessageBoxIcon.Information);
    }
Beispiel #30
0
    public static void Main()
    {
        //****************************************************************************************************************
        // CSV-Table Showing the Categories for Each Title
        // 1.1 -- 2015-08-07
        //

        // This macro writes a tab delimited CSV file showing for each reference which categories are assigned to that
        // reference. Import the file into Excel using the "From text" function in the DATA tab.
        // In the variable "categoryPresent" you can set the text that occurs in a cell if a category is present
        // for a certain reference.
        //
        //
        // EDIT HERE
        // Variables to be changed by user

        string categoryPresent = "Yes.";         // string to put in table cell if category is present

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

        ProjectShell activeProjectShell = Program.ActiveProjectShell;

        if (activeProjectShell == null)
        {
            return;                                     //no open project shell
        }
        Project activeProject = Program.ActiveProjectShell.Project;

        if (activeProject == null)
        {
            return;
        }

        Form primaryMainForm = activeProjectShell.PrimaryMainForm;

        if (primaryMainForm == null)
        {
            return;
        }

        if (Program.ProjectShells.Count == 0)
        {
            return;                                                     //no project open
        }
        //iterate over all references in the current filter (or over all, if there is no filter)
        List <Reference> references = Program.ActiveProjectShell.PrimaryMainForm.GetFilteredReferences();



        //reference to all Categories in the project
        Category[] allCategories = activeProject.AllCategories.ToArray();
        Array.Sort(allCategories);

        // abort if no categories/references present
        if (!allCategories.Any() || !references.Any())
        {
            DebugMacro.WriteLine("No categories or references in current project.");
            return;
        }

        string file = string.Empty;


        string initialDirectory = Environment.GetFolderPath(Environment.SpecialFolder.Personal);

        using (SaveFileDialog saveFileDialog = new SaveFileDialog())
        {
            saveFileDialog.Filter           = "CSV files (*.csv, *.txt)|*.csv;*.txt|All files (*.*)|*.*";
            saveFileDialog.InitialDirectory = initialDirectory;
            saveFileDialog.Title            = "Enter a file name for the CSV file.";

            if (saveFileDialog.ShowDialog(primaryMainForm) != DialogResult.OK)
            {
                return;
            }
            file = saveFileDialog.FileName;
        }


        // create file, delete if already present
        StreamWriter sw = null;


        try
        {
            sw = File.AppendText(file);
        }
        catch (Exception e)
        {
            DebugMacro.WriteLine("Error creating file: " + e.Message.ToString());
            return;
        }


        // write line with categories to file
        string headline = "\t \t \t";

        foreach (Category category in allCategories)
        {
            string cString = category.ToString() + "\t";
            headline = headline + cString;
        }
        headline = headline + "\n";
        sw.WriteLine(headline);


        // check categories for each reference
        foreach (Reference reference in references)
        {
            // write author, year and title to file
            string author = reference.AuthorsOrEditorsOrOrganizations.ToString();
            string year   = reference.YearResolved.ToString();
            string title  = reference.Title.ToString();
            string line   = author + "\t" + year + "\t" + title + "\t";

            // iterate over all Categories and Categories of each reference and write
            // categoryPresent string to file if category is present
            Category[] referenceCategories = reference.Categories.ToArray();
            Array.Sort(referenceCategories);
            foreach (Category category in allCategories)
            {
                foreach (Category referenceCategory in referenceCategories)
                {
                    if (referenceCategory == category)
                    {
                        line = line + categoryPresent;
                    }
                }
                line = line + "\t";
            }
            line = line + "\n";
            sw.WriteLine(line);
        }

        // close file
        sw.Close();

        // Message upon completion
        string message = "CSV file written to " + file;

        MessageBox.Show(message, "Macro", MessageBoxButtons.OK, MessageBoxIcon.Information);
    }