This is a migrated thread and some comments may be shown as answers.

Document processor in .NET 5

1 Answer 106 Views
General Discussions
This is a migrated thread and some comments may be shown as answers.
Bob
Top achievements
Rank 1
Veteran
Bob asked on 15 Nov 2020, 12:15 AM

We are unable to make a simple class library in NET 5 by trying to compile the following class:

using Abp.Domain.Entities;
using Abp.Timing;
using Nuagecare.App.NcDocument.Dtos;
using Nuagecare.App.NcIncident.Dto;
using Nuagecare.Authorization.Users.Dto;
using Nuagecare.NcEntity.Dtos;
using System;
using System.Collections.Generic;
using System.Dynamic;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Text;
using System.Windows.Media;
using Telerik.Windows.Documents.Flow.FormatProviders.Docx;
using Telerik.Windows.Documents.Flow.Model;
using Telerik.Windows.Documents.Flow.Model.Editing;
using Telerik.Windows.Documents.Flow.Model.Shapes;
using Telerik.Windows.Documents.Flow.Model.Styles;
using Telerik.Windows.Documents.Model;
using Telerik.Windows.Documents.Primitives;
using Telerik.Windows.Documents.Spreadsheet.Model;
 
namespace Nuagecare.DocumentProcessing
{
    public class DocumentProcessor : IDocumentProcessor
    {
        protected readonly ThemableFontFamily DefaultFontFamily = new ThemableFontFamily(new FontFamily("Calibri"));
        protected readonly ThemableColor DefaultForeground = new ThemableColor(Colors.Black);
        protected readonly double DefaultFontSize = 14.0;
 
        public Byte[] NcEntityMerge(Byte[] input, NcEntityDto ncEntity, string tenancyName, UserEditDto currentUser)
        {
            var FirstNames = ncEntity.GetData<AttributeDataDto>("FirstNames");
            var Surname = ncEntity.GetData<AttributeDataDto>("Surname");
            var Gender = ncEntity.GetData<AttributeDataDto>("Gender");
            var Height = ncEntity.GetData<AttributeDataDto>("Height");
            var Weight = ncEntity.GetData<AttributeDataDto>("Weight");
            var RoomNumber = ncEntity.GetData<AttributeDataDto>("RoomNumber");
            var NHSId = ncEntity.GetData<AttributeDataDto>("NHSId");
            var DateOfBirth = "";
            var Age = "";
 
            try
            {
                var sDateOfBirth1 = ncEntity.GetData<AttributeDataDto>("DateOfBirth"); //US (javascript) format
                DateTime dDateOfBirth = DateTime.ParseExact(sDateOfBirth1.Value, "MM/dd/yyyy HH:mm:ss", CultureInfo.InvariantCulture).ToLocalTime();
                DateOfBirth = dDateOfBirth.ToString("dd/MM/yyyy");
                Age = CalculateAge(dDateOfBirth).ToString();
            }
            catch (Exception ex)
            {
                DateOfBirth = "unknown";
                Age = "unknown";
            }
 
            DocxFormatProvider provider = new DocxFormatProvider();
            RadFlowDocument document = provider.Import(input);
 
            dynamic mergeRecord = new ExpandoObject();
 
            mergeRecord.DisplayName = ncEntity.DisplayName ?? "";
            mergeRecord.FullName = FirstNames.Value + " " + Surname.Value ?? "";
            mergeRecord.Gender = Gender.Value ?? "";
            mergeRecord.DateOfBirth = DateOfBirth;
            mergeRecord.Age = Age;
            mergeRecord.Height = Height.Value ?? "0";
            mergeRecord.Weight = Weight.Value ?? "0";
            mergeRecord.RoomNumber = RoomNumber.Value ?? "0";
            mergeRecord.NHSId = NHSId.Value ?? "";
            mergeRecord.TenancyName = System.Globalization.CultureInfo.CurrentCulture.TextInfo.ToTitleCase(tenancyName) ?? "";
            mergeRecord.CreationTime = Clock.Now.ToString("dddd, dd MMMM yyyy");
            mergeRecord.NuagecareRevisions = "1";
            mergeRecord.CreatedBy = currentUser.Name + " " + currentUser.Surname;
            mergeRecord.CreationText = "Created by " + currentUser.Name + " " + currentUser.Surname + " on " + Clock.Now.ToString("dddd, dd MMMM yyyy");
            mergeRecord.CreatedHistory = "Created by " + currentUser.Name + " " + currentUser.Surname + " on " + Clock.Now.ToString("dddd, dd MMMM yyyy");
            mergeRecord.LastUpdated = Clock.Now.ToString("dddd, dd MMMM yyyy");
 
            List<ExpandoObject> mailMergeDataSource = new List<ExpandoObject>();
            mailMergeDataSource.Add(mergeRecord);
 
            RadFlowDocument mailMergeResult = document.MailMerge(mailMergeDataSource);
 
            //use for testing - outputs to root of Web.Host
            //using (Stream output = new FileStream("CarePlan.docx", FileMode.OpenOrCreate))
            //{
            //    provider.Export(mailMergeResult, output);
            //}
            return provider.Export(mailMergeResult);
        }
 
