Exemple #1
0
        public static byte[] GetOwnerVerification(OwnerVerificationReportModel reportModel, string name)
        {
            try
            {
                // ******************************************************
                // get document template
                // ******************************************************
                Assembly assembly = Assembly.GetExecutingAssembly();
                byte[]   byteArray;
                int      ownerCount = 0;

                using (Stream templateStream = assembly.GetManifestResourceStream(ResourceName))
                {
                    byteArray = new byte[templateStream.Length];
                    templateStream.Read(byteArray, 0, byteArray.Length);
                    templateStream.Close();
                }

                using (MemoryStream documentStream = new MemoryStream())
                {
                    WordprocessingDocument wordDocument = WordprocessingDocument.Create(documentStream, WordprocessingDocumentType.Document, true);

                    // add a main document part
                    wordDocument.AddMainDocumentPart();

                    using (MemoryStream templateStream = new MemoryStream())
                    {
                        templateStream.Write(byteArray, 0, byteArray.Length);
                        WordprocessingDocument wordTemplate = WordprocessingDocument.Open(templateStream, true);

                        if (wordTemplate == null)
                        {
                            throw new Exception("Owner Verification template not found");
                        }

                        // ******************************************************
                        // merge document content
                        // ******************************************************
                        foreach (HetOwner owner in reportModel.Owners)
                        {
                            ownerCount++;

                            using (MemoryStream ownerStream = new MemoryStream())
                            {
                                WordprocessingDocument ownerDocument = (WordprocessingDocument)wordTemplate.Clone(ownerStream);
                                ownerDocument.Save();

                                Dictionary <string, string> values = new Dictionary <string, string>
                                {
                                    { "classification", owner.Classification },
                                    { "districtAddress", reportModel.DistrictAddress },
                                    { "districtContact", reportModel.DistrictContact },
                                    { "organizationName", owner.OrganizationName },
                                    { "address1", owner.Address1 },
                                    { "address2", owner.Address2 },
                                    { "reportDate", reportModel.ReportDate },
                                    { "ownerCode", owner.OwnerCode },
                                    { "sharedKeyHeader", owner.SharedKeyHeader },
                                    { "sharedKey", owner.SharedKey },
                                    { "workPhoneNumber", owner.PrimaryContact.WorkPhoneNumber }
                                };

                                // update classification number first [ClassificationNumber]
                                owner.Classification = owner.Classification.Replace("&", "&amp;");
                                bool found = false;

                                foreach (OpenXmlElement paragraphs in ownerDocument.MainDocumentPart.Document.Body.Elements())
                                {
                                    foreach (OpenXmlElement paragraphRun in paragraphs.Elements())
                                    {
                                        foreach (OpenXmlElement text in paragraphRun.Elements())
                                        {
                                            if (text.InnerText.Contains("ClassificationNumber"))
                                            {
                                                // replace text
                                                text.InnerXml = text.InnerXml.Replace("<w:t>ClassificationNumber</w:t>",
                                                                                      $"<w:t xml:space='preserve'>ORCS: {owner.Classification}</w:t>");

                                                found = true;
                                                break;
                                            }
                                        }

                                        if (found)
                                        {
                                            break;
                                        }
                                    }

                                    if (found)
                                    {
                                        break;
                                    }
                                }

                                ownerDocument.MainDocumentPart.Document.Save();
                                ownerDocument.Save();

                                // update merge fields
                                MergeHelper.ConvertFieldCodes(ownerDocument.MainDocumentPart.Document);
                                MergeHelper.MergeFieldsInElement(values, ownerDocument.MainDocumentPart.Document);
                                ownerDocument.MainDocumentPart.Document.Save();

                                // setup table for equipment data
                                Table     equipmentTable = GenerateEquipmentTable(owner.HetEquipment);
                                Paragraph tableParagraph = null;
                                found = false;

                                foreach (OpenXmlElement paragraphs in ownerDocument.MainDocumentPart.Document.Body.Elements())
                                {
                                    foreach (OpenXmlElement paragraphRun in paragraphs.Elements())
                                    {
                                        foreach (OpenXmlElement text in paragraphRun.Elements())
                                        {
                                            if (text.InnerText.Contains("Owner Equipment Table"))
                                            {
                                                // insert table here...
                                                text.RemoveAllChildren();
                                                tableParagraph = (Paragraph)paragraphRun.Parent;
                                                found          = true;
                                                break;
                                            }
                                        }

                                        if (found)
                                        {
                                            break;
                                        }
                                    }

                                    if (found)
                                    {
                                        break;
                                    }
                                }

                                // append table to document
                                if (tableParagraph != null)
                                {
                                    Run run = tableParagraph.AppendChild(new Run());
                                    run.AppendChild(equipmentTable);
                                }

                                ownerDocument.MainDocumentPart.Document.Save();
                                ownerDocument.Save();

                                // merge owner into the master document
                                if (ownerCount == 1)
                                {
                                    // update document header
                                    foreach (HeaderPart headerPart in ownerDocument.MainDocumentPart.HeaderParts)
                                    {
                                        MergeHelper.ConvertFieldCodes(headerPart.Header);
                                        MergeHelper.MergeFieldsInElement(values, headerPart.Header);
                                        headerPart.Header.Save();
                                    }

                                    wordDocument = (WordprocessingDocument)ownerDocument.Clone(documentStream);

                                    ownerDocument.Close();
                                    ownerDocument.Dispose();
                                }
                                else
                                {
                                    // DELETE document header from owner document
                                    ownerDocument.MainDocumentPart.DeleteParts(ownerDocument.MainDocumentPart.HeaderParts);

                                    List <HeaderReference> headers = ownerDocument.MainDocumentPart.Document.Descendants <HeaderReference>().ToList();

                                    foreach (HeaderReference header in headers)
                                    {
                                        header.Remove();
                                    }

                                    // DELETE document footers from owner document
                                    ownerDocument.MainDocumentPart.DeleteParts(ownerDocument.MainDocumentPart.FooterParts);

                                    List <FooterReference> footers = ownerDocument.MainDocumentPart.Document.Descendants <FooterReference>().ToList();

                                    foreach (FooterReference footer in footers)
                                    {
                                        footer.Remove();
                                    }

                                    // DELETE section properties from owner document
                                    List <SectionProperties> properties = ownerDocument.MainDocumentPart.Document.Descendants <SectionProperties>().ToList();

                                    foreach (SectionProperties property in properties)
                                    {
                                        property.Remove();
                                    }

                                    ownerDocument.Save();

                                    // insert section break in master
                                    MainDocumentPart mainPart = wordDocument.MainDocumentPart;

                                    Paragraph         para      = new Paragraph();
                                    SectionProperties sectProp  = new SectionProperties();
                                    SectionType       secSbType = new SectionType()
                                    {
                                        Val = SectionMarkValues.OddPage
                                    };
                                    PageSize pageSize = new PageSize()
                                    {
                                        Width = 11900U, Height = 16840U, Orient = PageOrientationValues.Portrait
                                    };
                                    PageMargin pageMargin = new PageMargin()
                                    {
                                        Top = 2642, Right = 23U, Bottom = 278, Left = 23U, Header = 714, Footer = 0, Gutter = 0
                                    };

                                    // page numbering throws out the "odd page" section breaks
                                    //PageNumberType pageNum = new PageNumberType() {Start = 1};

                                    sectProp.AppendChild(secSbType);
                                    sectProp.AppendChild(pageSize);
                                    sectProp.AppendChild(pageMargin);
                                    //sectProp.AppendChild(pageNum);

                                    ParagraphProperties paragraphProperties = new ParagraphProperties(sectProp);
                                    para.AppendChild(paragraphProperties);

                                    mainPart.Document.Body.InsertAfter(para, mainPart.Document.Body.LastChild);
                                    mainPart.Document.Save();

                                    // append document body
                                    string altChunkId = $"AltChunkId{ownerCount}";

                                    AlternativeFormatImportPart chunk = mainPart.AddAlternativeFormatImportPart(AlternativeFormatImportPartType.WordprocessingML, altChunkId);

                                    ownerDocument.Close();
                                    ownerDocument.Dispose();

                                    ownerStream.Seek(0, SeekOrigin.Begin);
                                    chunk.FeedData(ownerStream);

                                    AltChunk altChunk = new AltChunk {
                                        Id = altChunkId
                                    };

                                    Paragraph para3 = new Paragraph();
                                    Run       run3  = para3.InsertAfter(new Run(), para3.LastChild);
                                    run3.AppendChild(altChunk);

                                    mainPart.Document.Body.InsertAfter(para3, mainPart.Document.Body.LastChild);
                                    mainPart.Document.Save();
                                }
                            }
                        }

                        wordTemplate.Close();
                        wordTemplate.Dispose();
                        templateStream.Close();
                    }

                    // ******************************************************
                    // secure & return completed document
                    // ******************************************************
                    wordDocument.CompressionOption = CompressionOption.Maximum;
                    SecurityHelper.PasswordProtect(wordDocument);

                    wordDocument.Close();
                    wordDocument.Dispose();

                    documentStream.Seek(0, SeekOrigin.Begin);
                    byteArray = documentStream.ToArray();
                }

                return(byteArray);
            }
            catch (Exception e)
            {
                Console.WriteLine(e);
                throw;
            }
        }
