Пример #1
0
 private bool HasFieldElement(Template template, ReferencePropertyId propertyId)
 {
     if (template == null)
     {
         return(false);
     }
     if (propertyId == ReferencePropertyId.None)
     {
         return(false);
     }
     foreach (var element in template.Elements)
     {
         if (element is FieldElement && ((FieldElement)element).PropertyId == propertyId)
         {
             return(true);
         }
     }
     return(false);
 }
        public IEnumerable <ITextUnit> GetTextUnits(ComponentPart componentPart, Template template, Citation citation, out bool handled)
        {
            handled = false;

            if (componentPart == null)
            {
                return(null);
            }
            if (citation == null)
            {
                return(null);
            }
            if (citation.Reference == null)
            {
                return(null);
            }

            if (componentPart.Scope == ComponentPartScope.ParentReference && citation.Reference.ParentReference == null)
            {
                return(null);
            }
            var referenceInScopeOfComponentPart = componentPart.Scope == ComponentPartScope.ParentReference ? citation.Reference.ParentReference : citation.Reference;



            //check for the first custom field in the componentPart ... we expect this to be the field where the publication media type ist stored
            ReferencePropertyId[] customFieldProperties = new ReferencePropertyId[]
            {
                ReferencePropertyId.CustomField1,
                ReferencePropertyId.CustomField2,
                ReferencePropertyId.CustomField3,
                ReferencePropertyId.CustomField4,
                ReferencePropertyId.CustomField5,
                ReferencePropertyId.CustomField6,
                ReferencePropertyId.CustomField7,
                ReferencePropertyId.CustomField8,
                ReferencePropertyId.CustomField9
            };
            TextFieldElement customFieldElement = componentPart.GetFieldElements().OfType <TextFieldElement>().FirstOrDefault(fieldElement => customFieldProperties.Contains(fieldElement.PropertyId));

            if (customFieldElement == null)
            {
                return(null);
            }

            //check if corresponding reference field contains data
            var mediaType = referenceInScopeOfComponentPart.GetValue(customFieldElement.PropertyId) as string;

            if (string.IsNullOrEmpty(mediaType))
            {
                return(null);
            }

            //the following words should be output in italics
            var specialMediaTypes = new string[] {
                "iPad",
                "Kindle",
                "Microsoft",
                "Word",
                "PowerPoint",
                "Excel",
                "Nook",
                "Sony",
                "Adobe"
            };

            var regEx = new Regex(@"\b(" + string.Join("|", specialMediaTypes) + @")\b", RegexOptions.IgnoreCase);

            if (regEx.IsMatch(mediaType))
            {
                var words = mediaType.Split(' ');
                var newLiteralElements = new List <LiteralElement>();


                for (int i = 0; i < words.Count(); i++)
                {
                    var word = words[i];
                    if (string.IsNullOrWhiteSpace(word))
                    {
                        continue;
                    }

                    LiteralElement newLiteralElement = null;
                    if (i < words.Count() - 1)
                    {
                        newLiteralElement = new LiteralElement(componentPart, word + " ");
                    }
                    else
                    {
                        newLiteralElement = new LiteralElement(componentPart, word);
                    }

                    if (specialMediaTypes.Contains(word))
                    {
                        newLiteralElement.FontStyle = SwissAcademic.Drawing.FontStyle.Italic;
                    }
                    else
                    {
                        newLiteralElement.FontStyle = SwissAcademic.Drawing.FontStyle.Neutral;
                    }

                    newLiteralElements.Add(newLiteralElement);
                }


                var index = componentPart.Elements.IndexOf(customFieldElement);
                componentPart.Elements.RemoveAt(index);
                componentPart.Elements.InsertElements(index, newLiteralElements);
                foreach (var element in componentPart.Elements.OfType <LiteralElement>())
                {
                    element.ApplyCondition = ElementApplyCondition.Always;
                }
                //componentPart.Elements.ReplaceItem(customFieldElement, newLiteralElements);
            }

            return(null);
        }