        public Byte[] ReplaceCarePlanImage(Byte[] input, Byte[] image, IDictionary<string, string> imageNames)
        {
            //deprecated - unable find and replace image
            //possibly user two bookmarks and delete everything in between (i.e. the old image) and replace with the new image
            DocxFormatProvider provider = new DocxFormatProvider();
            RadFlowDocument document = provider.Import(input);
            RadFlowDocumentEditor editor = new RadFlowDocumentEditor(document);
 
            var carePlanTitleParagraph = document.EnumerateChildrenOfType<Paragraph>().Where(p => p.StyleId.Contains("Title")).First();
 
            if (carePlanTitleParagraph != null)
            {
                Break br = new Break(document);
                editor.MoveToInlineEnd(carePlanTitleParagraph.Inlines.Last());
                editor.InsertParagraph();
 
                var header = document.Sections.First().Headers.Default;
                var headerImages = header.EnumerateChildrenOfType<ImageInline>();
                var footer = document.Sections.First().Headers.Default;
                var footerImages = footer.EnumerateChildrenOfType<ImageInline>();
                var images = document.EnumerateChildrenOfType<ImageInline>();
 
                foreach (var item in images)
                {
                    if (headerImages.Contains(item) || footerImages.Contains(item))
                    {
                        continue;
                    }
                    else
                    {
                        using (MemoryStream memStream = new MemoryStream(image))
                        {
                            var extension = Path.GetExtension(imageNames["FileName"]);
                            var props = System.Drawing.Image.FromStream(memStream);
                            int Width;
                            int Height;
                            if (props.Width > 350)
                            {
                                Width = 350;
                                Height = Convert.ToInt32((Convert.ToDecimal(props.Height) / Convert.ToDecimal(props.Width)) * 350);
                            }
                            else
                            {
                                Width = props.Width;
                                Height = props.Height;
                            }
                            //editor.InsertImageInline(memStream, extension.Replace(".", ""), new System.Windows.Size(Width, Height));
                            item.Image.ImageSource = new Telerik.Windows.Documents.Media.ImageSource(memStream, extension.Replace(".", ""));
                            item.Image.Name = Path.GetExtension(imageNames["FileName"]);
                        }
                    }
                }
 
 
 
            }
 
            return provider.Export(document);
        }
 