Exemple #2
0
        public static byte[] GetRentalAgreement(RentalAgreementDocViewModel reportModel, string name)
        {
            try
            {
                char[] characters = System.Text.Encoding.ASCII.GetChars(new byte[] { 10 });
                char   crLf       = characters[0];

                // ******************************************************
                // get document template
                // ******************************************************
                Assembly assembly = Assembly.GetExecutingAssembly();
                byte[]   byteArray;

                using (Stream templateStream = assembly.GetManifestResourceStream(ResourceName))
                {
                    byteArray = new byte[templateStream.Length];
                    templateStream.Read(byteArray, 0, byteArray.Length);
                    templateStream.Close();
                }

                using (MemoryStream documentStream = new MemoryStream())
                {
                    WordprocessingDocument wordDocument = WordprocessingDocument.Create(documentStream, WordprocessingDocumentType.Document, true);

                    // add a main document part
                    wordDocument.AddMainDocumentPart();

                    using (MemoryStream templateStream = new MemoryStream())
                    {
                        templateStream.Write(byteArray, 0, byteArray.Length);
                        WordprocessingDocument wordTemplate = WordprocessingDocument.Open(templateStream, true);

                        if (wordTemplate == null)
                        {
                            throw new Exception("Rental Agreement template not found");
                        }

                        // ******************************************************
                        // merge document content
                        // ******************************************************
                        using (MemoryStream agreementStream = new MemoryStream())
                        {
                            WordprocessingDocument agreementDocument = (WordprocessingDocument)wordTemplate.Clone(agreementStream);
                            agreementDocument.Save();

                            // create note
                            string note = "";
                            if (reportModel.Note != null)
                            {
                                foreach (NoteLine line in reportModel.Note)
                                {
                                    if (!string.IsNullOrEmpty(note))
                                    {
                                        note += $"{crLf.ToString()}{line.Line}";
                                    }
                                    else
                                    {
                                        note += $"{line.Line}";
                                    }
                                }
                            }

                            // equipment full name
                            string equipmentName = $"{reportModel.Equipment.Year}/" +
                                                   $"{reportModel.Equipment.Make}/" +
                                                   $"{reportModel.Equipment.Model}/" +
                                                   $"{reportModel.Equipment.Size}/" +
                                                   $"{reportModel.Equipment.SerialNumber}";

                            // rates included in total
                            string rateString1 = "";
                            string comment1    = "";
                            if (reportModel.RentalAgreementRatesWithTotal != null)
                            {
                                foreach (HetRentalAgreementRate rate in reportModel.RentalAgreementRatesWithTotal)
                                {
                                    if (!string.IsNullOrEmpty(rateString1))
                                    {
                                        rateString1 += $"{crLf.ToString()}{rate.RateString}";
                                        comment1    += $"{crLf.ToString()}{rate.Comment}";
                                    }
                                    else
                                    {
                                        rateString1 += $"{rate.RateString}";
                                        comment1    += $"{rate.Comment}";
                                    }
                                }
                            }

                            // rates not included in total
                            string rateString2 = "";
                            string comment2    = "";
                            if (reportModel.RentalAgreementRatesWithoutTotal != null)
                            {
                                foreach (HetRentalAgreementRate rate in reportModel.RentalAgreementRatesWithoutTotal)
                                {
                                    if (!string.IsNullOrEmpty(rateString2))
                                    {
                                        rateString2 += $"{crLf.ToString()}{rate.RateString}";
                                        comment2    += $"{crLf.ToString()}{rate.Comment}";
                                    }
                                    else
                                    {
                                        rateString2 += $"{rate.RateString}";
                                        comment2    += $"{rate.Comment}";
                                    }
                                }
                            }

                            // agreement conditions
                            string comment3 = "";
                            if (reportModel.RentalAgreementConditions != null)
                            {
                                foreach (HetRentalAgreementCondition cond in reportModel.RentalAgreementConditions)
                                {
                                    var conditionComment = string.IsNullOrEmpty(cond.Comment) ? cond.ConditionName : cond.Comment;

                                    if (!string.IsNullOrEmpty(comment3))
                                    {
                                        comment3 += $"{crLf.ToString()}{conditionComment}";
                                    }
                                    else
                                    {
                                        comment3 += $"{conditionComment}";
                                    }
                                }
                            }

                            // rates not included in total
                            string overtimeRate    = "";
                            string overtimeComment = "";
                            if (reportModel.RentalAgreementRatesOvertime != null)
                            {
                                foreach (HetRentalAgreementRate rate in reportModel.RentalAgreementRatesOvertime.OrderByDescending(x => x.Comment))
                                {
                                    if (!string.IsNullOrEmpty(overtimeRate))
                                    {
                                        overtimeRate    += $"{crLf.ToString()}{rate.RateString}";
                                        overtimeComment += $"{crLf.ToString()}{rate.Comment}";
                                    }
                                    else
                                    {
                                        overtimeRate    += $"{rate.RateString}";
                                        overtimeComment += $"{rate.Comment}";
                                    }
                                }
                            }

                            Dictionary <string, string> values = new Dictionary <string, string>
                            {
                                { "classification", reportModel.Classification },
                                { "equipmentCode", reportModel.Equipment.EquipmentCode },
                                { "number", reportModel.Number },
                                { "organizationName", reportModel.Equipment.Owner.OrganizationName },
                                { "address1", reportModel.Equipment.Owner.Address1 },
                                { "address2", reportModel.Equipment.Owner.Address2 },
                                { "ownerCode", reportModel.Equipment.Owner.OwnerCode },
                                { "workPhoneNumber", reportModel.Equipment.Owner.PrimaryContact.WorkPhoneNumber },
                                { "mobilePhoneNumber", reportModel.Equipment.Owner.PrimaryContact.MobilePhoneNumber },
                                { "faxPhoneNumber", reportModel.Equipment.Owner.PrimaryContact.FaxPhoneNumber },
                                { "equipmentFullName", equipmentName },
                                { "noteLine", note },
                                { "baseRateString", reportModel.BaseRateString },
                                { "rateComment", reportModel.RateComment },
                                { "projectNumber", reportModel.Project.ProvincialProjectNumber },
                                { "projectName", reportModel.Project.Name },
                                { "district", reportModel.Project.District.Name },
                                { "estimateHours", reportModel.EstimateHours.ToString() },
                                { "estimateStartWork", reportModel.EstimateStartWork },
                                { "localAreaName", reportModel.Equipment.LocalArea.Name },
                                { "workSafeBcpolicyNumber", reportModel.Equipment.Owner.WorkSafeBcpolicyNumber },
                                { "agreementCity", reportModel.AgreementCity },
                                { "datedOn", reportModel.DatedOn },
                                { "rateString1", rateString1 },
                                { "comment1", comment1 },
                                { "agreementTotalString", reportModel.AgreementTotalString },
                                { "rateString2", rateString2 },
                                { "comment2", comment2 },
                                { "comment3", comment3 },
                                { "overtimeRate", overtimeRate },
                                { "overtimeComment", overtimeComment },
                                { "doingBusinessAs", reportModel.DoingBusinessAs },
                                { "emailAddress", reportModel.EmailAddress }
                            };

                            // update main document
                            MergeHelper.ConvertFieldCodes(agreementDocument.MainDocumentPart.Document);
                            MergeHelper.MergeFieldsInElement(values, agreementDocument.MainDocumentPart.Document);
                            agreementDocument.MainDocumentPart.Document.Save();

                            wordDocument = (WordprocessingDocument)agreementDocument.Clone(documentStream);

                            agreementDocument.Close();
                            agreementDocument.Dispose();
                        }

                        wordTemplate.Close();
                        wordTemplate.Dispose();
                        templateStream.Close();
                    }

                    // ******************************************************
                    // secure & return completed document
                    // ******************************************************
                    wordDocument.CompressionOption = CompressionOption.Maximum;
                    SecurityHelper.PasswordProtect(wordDocument);

                    wordDocument.Close();
                    wordDocument.Dispose();

                    documentStream.Seek(0, SeekOrigin.Begin);
                    byteArray = documentStream.ToArray();
                }

                return(byteArray);
            }
            catch (Exception e)
            {
                Console.WriteLine(e);
                throw;
            }
        }