Пример #3
0
        //Version 2.0 script can be attached to both date/time field element as well as text field element

        //Format date range (if applicable)
        //Enter date range as: dd.MM.yyyy - dd.MM.yyyy
        //Format it to: dd.-dd. MMMM yyyy e.g.

        public IEnumerable <ITextUnit> GetTextUnits(ComponentPart componentPart, Template template, Citation citation, out bool handled)
        {
            CultureInfo targetCulture = CultureInfo.CreateSpecificCulture("de-DE");

            handled = false;

            if (citation == null)
            {
                return(null);
            }
            if (citation.Reference == null)
            {
                return(null);
            }

            if (componentPart == null)
            {
                return(null);
            }
            if (componentPart.Elements == null || componentPart.Elements.Count != 1)
            {
                return(null);
            }

            FieldElement firstDateContainingFieldElement = componentPart.Elements.Where(element =>
            {
                DateTimeFieldElement dateTimeFieldElement = element as DateTimeFieldElement;
                if (dateTimeFieldElement != null)
                {
                    return(true);
                }

                TextFieldElement textFieldElement = element as TextFieldElement;
                if (textFieldElement != null)
                {
                    return(true);
                }

                return(false);
            }).FirstOrDefault() as FieldElement;

            if (firstDateContainingFieldElement == null)
            {
                return(null);
            }

            ReferencePropertyId referencePropertyId = firstDateContainingFieldElement.PropertyId;

            Reference referenceResolved = componentPart.Scope == ComponentPartScope.ParentReference ? citation.Reference.ParentReference : citation.Reference;

            if (referenceResolved == null)
            {
                return(null);
            }

            string date = referenceResolved.GetValue(referencePropertyId) as string;

            if (string.IsNullOrEmpty(date))
            {
                return(null);
            }

            FontStyle fontStyle =
                firstDateContainingFieldElement is DateTimeFieldElement ?
                ((DateTimeFieldElement)firstDateContainingFieldElement).FontStyle :
                ((TextFieldElement)firstDateContainingFieldElement).FontStyle;

            DateTime dateSingle;
            DateTime dateA;
            DateTime dateB;

            CultureInfo deDE = new CultureInfo("de-DE");

            string[] formats = new string[] { "dd.MM.yyyy", "d.M.yyyy", "d.MM.yyyy", "dd.M.yyyy", "dd.MM.yy", "d.M.yy", "d.MM.yy", "dd.M.yy" };


            //try single date first
            var found = DateTime.TryParseExact(date, formats, deDE, DateTimeStyles.None, out dateSingle);

            if (found)
            {
                var monthStringShort = dateSingle.ToString("MMM", targetCulture);
                var monthStringLong  = dateSingle.ToString("MMMM", targetCulture);
                var monthString      = monthStringShort == monthStringLong ? monthStringShort : monthStringShort + ".";

                var yearString = dateSingle.ToString("yyyy");

                var dayString = dateSingle.Day.ToString("D2");

                var outputFormatSingle = "{0} {1}, {2}";
                var dateSingleText     = string.Format(outputFormatSingle, monthString, dayString, yearString);

                var outputSingleDate = new TextUnitCollection();
                var textSingleDate   = new LiteralTextUnit(dateSingleText);
                textSingleDate.FontStyle = fontStyle;
                outputSingleDate.Add(textSingleDate);
                handled = true;
                return(outputSingleDate);
            }

            //then try date range
            List <string> dates = date.Split('-').Select(d => d.Trim()).ToList();

            if (dates.Count != 2)
            {
                return(null);
            }


            var foundA = DateTime.TryParseExact(dates.ElementAt(0), formats, deDE, DateTimeStyles.None, out dateA);
            var foundB = DateTime.TryParseExact(dates.ElementAt(1), formats, deDE, DateTimeStyles.None, out dateB);

            if (!foundA || !foundB)
            {
                return(null);
            }


            var monthAStringShort = dateA.ToString("MMM", targetCulture);
            var monthAStringLong  = dateA.ToString("MMMM", targetCulture);
            var monthAString      = monthAStringShort == monthAStringLong ? monthAStringShort : monthAStringShort + ".";

            var monthBStringShort = dateB.ToString("MMM", targetCulture);
            var monthBStringLong  = dateB.ToString("MMMM", targetCulture);
            var monthBString      = monthBStringShort == monthBStringLong ? monthBStringShort : monthBStringShort + ".";

            var yearAString = dateA.ToString("yyyy");
            var yearBString = dateB.ToString("yyyy");

            var dayAString = dateA.Day.ToString("D2");
            var dayBString = dateB.Day.ToString("D2");

            string outputFormat  = string.Empty;
            string dateRangeText = string.Empty;

            //same year, same month
            if (dateA.Year == dateB.Year && dateA.Month == dateB.Month && dateA.Day != dateB.Day)
            {
                outputFormat  = "{0}.-{1}. {2} {3}";                //e.g. 08.-11. September 2013
                dateRangeText = string.Format(outputFormat, dayAString, dayBString, monthAStringLong, yearAString);
            }


            //same year, different months
            else if (dateA.Year == dateB.Year && dateA.Month != dateB.Month)
            {
                outputFormat  = "{0}. {1} - {2}. {3} {4}";                //e.g. 27. September - 04. Oktober 2013
                dateRangeText = string.Format(outputFormat, dayAString, monthAStringLong, dayBString, monthBStringLong, yearAString);
            }

            //different years
            else
            {
                outputFormat  = "{0}. {1} {2} - {3}. {4} {5}";                //e.g. 27. Dezember 2013 - 04. Januar 2014
                dateRangeText = string.Format(outputFormat, dayAString, monthAStringLong, yearAString, dayBString, monthBStringLong, yearBString);
            }

            var output = new TextUnitCollection();
            var text   = new LiteralTextUnit(dateRangeText);

            text.FontStyle = fontStyle;
            output.Add(text);
            handled = true;
            return(output);
        }