        public Byte[] NcAccidentBookMerge(
            Byte[] input,
            CreateOrEditNcDocumentInput ncDocument,
            UserEditDto currentUser,
            List<NcEntityDto> entities,
            List<UserEditDto> staff,
            string IncidentType,
            List<string> AccidentTags
            )
        {
            List<string> EntityNames = new List<string>();
            foreach (var ncEntity in entities)
            {
                var Title = ncEntity.GetData<AttributeDataDto>("Title").Value;
                var FirstNames = ncEntity.GetData<AttributeDataDto>("FirstNames").Value;
                var Surname = ncEntity.GetData<AttributeDataDto>("Surname").Value;
                EntityNames.Add(Title + " " + FirstNames + " " + Surname);
            }
            var ResidentNames = string.Join(", ", EntityNames);
 
            List<string> UserNames = new List<string>();
            foreach (var person in staff)
            {
                var FirstNames = person.Name;
                var Surname = person.Surname;
                UserNames.Add(FirstNames + " " + Surname);
            }
            var StaffNames = string.Join(", ", UserNames);
 
            List<string> DatesOfBirth = new List<string>();
            foreach (var ncEntity in entities)
            {
                var DoB = ncEntity.GetData<AttributeDataDto>("DateOfBirth").Value;
                DatesOfBirth.Add(DoB);
            }
            var DoBs = string.Join(", ", DatesOfBirth);
 
 
            List<string> AccidentTagList = new List<string>();
            foreach (var AccidentTag in AccidentTags)
            {
                AccidentTagList.Add(AccidentTag);
            }
            var AccidentTagNames = string.Join(", ", AccidentTagList);
 
 
            DocxFormatProvider provider = new DocxFormatProvider();
 
            RadFlowDocument document = provider.Import(input);
            dynamic mergeRecord = new ExpandoObject();
 
            mergeRecord.IncidentSummary = ncDocument.DisplayName ?? "";
            mergeRecord.ResidentNames = ResidentNames;
            mergeRecord.DatesOfBirth = DoBs;
            mergeRecord.StaffNames = StaffNames;
            mergeRecord.ReportString = ncDocument.ReportString ?? "";
            mergeRecord.IncidentType = IncidentType ?? "";
            mergeRecord.AccidentTags = AccidentTagNames;
            mergeRecord.OccurrenceDateAndTime = ncDocument.OccurrenceDatetime;
 
            if (UserNames.Count() > 0)
            {
                mergeRecord.FirstPerson = UserNames[0];
            }
 
            mergeRecord.ReportingUser = currentUser.Name + " " + currentUser.Surname;
 
            List<ExpandoObject> mailMergeDataSource = new List<ExpandoObject>();
            mailMergeDataSource.Add(mergeRecord);
 
            RadFlowDocument mailMergeResult = document.MailMerge(mailMergeDataSource);
 
            //use for testing - outputs to root of Web.Host
            //using (Stream output = new FileStream("CarePlan.docx", FileMode.OpenOrCreate))
            //{
            //    provider.Export(mailMergeResult, output);
            //}
            return provider.Export(mailMergeResult);
        }
 