Exemple #3
0
        public static byte[] GetSeniorityList(SeniorityListReportViewModel reportModel, string name)
        {
            try
            {
                // ******************************************************
                // get document template
                // ******************************************************
                Assembly assembly = Assembly.GetExecutingAssembly();
                byte[]   byteArray;
                int      recordCount = 0;

                using (Stream templateStream = assembly.GetManifestResourceStream(ResourceName))
                {
                    byteArray = new byte[templateStream.Length];
                    templateStream.Read(byteArray, 0, byteArray.Length);
                    templateStream.Close();
                }

                using (MemoryStream documentStream = new MemoryStream())
                {
                    WordprocessingDocument wordDocument = WordprocessingDocument.Create(documentStream, WordprocessingDocumentType.Document, true);

                    // add a main document part
                    wordDocument.AddMainDocumentPart();

                    using (MemoryStream templateStream = new MemoryStream())
                    {
                        templateStream.Write(byteArray, 0, byteArray.Length);
                        WordprocessingDocument wordTemplate = WordprocessingDocument.Open(templateStream, true);

                        if (wordTemplate == null)
                        {
                            throw new Exception("Owner Verification template not found");
                        }

                        // ******************************************************
                        // merge document content
                        // ******************************************************
                        foreach (SeniorityListRecord seniorityList in reportModel.SeniorityListRecords)
                        {
                            recordCount++;

                            using (MemoryStream listStream = new MemoryStream())
                            {
                                WordprocessingDocument listDocument = (WordprocessingDocument)wordTemplate.Clone(listStream);
                                listDocument.Save();

                                Dictionary <string, string> values = new Dictionary <string, string>
                                {
                                    { "classification", reportModel.Classification },
                                    { "printedOn", reportModel.PrintedOn },
                                    { "districtName", seniorityList.DistrictName },
                                    { "localAreaName", seniorityList.LocalAreaName },
                                    { "districtEquipmentTypeName", seniorityList.DistrictEquipmentTypeName }
                                };

                                // update main document
                                MergeHelper.ConvertFieldCodes(listDocument.MainDocumentPart.Document);
                                MergeHelper.MergeFieldsInElement(values, listDocument.MainDocumentPart.Document);
                                listDocument.MainDocumentPart.Document.Save();

                                // setup table for seniority list
                                Table seniorityTable = GenerateSeniorityTable(seniorityList.SeniorityList, seniorityList);

                                // find our paragraph
                                Paragraph tableParagraph = null;
                                bool      found          = false;

                                foreach (OpenXmlElement paragraphs in listDocument.MainDocumentPart.Document.Body.Elements())
                                {
                                    foreach (OpenXmlElement paragraphRun in paragraphs.Elements())
                                    {
                                        foreach (OpenXmlElement text in paragraphRun.Elements())
                                        {
                                            if (text.InnerText.Contains("SeniorityListTable"))
                                            {
                                                // insert table here...
                                                text.RemoveAllChildren();
                                                tableParagraph = (Paragraph)paragraphRun.Parent;
                                                found          = true;
                                                break;
                                            }
                                        }

                                        if (found)
                                        {
                                            break;
                                        }
                                    }

                                    if (found)
                                    {
                                        break;
                                    }
                                }

                                // append table to document
                                if (tableParagraph != null)
                                {
                                    Run run = tableParagraph.AppendChild(new Run());
                                    run.AppendChild(seniorityTable);
                                }

                                listDocument.MainDocumentPart.Document.Save();
                                listDocument.Save();

                                // merge owner into the master document
                                if (recordCount == 1)
                                {
                                    // update document header
                                    foreach (HeaderPart headerPart in listDocument.MainDocumentPart.HeaderParts)
                                    {
                                        MergeHelper.ConvertFieldCodes(headerPart.Header);
                                        MergeHelper.MergeFieldsInElement(values, headerPart.Header);
                                        headerPart.Header.Save();
                                    }

                                    wordDocument = (WordprocessingDocument)listDocument.Clone(documentStream);

                                    listDocument.Close();
                                    listDocument.Dispose();
                                }
                                else
                                {
                                    // DELETE document header from owner document
                                    listDocument.MainDocumentPart.DeleteParts(listDocument.MainDocumentPart.HeaderParts);

                                    List <HeaderReference> headers = listDocument.MainDocumentPart.Document.Descendants <HeaderReference>().ToList();

                                    foreach (HeaderReference header in headers)
                                    {
                                        header.Remove();
                                    }

                                    // DELETE document footers from owner document
                                    listDocument.MainDocumentPart.DeleteParts(listDocument.MainDocumentPart.FooterParts);

                                    List <FooterReference> footers = listDocument.MainDocumentPart.Document.Descendants <FooterReference>().ToList();

                                    foreach (FooterReference footer in footers)
                                    {
                                        footer.Remove();
                                    }

                                    // DELETE section properties from owner document
                                    List <SectionProperties> properties = listDocument.MainDocumentPart.Document.Descendants <SectionProperties>().ToList();

                                    foreach (SectionProperties property in properties)
                                    {
                                        property.Remove();
                                    }

                                    listDocument.Save();

                                    // insert section break in master
                                    MainDocumentPart mainPart = wordDocument.MainDocumentPart;

                                    Paragraph pageBreak = new Paragraph(new Run(new Break {
                                        Type = BreakValues.Page
                                    }));

                                    mainPart.Document.Body.InsertAfter(pageBreak, mainPart.Document.Body.LastChild);
                                    mainPart.Document.Save();

                                    // append document body
                                    string altChunkId = $"AltChunkId{recordCount}";

                                    AlternativeFormatImportPart chunk = mainPart.AddAlternativeFormatImportPart(AlternativeFormatImportPartType.WordprocessingML, altChunkId);

                                    listDocument.Close();
                                    listDocument.Dispose();

                                    listStream.Seek(0, SeekOrigin.Begin);
                                    chunk.FeedData(listStream);

                                    AltChunk altChunk = new AltChunk {
                                        Id = altChunkId
                                    };

                                    Paragraph para3 = new Paragraph();
                                    Run       run3  = para3.InsertAfter(new Run(), para3.LastChild);
                                    run3.AppendChild(altChunk);

                                    mainPart.Document.Body.InsertAfter(para3, mainPart.Document.Body.LastChild);
                                    mainPart.Document.Save();
                                }
                            }
                        }

                        wordTemplate.Close();
                        wordTemplate.Dispose();
                        templateStream.Close();
                    }

                    // ******************************************************
                    // secure & return completed document
                    // ******************************************************
                    wordDocument.CompressionOption = CompressionOption.Maximum;
                    SecurityHelper.PasswordProtect(wordDocument);

                    wordDocument.Close();
                    wordDocument.Dispose();

                    documentStream.Seek(0, SeekOrigin.Begin);
                    byteArray = documentStream.ToArray();
                }

                return(byteArray);
            }
            catch (Exception e)
            {
                Console.WriteLine(e);
                throw;
            }
        }