Пример #4
0
        public IEnumerable <ITextUnit> GetTextUnits(ComponentPart componentPart, Template template, Citation citation, out bool handled)
        {
            handled = false;

            if (citation == null)
            {
                return(null);
            }
            if (citation.Reference == null)
            {
                return(null);
            }
            if (componentPart == null)
            {
                return(null);
            }
            if (componentPart.Elements == null || !componentPart.Elements.Any())
            {
                return(null);
            }

            #region ReferenceInScope

            Reference referenceInScope = null;
            if (componentPart.Scope == ComponentPartScope.Reference)
            {
                referenceInScope = citation.Reference;
            }
            else if (componentPart.Scope == ComponentPartScope.ParentReference)
            {
                referenceInScope = citation.Reference.ParentReference;
            }
            if (referenceInScope == null)
            {
                return(null);
            }

            #endregion

            IEnumerable <DateTimeFieldElement> dateTimeFieldElements = componentPart.Elements.OfType <DateTimeFieldElement>().ToList();
            if (dateTimeFieldElements == null || !dateTimeFieldElements.Any())
            {
                return(null);
            }


            bool        dateFound             = false;
            CultureInfo targetCulture         = CultureInfo.CreateSpecificCulture("en-US");
            string      targetFullFormat      = "";   //use "" and it will be taken from the DateTimeFieldElement
            string      targetYearMonthFormat = "yyyy MMM";
            string      targetYearOnlyFormat  = "yyyy";

            foreach (DateTimeFieldElement dateTimeFieldElement in dateTimeFieldElements)
            {
                if (string.IsNullOrEmpty(targetFullFormat))
                {
                    targetFullFormat = dateTimeFieldElement.Format;
                }
                ReferencePropertyId propertyId = dateTimeFieldElement.PropertyId;
                string dateString = referenceInScope.GetValue(propertyId) as string;
                if (string.IsNullOrEmpty(dateString))
                {
                    continue;
                }

                List <Segment> segments = GetSegments(dateString);
                if (segments == null || !segments.Any())
                {
                    continue;
                }

                List <LiteralElement> literalElements = new List <LiteralElement>();
                foreach (Segment segment in segments)
                {
                    switch (segment.type)
                    {
                        #region Text

                    case SegmentType.Text:
                    {
                        var literalElement = new LiteralElement(componentPart, segment.text);
                        literalElement.FontStyle = dateTimeFieldElement.FontStyle;
                        literalElements.Add(literalElement);
                    }
                    break;

                        #endregion

                        #region DateTime

                    case SegmentType.DateTime:
                    {
                        string newDateString;
                        if (!segment.ContainsMonthInformation && !segment.ContainsDayInformation)
                        {
                            newDateString = segment.dateTime.ToString(targetYearOnlyFormat, targetCulture);
                        }
                        else if (!segment.ContainsDayInformation)
                        {
                            newDateString = segment.dateTime.ToString(targetYearMonthFormat, targetCulture);
                        }
                        else
                        {
                            newDateString = segment.dateTime.ToString(targetFullFormat, targetCulture);
                        }
                        var literalElement = new LiteralElement(componentPart, newDateString);
                        literalElement.FontStyle = dateTimeFieldElement.FontStyle;
                        literalElements.Add(literalElement);
                    }
                    break;

                        #endregion
                    }
                }

                //replace the DateTimeFieldElement by the LiteralElements
                componentPart.Elements.ReplaceItem(dateTimeFieldElement, literalElements);
            }



            //and Citavi handles the rest, therefore we say handled = false && return null
            handled = false;
            return(null);
        }