        public Byte[] NcIncidentReportMerge(
            Byte[] input,
            CreateNcIncidentReportDocumentInput incident
            )
        {
            DocxFormatProvider provider = new DocxFormatProvider();
 
            RadFlowDocument document = provider.Import(input);
            dynamic mergeRecord = new ExpandoObject();
 
            mergeRecord.Id = incident.Id;
            mergeRecord.IncidentType = incident.IncidentType;
            mergeRecord.IncidentState = incident.IncidentState;
            mergeRecord.CreationTime = incident.CreationTime;
            mergeRecord.CreatorUser = incident.CreatorUser;
            mergeRecord.OccurrenceDateAndTime = incident.OccurrenceDatetime;
            mergeRecord.IncidentSummary = incident.IncidentSummary ?? "";
            mergeRecord.FirstPersonToIdentifyTheIncidentUser = incident.FirstPersonToIdentifyTheIncidentUser;
            mergeRecord.ReporterUser = incident.ReporterUser;
            mergeRecord.ManagerNotified = incident.ManagerNotified;
            mergeRecord.ReportedToManagerUser = incident.ReportedToManagerUser ?? "";
            mergeRecord.AntecedentNotes = incident.AntecedentNotes;
            mergeRecord.BehaviourNotes = incident.BehaviourNotes;
            mergeRecord.ConsequenceNotes = incident.ConsequenceNotes;
            mergeRecord.PropertyDamage = incident.PropertyDamage ?? "No property damage notes.";
            mergeRecord.PersonalInjuries = incident.PersonalInjuries ?? "No personal injury notes.";
            mergeRecord.MedicalNotes = incident.MedicalNotes ?? "No medical notes.";
            mergeRecord.ExternalAgencyNotes = incident.ExternalAgencyNotes ?? "No external agency notes.";
            mergeRecord.CarePlanNotes = incident.CarePlanNotes ?? "No care plan notes.";
            mergeRecord.RIDDORNotes = incident.RIDDORNotes ?? "No RIDDOR notes.";
            mergeRecord.NextOfKinNotes = incident.NextOfKinNotes ?? "No next of kin notes.";
            mergeRecord.AdditionalNotes = incident.AdditionalNotes ?? "No additional notes.";
 
            if (String.IsNullOrEmpty(string.Join(", ", incident.ResidentNames)))
            {
                mergeRecord.ResidentNames = "No residents involved.";
            }
            else
            {
                mergeRecord.ResidentNames = string.Join(", ", incident.ResidentNames);
            }
 
            if (String.IsNullOrEmpty(string.Join(", ", incident.StaffNames)))
            {
                mergeRecord.StaffNames = string.Join(", ", incident.StaffNames);
            }
            else
            {
                mergeRecord.StaffNames = string.Join(", ", incident.StaffNames);
            }
 
            if (String.IsNullOrEmpty(string.Join(", ", incident.ContactNames)))
            {
                mergeRecord.ContactNames = "No third parties involved.";
            }
            else
            {
                mergeRecord.ContactNames = string.Join(", ", incident.ContactNames);
            }
 
 
            List<ExpandoObject> mailMergeDataSource = new List<ExpandoObject>();
            mailMergeDataSource.Add(mergeRecord);
 
            RadFlowDocument mailMergeResult = document.MailMerge(mailMergeDataSource);
 
            //RadFlowDocumentEditor editor = new RadFlowDocumentEditor(document); // document is an instance of the RadFlowDocument class
            //editor.ReplaceText("code", "source code", true, true);
 
            //use for testing - outputs to root of Web.Host
            //using (Stream output = new FileStream("ReportIncident.docx", FileMode.OpenOrCreate))
            //{
            //    provider.Export(mailMergeResult, output);
            //}
            return provider.Export(mailMergeResult);
        }
 
 
        public Byte[] AppendHistory(Byte[] input, List<NcDocumentHistoryDto> documentHistory)
        {
            DocxFormatProvider provider = new DocxFormatProvider();
            RadFlowDocument document = provider.Import(input);
            //SetupHistoryStyles(document);
            CreateSection(document, "Document history", documentHistory);
 
            //comment out when live
            //using (Stream output = new FileStream("LocalTest.docx", FileMode.OpenOrCreate))
            //{
            //    provider.Export(document, output);
            //}
 
            return provider.Export(document);
        }
 
        #region helpers
        /// <summary> 
        /// For calculating only age 
        /// </summary> 
        /// <param name="dateOfBirth">Date of birth</param> 
        /// <returns> age e.g. 26</returns> 
        private int CalculateAge(DateTime dateOfBirth)
        {
            int age = 0;
            age = DateTime.Now.Year - dateOfBirth.Year;
            if (DateTime.Now.DayOfYear < dateOfBirth.DayOfYear)
                age = age - 1;
            return age;
        }
 
        //private void SetupHistoryStyles(RadFlowDocument document)
        //{
        //    var heading1 = document.StyleRepository.AddBuiltInStyle(BuiltInStyleNames.GetHeadingStyleIdByIndex(1));
        //    var heading2 = document.StyleRepository.AddBuiltInStyle(BuiltInStyleNames.GetHeadingStyleIdByIndex(2));
        //}
 
        private void SetupCarePlanStyles(RadFlowDocument document)
        {
            var heading1 = document.StyleRepository.AddBuiltInStyle(BuiltInStyleNames.GetHeadingStyleIdByIndex(1));
            heading1.CharacterProperties.FontFamily.LocalValue = DefaultFontFamily;
            heading1.CharacterProperties.FontSize.LocalValue = 32.0;
            heading1.CharacterProperties.FontWeight.LocalValue = System.Windows.FontWeights.Bold;
            heading1.CharacterProperties.ForegroundColor.LocalValue = DefaultForeground;
            heading1.ParagraphProperties.PageBreakBefore.LocalValue = true;
        }
 
        private void CreateSection(RadFlowDocument document, string title, List<NcDocumentHistoryDto> documentHistory)
        {
            //delete section if exists
            Section sectionFound = null;
            var existingParagraph = FindHeaderAsParagraphContainingText(document, title);
            if (existingParagraph != null)
            {
                foreach (var sectionInstance in document.EnumerateChildrenOfType<Section>())
                {
                    if (sectionInstance == existingParagraph.BlockContainer)
                    {
                        sectionFound = sectionInstance;
                        break;
                    }
                }
                if (sectionFound != null)
                {
                    document.Sections.Remove(sectionFound);
                }
            }
 
            RadFlowDocumentEditor editor = new RadFlowDocumentEditor(document);
            Section section = editor.InsertSection();
            section.SectionType = SectionType.Continuous;
            section.PageSize = PaperTypeConverter.ToSize(PaperTypes.A4);
 
            var paragraph = section.Blocks.AddParagraph();
            editor.MoveToParagraphStart(paragraph);
            paragraph.StyleId = BuiltInStyleNames.GetHeadingStyleIdByIndex(1);
            editor.InsertText(title);
 
            InsertTable(section, editor, documentHistory);
        }
 
        private void InsertTable(Section section, RadFlowDocumentEditor editor, List<NcDocumentHistoryDto> documentHistory)
        {
            var paragraph = section.Blocks.AddParagraph();
            editor.MoveToParagraphStart(paragraph);
 
            Table table = section.Blocks.AddTable();
 
            var row = table.Rows.AddTableRow();
 
            var cell = row.Cells.AddTableCell();
            cell.PreferredWidth = new TableWidthUnit(TableWidthUnitType.Fixed, 120);
            SetCellText(editor, cell, "History", bold: true, background: new ThemableColor(Colors.LightSteelBlue), horizontalAlignment: Alignment.Left);
 
            //cell = row.Cells.AddTableCell();
            //cell.PreferredWidth = new TableWidthUnit(TableWidthUnitType.Fixed, 120);
            //SetCellText(editor, cell, "User", bold: true, background: new ThemableColor(Colors.LightSteelBlue), horizontalAlignment: Alignment.Left);
 
            //cell = row.Cells.AddTableCell();
            //cell.PreferredWidth = new TableWidthUnit(TableWidthUnitType.Auto);
            //SetCellText(editor, cell, "Report string", bold: true, background: new ThemableColor(Colors.LightSteelBlue), horizontalAlignment: Alignment.Left);
 
            //cell = row.Cells.AddTableCell();
            //cell.PreferredWidth = new TableWidthUnit(TableWidthUnitType.Fixed, 100);
            //SetCellText(editor, cell, "Filename", bold: true, background: new ThemableColor(Colors.LightSkyBlue), horizontalAlignment: Alignment.Left);
 
 
            foreach (var history in documentHistory)
            {
                row = table.Rows.AddTableRow();
 
                //cell = row.Cells.AddTableCell();
                //SetCellText(editor, cell, history.CreationTime.ToLocalTime().ToString("dd/MM/yyyy HH:mm"), horizontalAlignment: Alignment.Left, verticalAlignment: VerticalAlignment.Top);
 
                //cell = row.Cells.AddTableCell();
                //SetCellText(editor, cell, history.CreatorUserName, horizontalAlignment: Alignment.Left, verticalAlignment: VerticalAlignment.Top);
 
                cell = row.Cells.AddTableCell();
                SetCellText(editor, cell, history.ReportString, horizontalAlignment: Alignment.Left, verticalAlignment: VerticalAlignment.Top);
 
                //cell = row.Cells.AddTableCell();
                //var test = Path.GetFileName(history.Uri);
                //SetCellText(editor, cell, Path.GetFileName(history.Uri), horizontalAlignment: Alignment.Left, verticalAlignment: VerticalAlignment.Top);
            }
        }
 