Пример #5
0
        public static void StoreTargetReferences(this List <SequenceNumberImportInfo> sequenceNumberImportInfos, ReferencePropertyId propertyId)
        {
            foreach (var sequenceNumberInfo in sequenceNumberImportInfos)
            {
                var currentValue = sequenceNumberInfo.TargetReference.GetValue(propertyId).ToString().Trim();

                if (string.IsNullOrEmpty(currentValue))
                {
                    sequenceNumberInfo.TargetReference.SetValue(propertyId, sequenceNumberInfo.Number);
                    sequenceNumberInfo.Success = true;
                }
                else
                {
                    if (currentValue.Equals(sequenceNumberInfo.Number, StringComparison.OrdinalIgnoreCase))
                    {
                        sequenceNumberInfo.Success = true;
                    }
                    else
                    {
                        var newValue = currentValue + " | " + sequenceNumberInfo.Number;
                        sequenceNumberInfo.TargetReference.SetValue(propertyId, newValue);
                        sequenceNumberInfo.Success = true;
                    }
                }
            }
        }
Пример #6
0
        public IEnumerable <ITextUnit> GetTextUnits(ComponentPart componentPart, Template template, Citation citation, out bool handled)
        {
            handled = false;
            if (citation == null)
            {
                return(null);
            }

            Reference reference = citation.Reference;

            if (reference == null)
            {
                return(null);
            }

            if (componentPart == null)
            {
                return(null);
            }
            if (componentPart.Elements == null || !componentPart.Elements.Any() || componentPart.Elements.Count != 1)
            {
                return(null);
            }

            TextFieldElement firstTextFieldElement = componentPart.Elements.OfType <TextFieldElement>().FirstOrDefault() as TextFieldElement;

            if (firstTextFieldElement == null)
            {
                return(null);
            }

            ComponentPartScope scope            = componentPart.Scope;
            Reference          referenceInScope = null;

            if (scope == ComponentPartScope.Reference)
            {
                referenceInScope = reference;
            }
            else
            {
                referenceInScope = reference.ParentReference;
            }
            if (referenceInScope == null)
            {
                return(null);
            }


            ReferencePropertyId propertyTagged = ReferencePropertyId.None;

            switch (firstTextFieldElement.PropertyId)
            {
            case ReferencePropertyId.Title:
            {
                propertyTagged = ReferencePropertyId.TitleTagged;
            }
            break;

            case ReferencePropertyId.Subtitle:
            {
                propertyTagged = ReferencePropertyId.SubtitleTagged;
            }
            break;

            case ReferencePropertyId.TitleSupplement:
            {
                propertyTagged = ReferencePropertyId.TitleSupplementTagged;
            }
            break;
            }
            if (propertyTagged == ReferencePropertyId.None)
            {
                return(null);
            }

            string stringTagged = referenceInScope.GetValue(propertyTagged) as string;

            if (string.IsNullOrEmpty(stringTagged))
            {
                return(null);
            }
            if (!HasTags(stringTagged))
            {
                return(null);
            }


            bool italicFound = false;

            TextUnitCollection textUnitCollection = TextUnitCollectionUtility.TaggedTextToTextUnits(firstTextFieldElement, stringTagged);

            foreach (ITextUnit textUnit in textUnitCollection)
            {
                //Flip bits where required
                if (firstTextFieldElement.FontStyle.HasFlag(FontStyle.Italic))
                {
                    textUnit.TemporaryFontStyle ^= FontStyle.Italic;
                }
                if (firstTextFieldElement.FontStyle.HasFlag(FontStyle.Bold))
                {
                    textUnit.TemporaryFontStyle ^= FontStyle.Bold;
                }
            }

            handled = true;
            return(textUnitCollection);
        }
Пример #7
0
        //Version 3.0: complete overhaul, script considers different output for placehoder citations and bibliography citations
        //Version 2.0: script can be attached to both date/time field element as well as text field element

        public IEnumerable <ITextUnit> GetTextUnits(ComponentPart componentPart, Template template, Citation citation, out bool handled)
        {
            //enter the culture the date info has been formatted and entered in, e.g. 12/05/2017 would be December, 12th in en-UK and May, 5th in en-US
            CultureInfo targetCulture = CultureInfo.CreateSpecificCulture("en-US");

            //list all possible date formats for this script to check; the scripts tries to parse the date beginning from left to right
            string[] formats = new string[] { "yyyy-MM-dd", "yyyy/MM/dd", "dd/MM/yyyy", "yyyy/dd/MM", "dd.MM.yyyy", "d.M.yyyy", "d.MM.yyyy", "dd.M.yyyy", "dd.MM.yy", "d.M.yy", "d.MM.yy", "dd.M.yy" };

            bool usePeriodAfterAbbreviatedMonthName = true;                     //if true, month names will be: Jan. Feb. Mar. Apr. May (!) Jun. Jul. Aug. Sept. Oct. Nov. Dec.

            ///IMPORTANT: Use the following indexed placeholders {n} and format strings xxxx as in {n:xxxx} for the templates.
            ///You can ommit placeholders and/or place them freely inside the templates below. Yet, it is not recommended to use the same placeholder more than once,
            ///because this script is not optimized for this.
            ///
            ///{0}: letter for ambiguity resolving
            ///{1}: year	of start or single date
            ///{2}: month	of start or single date
            ///{3}: day     of start or single date
            ///{4}: year	of end date
            ///{5}: month	of end date
            ///{6}: day     of end date
            ///use the following formatting for "6 June 2018"
            ///YEAR:	yyyy = 2018, yy = 18
            ///MONTH:	MMMM = June, MMM = Jun, MM = 06, %M = 6
            ///DAY:		dd = 06, %d = 6, %do = 6th

            //SINGLE DATE - output format templates
            string outputFormatSingleDatePlaceholder  = "{1:yyyy}{0}";                                                                                                                                                          //e.g. 2013a
            string outputFormatSingleDateBibliography = "{1:yyyy}{0}, {2:MMMM} {3:%do}";                                                                                                                                        //e.g. 2013a, January 6th

            //DATE RANGE - output format templates
            //same year, same month
            string outputFormatDateRangeSameYearSameMonthPlaceholder  = "{1:yyyy}{0}";                                                                                                                  //e.g. 2013a
            string outputFormatDateRangeSameYearSameMonthBibliography = "{1:yyyy}{0}, {2:MMMM} {3:%do} - {6:%do}";                                                                                      //e.g. 2013a, January 6th - 9th

            //same year, different month
            string outputFormatDateRangeSameYearDifferentMonthPlaceholder  = "{1:yyyy}{0}";                                                                                             //e.g. 2013a
            string outputFormatDateRangeSameYearDifferentMonthBibliography = "{1:yyyy}{0}, {2:MMMM} {3:%do} - {5:MMMM} {6:%do}";                                                        //e.g. 2013a, September 28th - October 3rd

            //different years
            string outputFormatDateRangeDifferentYearsPlaceholder  = "{1:yyyy}/{4:yyyy}{0}";                                                                            //e.g. 2013/2014a
            string outputFormatDateRangeDifferentYearsBibliography = "{1:yyyy}/{4:yyyy}{0}; {1:yyyy}, {2:MMMM} {3:%do} - {4:yyyy}, {5:MMMM} {6:%do}";                   //e.g. 2013/2014a; 2013, December 29th - 2014, January 4th

            handled = false;

            if (citation == null)
            {
                return(null);
            }

            Reference referenceInScope = GetReferenceInScope(componentPart, citation);

            if (referenceInScope == null)
            {
                return(null);
            }

            FieldElement dateFieldElement = GetDateFieldElement(componentPart);

            if (dateFieldElement == null)
            {
                return(null);
            }

            ReferencePropertyId referencePropertyId = dateFieldElement.PropertyId;
            string dateString = referenceInScope.GetValue(referencePropertyId) as string;

            if (string.IsNullOrEmpty(dateString))
            {
                return(null);
            }

            TextUnitCollection output = null;

            PlaceholderCitation placeholderCitation = citation as PlaceholderCitation;
            bool isPlaceholderCitation = placeholderCitation != null;

            PreviewCitation previewCitation = citation as PreviewCitation;
            bool            isPreviewBibliographyCitation = previewCitation != null && citation.CitationType == CitationType.Bibliography;

            BibliographyCitation bibliographyCitation = citation as BibliographyCitation;
            bool isBibliographyCitation = bibliographyCitation != null;

            if (bibliographyCitation == null && placeholderCitation != null)
            {
                bibliographyCitation = placeholderCitation.CorrespondingBibliographyCitation;
            }
            if (bibliographyCitation == null && !isPreviewBibliographyCitation)
            {
                return(null);
            }


            string          identifyingLetter         = bibliographyCitation != null ? bibliographyCitation.IdentifyingLetter : string.Empty;
            LiteralTextUnit identifyingLetterTextUnit = new LiteralTextUnit(identifyingLetter, Drawing.FontStyle.Neutral);
            bool            hasIdentifyingLetter      = !string.IsNullOrEmpty(identifyingLetter);

            #region Tread n.d. + letter for disambiguation ("IdentifyingLetter")

            if (hasIdentifyingLetter && ContainsND(dateString))
            {
                //we make sure the IdentifyingLetter is separated from n.d. by a space char or hyphen: Smith n.d.-a, Smith n.d.-b
                //go to method SeparateIdentifyingLetterFromND below to customize
                output = componentPart.GetTextUnitsUnfiltered(citation, template);
                if (output == null || !output.Any())
                {
                    return(null);
                }

                handled = true;
                return(SeparateIdentifyingLetterFromND(output, identifyingLetter));
            }

            #endregion

            FontStyle fontStyle = dateFieldElement is DateTimeFieldElement ? ((DateTimeFieldElement)dateFieldElement).FontStyle : ((TextFieldElement)dateFieldElement).FontStyle;

            DateTime dateSingle;
            DateTime dateStart;
            DateTime dateEnd;

            string outputText = string.Empty;

            #region Check for Single Date

            if (TryParseSingleDate(dateString, formats, targetCulture, out dateSingle))
            {
                #region BibliographyCitation

                if (isBibliographyCitation || isPreviewBibliographyCitation)
                {
                    outputText = FormatDate(dateSingle, outputFormatSingleDateBibliography, targetCulture, identifyingLetter, usePeriodAfterAbbreviatedMonthName);
                }

                #endregion

                #region PlaceholderCitation

                else if (isPlaceholderCitation)
                {
                    outputText = FormatDate(dateSingle, outputFormatSingleDatePlaceholder, targetCulture, identifyingLetter, usePeriodAfterAbbreviatedMonthName);
                }

                #endregion

                #region Other

                else
                {
                    handled = false;
                    return(null);
                }

                #endregion
            }

            #endregion

            #region Check for Date Range

            else if (TryParseDateRange(dateString, formats, targetCulture, out dateStart, out dateEnd))
            {
                #region BibliographyCitation

                if (isBibliographyCitation || isPreviewBibliographyCitation)
                {
                    #region same year, same month

                    if (dateStart.Year == dateEnd.Year && dateStart.Month == dateEnd.Month && dateStart.Day != dateEnd.Day)
                    {
                        outputText = FormatDateRange(dateStart, dateEnd, outputFormatDateRangeSameYearSameMonthBibliography, targetCulture, identifyingLetter, usePeriodAfterAbbreviatedMonthName);
                    }

                    #endregion

                    #region same year, different months

                    else if (dateStart.Year == dateEnd.Year && dateStart.Month != dateEnd.Month)
                    {
                        outputText = FormatDateRange(dateStart, dateEnd, outputFormatDateRangeSameYearDifferentMonthBibliography, targetCulture, identifyingLetter, usePeriodAfterAbbreviatedMonthName);
                    }

                    #endregion

                    #region different years

                    else
                    {
                        outputText = FormatDateRange(dateStart, dateEnd, outputFormatDateRangeDifferentYearsBibliography, targetCulture, identifyingLetter, usePeriodAfterAbbreviatedMonthName);
                    }

                    #endregion
                }

                #endregion

                #region PlaceholderCitation

                else if (isPlaceholderCitation)
                {
                    #region same year, same month

                    if (dateStart.Year == dateEnd.Year && dateStart.Month == dateEnd.Month && dateStart.Day != dateEnd.Day)
                    {
                        outputText = FormatDateRange(dateStart, dateEnd, outputFormatDateRangeSameYearSameMonthPlaceholder, targetCulture, identifyingLetter, usePeriodAfterAbbreviatedMonthName);
                    }

                    #endregion

                    #region same year, different months

                    else if (dateStart.Year == dateEnd.Year && dateStart.Month != dateEnd.Month)
                    {
                        outputText = FormatDateRange(dateStart, dateEnd, outputFormatDateRangeSameYearDifferentMonthPlaceholder, targetCulture, identifyingLetter, usePeriodAfterAbbreviatedMonthName);
                    }

                    #endregion

                    #region different years

                    else
                    {
                        outputText = FormatDateRange(dateStart, dateEnd, outputFormatDateRangeDifferentYearsPlaceholder, targetCulture, identifyingLetter, usePeriodAfterAbbreviatedMonthName);
                    }

                    #endregion
                }

                #endregion

                #region Other

                else
                {
                    handled = false;
                    return(null);
                }

                #endregion
            }

            #endregion

            #region Do the output

            if (!string.IsNullOrEmpty(outputText))
            {
                var outputTextUnits = new TextUnitCollection();
                outputTextUnits = TextUnitCollectionUtility.TaggedTextToTextUnits(dateFieldElement, outputText, fontStyle);

                if (outputTextUnits.Any())
                {
                    List <ITextUnit> componentPartOutput = new List <ITextUnit>();
                    foreach (IElement element in componentPart.Elements)
                    {
                        if (element == dateFieldElement)
                        {
                            componentPartOutput.AddRange(outputTextUnits);
                        }
                        else
                        {
                            componentPartOutput.AddRange(element.GetTextUnits(citation, template));
                        }
                    }
                    handled = true;
                    return(componentPartOutput);
                }
            }

            #endregion

            handled = false;
            return(null);
        }
    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()