        private void SetCellText(RadFlowDocumentEditor editor, TableCell cell, string text, string fontFamily = null,
                               double? fontSize = null, bool? bold = null, bool? italic = null, TableCellBorders borders = null,
                               ThemableColor background = null, ThemableColor foreground = null, Alignment? horizontalAlignment = null,
                               VerticalAlignment? verticalAlignment = null)
        {
            cell.IgnoreCellMarkerInRowHeightCalculation = true;
            cell.Padding = new Padding(1);
 
            var paragraph = cell.Blocks.AddParagraph();
            paragraph.StyleId = BuiltInStyleNames.NormalStyleId;
            paragraph.Properties.SpacingBefore.LocalValue = 0;
            paragraph.Properties.SpacingAfter.LocalValue = 0;
 
            editor.MoveToParagraphStart(paragraph);
 
            if (borders != null)
                cell.Borders = borders;
 
            if (background != null)
                cell.Shading.BackgroundColor = background;
 
            editor.CharacterFormatting.FontFamily.LocalValue = string.IsNullOrEmpty(fontFamily)
                                                                   ? DefaultFontFamily
                                                                   : new ThemableFontFamily(fontFamily);
 
            editor.CharacterFormatting.FontSize.LocalValue = fontSize ?? DefaultFontSize;
 
            //editor.CharacterFormatting.FontWeight.LocalValue = (bold ?? false) ? FontWeights.Bold : FontWeights.Normal;
            //editor.CharacterFormatting.FontStyle.LocalValue = (italic ?? false) ? FontStyles.Italic : FontStyles.Normal;
 
            editor.CharacterFormatting.ForegroundColor.LocalValue = foreground ?? DefaultForeground;
 
            cell.VerticalAlignment = verticalAlignment != null ? verticalAlignment.Value : VerticalAlignment.Center;
 
            paragraph.TextAlignment = horizontalAlignment != null ? horizontalAlignment.Value : Alignment.Center;
 
            editor.InsertText(string.IsNullOrEmpty(text) ? " " : text);
        }
 
 
        private Paragraph FindHeaderAsParagraphContainingText(RadFlowDocument document, string searchedText)
        {
            foreach (var titleParagraph in document.EnumerateChildrenOfType<Paragraph>().Where(p => p.StyleId.Contains("Heading")))
            {
                StringBuilder paragraphContent = new StringBuilder();
                foreach (var run in titleParagraph.EnumerateChildrenOfType<Run>())
                {
                    if (run.Text == searchedText)
                    {
                        return titleParagraph;
                    }
                }
            }
            return null;
        }
 
 
        #endregion
    }
}

 

Can you tell us what Nuget packages we need to install to make this work?

1 Answer, 1 is accepted

Sort by
0
Peshito
Telerik team
answered on 16 Nov 2020, 03:10 PM

Hi,

What error messages did you receive by running the code? A list of the NuGet packages depending on the platform used can be found in our help article.

Hope this helps.

Regards,
Peshito
Progress Telerik

Virtual Classroom, the free self-paced technical training that gets you up to speed with Telerik and Kendo UI products quickly just got a fresh new look + new and improved content including a brand new Blazor course! Check it out at https://learn.telerik.com/.

Tags
General Discussions
Asked by
Bob
Top achievements
Rank 1
Veteran
Answers by
Peshito
Telerik team
Share this question
or