Пример #9
0
        static string GetReferencePropertybyId(this Reference reference, ReferencePropertyId propertyId)
        {
            switch (propertyId)
            {
            case ReferencePropertyId.Title:
            {
                if (!string.IsNullOrEmpty(reference.Title))
                {
                    return(reference.Title);
                }
            }
            break;

            case ReferencePropertyId.Periodical:
            {
                if (reference.Periodical != null)
                {
                    return(reference.Periodical.StandardAbbreviationAuto);
                }
            }
            break;

            case ReferencePropertyId.Subtitle:
            {
                if (!string.IsNullOrEmpty(reference.Subtitle))
                {
                    return(reference.Subtitle);
                }
            }
            break;

            case ReferencePropertyId.YearResolved:
            {
                if (!string.IsNullOrEmpty(reference.YearResolved))
                {
                    return(reference.YearResolved);
                }
            }
            break;

            case ReferencePropertyId.ShortTitle:
            {
                if (!string.IsNullOrEmpty(reference.ShortTitle))
                {
                    return(reference.ShortTitle);
                }
            }
            break;

            case ReferencePropertyId.AuthorsOrEditorsOrOrganizations:
            {
                if (reference.AuthorsOrEditorsOrOrganizations.Any())
                {
                    return(reference.AuthorsOrEditorsOrOrganizations.First().LastName);
                }
            }
            break;

            case ReferencePropertyId.CustomField1:
            {
                if (!string.IsNullOrEmpty(reference.CustomField1))
                {
                    return(reference.CustomField1);
                }
            }
            break;

            case ReferencePropertyId.CustomField2:
            {
                if (!string.IsNullOrEmpty(reference.CustomField2))
                {
                    return(reference.CustomField2);
                }
            }
            break;

            case ReferencePropertyId.CustomField3:
            {
                if (!string.IsNullOrEmpty(reference.CustomField3))
                {
                    return(reference.CustomField3);
                }
            }
            break;

            case ReferencePropertyId.CustomField4:
            {
                if (!string.IsNullOrEmpty(reference.CustomField4))
                {
                    return(reference.CustomField4);
                }
            }
            break;

            case ReferencePropertyId.CustomField5:
            {
                if (!string.IsNullOrEmpty(reference.CustomField5))
                {
                    return(reference.CustomField5);
                }
            }
            break;

            case ReferencePropertyId.CustomField6:
            {
                if (!string.IsNullOrEmpty(reference.CustomField6))
                {
                    return(reference.CustomField6);
                }
            }
            break;

            case ReferencePropertyId.CustomField7:
            {
                if (!string.IsNullOrEmpty(reference.CustomField7))
                {
                    return(reference.CustomField7);
                }
            }
            break;

            case ReferencePropertyId.CustomField8:
            {
                if (!string.IsNullOrEmpty(reference.CustomField8))
                {
                    return(reference.CustomField8);
                }
            }
            break;

            case ReferencePropertyId.CustomField9:
            {
                if (!string.IsNullOrEmpty(reference.CustomField9))
                {
                    return(reference.CustomField9);
                }
            }
            break;
            }

            return(string.Empty);
        }
Пример #10
0
        public int Compare(Citation x, Citation y)
        {
            // Dieses Script kann sowohl zur Sortierung des Literaturverzeichnisses
            // als auch von Mehrfachnachweisen im Text und in der Fußnote eingesetzt werden.

            //1. Alles ausser Gesetz/Verordnung und Gerichtsentscheidungen
            //2. Gesetz/Verordnung
            //3. Gerichtsentscheidungen

            //wenn beide unter 3. fallen:
            //Freitextfeld 1 auswerten ("Instanz", intern CustomField1) ODER Gericht (intern "Organizations"), s. Zeile 34, "courtField"
            //1. Bundesverfassungsgericht
            //2. Bundesgerichtshof
            //3. Oberlandesgericht
            //4. Landgericht
            //5. Amtsgericht

            //(die genauen Schreibweisen können in den Zeilen 120-133 eingestellt werden)
            //wenn beide dieselbe Instanz haben absteigend nach Autor, Herausgeber, Institution !

            ReferencePropertyId courtField = ReferencePropertyId.Organizations;             //alternativ: ReferencePropertyId.CustomField1

            if (x == null || y == null)
            {
                return(0);
            }
            var xReference = x.Reference;
            var yReference = y.Reference;

            if (xReference == null || yReference == null)
            {
                return(0);
            }

            var defaultComparer = CitationComparer.AuthorYearTitleOrNoAuthorThenTitleYearAscending;


            var xIsLiterature = xReference.ReferenceType != ReferenceType.StatuteOrRegulation && xReference.ReferenceType != ReferenceType.CourtDecision;
            var yIsLiterature = yReference.ReferenceType != ReferenceType.StatuteOrRegulation && yReference.ReferenceType != ReferenceType.CourtDecision;

            var xIsStatuteOrRegulation = xReference.ReferenceType == ReferenceType.StatuteOrRegulation;
            var yIsStatuteOrRegulation = yReference.ReferenceType == ReferenceType.StatuteOrRegulation;

            var xIsCourtDecision = xReference.ReferenceType == ReferenceType.CourtDecision;
            var yIsCourtDecision = yReference.ReferenceType == ReferenceType.CourtDecision;

            if (xIsCourtDecision && yIsCourtDecision)
            {
                //spezielle Sortierung für Gerichtsentscheidungen:

                int xCourtRanking = 99;
                int yCourtRanking = 99;

                if (courtField == ReferencePropertyId.Organizations)
                {
                    IEnumerable <Person> xCourts = xReference.GetValue(courtField) as IEnumerable <Person>;
                    IEnumerable <Person> yCourts = yReference.GetValue(courtField) as IEnumerable <Person>;

                    Person xCourt = xCourts == null ? null : xCourts.FirstOrDefault();
                    Person yCourt = yCourts == null ? null : yCourts.FirstOrDefault();

                    xCourtRanking = GetCourtRanking(xCourt);
                    yCourtRanking = GetCourtRanking(yCourt);
                }
                else
                {
                    string xCourt = xReference.GetValue(courtField) as string;
                    string yCourt = yReference.GetValue(courtField) as string;

                    xCourtRanking = GetCourtRanking(xCourt);
                    yCourtRanking = GetCourtRanking(yCourt);
                }



                if (xCourtRanking == yCourtRanking)
                {
                    return(defaultComparer.Compare(x, y));
                }
                else
                {
                    return(xCourtRanking.CompareTo(yCourtRanking));
                }
            }
            else if (xIsCourtDecision && !yIsCourtDecision)
            {
                return(1);
            }
            else if (!xIsCourtDecision && yIsCourtDecision)
            {
                return(-1);
            }
            else if (xIsStatuteOrRegulation && yIsLiterature)
            {
                return(1);
            }
            else if (xIsLiterature && yIsStatuteOrRegulation)
            {
                return(-1);
            }
            else
            {
                //z.B. beide Literatur oder beide Gesetz/Verordnung
                return(defaultComparer.Compare(x, y));
            }
        }