Exemplo n.º 1
0
        /// <summary>
        /// Tries to auto resize the specified table columns.
        /// </summary>
        /// <param name="table">pdf table</param>
        public static void AutoResizeTableColumns(this PdfGrid table)
        {
            if (table == null) return;
            var currentRowWidthsList = new List<float>();
            var previousRowWidthsList = new List<float>();

            foreach (var row in table.Rows)
            {
                currentRowWidthsList.Clear();
                currentRowWidthsList.AddRange(row.GetCells().Select(cell => cell.GetCellWidth()));

                if (!previousRowWidthsList.Any())
                {
                    previousRowWidthsList = new List<float>(currentRowWidthsList);
                }
                else
                {
                    for (int i = 0; i < previousRowWidthsList.Count; i++)
                    {
                        if (previousRowWidthsList[i] < currentRowWidthsList[i])
                            previousRowWidthsList[i] = currentRowWidthsList[i];
                    }
                }
            }

            if (previousRowWidthsList.Any())
                table.SetTotalWidth(previousRowWidthsList.ToArray());
        }
Exemplo n.º 2
0
        static List<int> getNums(string input_text)
        {
            char[] delChars = { ',' };

            List<string> str_pages = new List<string>(input_text.Split(delChars));
            List<int> pages = new List<int>();

            foreach (string s in str_pages)
            {
                Match match = Regex.Match(s, @"^[0-9]+$");

                if (match.Success)
                {
                    pages.Add(Int32.Parse(s));
                }

            }

            foreach (string t in str_pages)
            {
                Match match = Regex.Match(t, @"^\d+-+\d+$");

                if (match.Success)
                {
                    int num1 = sep(t, "before");
                    int num2 = sep(t, "after");

                    if (num1 >= num2)
                    {
                        // FAIL PROCESS, ALERT USER
                        pages.Clear();
                        return pages;
                    }
                    else
                    {
                        foreach (int num in Enumerable.Range(num1, num2 - num1 + 1))
                        {
                            pages.Add(num);
                        }
                    }
                }
            }

            return pages;
        }
Exemplo n.º 3
0
        public void CreateReport(string filepath, int scene_number, EyeX.Person person)
        {
            var doc = new Document();

            // Set the page size
            doc.SetPageSize(PageSize.A4.Rotate());
            string fullpath= Path.Combine(filepath, "report.pdf");
            PdfWriter.GetInstance(doc, new FileStream(fullpath, FileMode.Create));

            doc.Open();

            // add personal info
            List<Phrase> phrases = new List<Phrase>();
            phrases.Add(new Phrase(Properties.Settings.Default.id + "\n", HeaderFont));
            phrases.Add(new Phrase("Персональная информация \n", HeaderFont));
            phrases.Add(new Phrase("Возраст: " + person.age + "\n", ArticleFont));
            phrases.Add(new Phrase("Пол: " + person.sex.ToString() + "\n", ArticleFont));
            phrases.Add(new Phrase("Дата: " + DateTime.Now.ToString() + "\n", ArticleFont));
            phrases.Add(new Phrase("\n", ArticleFont));

            foreach (var phrase in phrases)
                doc.Add(phrase);
            phrases.Clear();

            for (int i = 0; i < scene_number; i++)
            {
                Image img = Image.GetInstance(filepath + "\\img\\" + i + ".jpeg");

                img.ScalePercent(50);
                img.Alignment = Element.ALIGN_CENTER;
                doc.Add(img);
            }

            doc.Close();
            Process.Start(filepath);
        }
        private void insertarCodigosDeBarraAPlantillaWord(Word.Document docPRUEBA, int i)
        {
            List<Word.Shape> lst = new List<Word.Shape>();
            foreach (Word.Shape sh in docPRUEBA.Shapes)
            {
                while (sh.Name.Contains("\n"))
                    sh.Name = sh.Name.Replace("\n", "");
                if (sh.Type.ToString() == "msoPicture")
                    lst.Add(sh);
            }
            List<Word.Range> ranges = new List<Microsoft.Office.Interop.Word.Range>();

            float left, top, h, w;
            bool insertado = false;
            string tempname = "";
            List<Word.Shape> removedShapes = new List<Word.Shape>();
            try
            {
                foreach (string bcd in lista_camposCodBarr)
                {
                    insertado = false;
                    ranges.Clear();
                    foreach (Word.Shape sh in lst)
                    {
                        if (sh.Name == bcd)
                        {
                            left = sh.Left;
                            top = sh.Top;
                            h = sh.Height;
                            w = sh.Width;
                            sh.ConvertToInlineShape();
                            foreach (Word.InlineShape s in docPRUEBA.InlineShapes)
                            {
                                if (s.Type == Word.WdInlineShapeType.wdInlineShapePicture)
                                {
                                    tempname = sh.Name;
                                    ranges.Add(s.Range);
                                    s.Delete();
                                    removedShapes.Add(sh);
                                }
                            }
                            foreach (Word.Range r in ranges)
                            {
                                r.InlineShapes.AddPicture(@rutasEnModAdmin.RutaDeTemp + "/" + i + bcd + ".jpg", Type.Missing, Type.Missing, Type.Missing);
                                insertado = true;
                            }
                            Word.Shape pic;
                            foreach (Word.InlineShape s in docPRUEBA.InlineShapes)
                            {
                                if (s.Type == Word.WdInlineShapeType.wdInlineShapePicture)
                                {
                                    pic = s.ConvertToShape();
                                    pic.Name = tempname;
                                    pic.Top = top;
                                    pic.Left = left;
                                    pic.Height = h;
                                    pic.Width = w;
                                }
                            }
                            if (insertado)
                                break;
                        }

                    }
                    foreach (Word.Shape s in removedShapes)
                        lst.Remove(s);
                }
                if (dgv_PesosLotes.InvokeRequired)
                {
                    this.Invoke(new Action(() => dgv_PesosLotes.Rows[i].DefaultCellStyle.BackColor = Color.White));
                    this.Invoke(new Action(() => dgv_PesosLotes.Rows[i].Cells[1].ReadOnly = false ));
                    this.Invoke(new Action(() => dgv_PesosLotes.Rows[i].Cells[2].ReadOnly = false));
                    this.Invoke(new Action(() => dgv_PesosLotes.Rows[i].Cells[4].ReadOnly = false));
                    this.Invoke(new Action(() => dgv_PesosLotes.Rows[i].Cells[5].ReadOnly = false));

                }
                else
                {
                    dgv_PesosLotes.Rows[i].DefaultCellStyle.BackColor = Color.White;
                    dgv_PesosLotes.Rows[i].Cells[1].ReadOnly = false;
                    dgv_PesosLotes.Rows[i].Cells[2].ReadOnly = false;
                    dgv_PesosLotes.Rows[i].Cells[4].ReadOnly = false;
                    dgv_PesosLotes.Rows[i].Cells[5].ReadOnly = false;
                }
            }
            catch
            {
                if (dgv_PesosLotes.InvokeRequired)
                {
                    this.Invoke(new Action(() => dgv_PesosLotes.Rows[i].DefaultCellStyle.BackColor = Color.Red));
                    this.Invoke(new Action(() => dgv_PesosLotes.Rows[i].Cells[3].Value = null));
                    this.Invoke(new Action(() => dgv_PesosLotes.Rows[i].Cells[1].ReadOnly = false));
                    this.Invoke(new Action(() => dgv_PesosLotes.Rows[i].Cells[2].ReadOnly = false));
                    this.Invoke(new Action(() => dgv_PesosLotes.Rows[i].Cells[4].ReadOnly = false));
                    this.Invoke(new Action(() => dgv_PesosLotes.Rows[i].Cells[5].ReadOnly = false));
                }
                else
                {
                    dgv_PesosLotes.Rows[i].DefaultCellStyle.BackColor = Color.Red;
                    dgv_PesosLotes.Rows[i].Cells[3].Value = null;
                    dgv_PesosLotes.Rows[i].Cells[1].ReadOnly = false;
                    dgv_PesosLotes.Rows[i].Cells[2].ReadOnly = false;
                    dgv_PesosLotes.Rows[i].Cells[4].ReadOnly = false;
                    dgv_PesosLotes.Rows[i].Cells[5].ReadOnly = false;
                }
            }

        }
        private void insertarCodigosDeBarraAPlantillaWord_ParaCopiar(Word.Document docWord)
        {
            int i = 0;
            List<Word.Shape> lst = new List<Word.Shape>();
            foreach (Word.Shape sh in docWord.Shapes)
            {
                while (sh.Name.Contains("\n"))
                    sh.Name = sh.Name.Replace("\n", "");
                if (sh.Type.ToString() == "msoPicture")
                    lst.Add(sh);
            }
            List<Word.Range> ranges = new List<Microsoft.Office.Interop.Word.Range>();

            float left, top, h, w;
            bool insertado = false;
            string tempname = "";
            List<Word.Shape> removedShapes = new List<Word.Shape>();
            try
            {
                foreach (string bcd in lista_camposCodBarr)
                {
                    insertado = false;
                    ranges.Clear();
                    foreach (Word.Shape sh in lst)
                    {
                        if (sh.Name == bcd)
                        {
                            left = sh.Left;
                            top = sh.Top;
                            h = sh.Height;
                            w = sh.Width;
                            sh.ConvertToInlineShape();
                            foreach (Word.InlineShape s in docWord.InlineShapes)
                            {
                                if (s.Type == Word.WdInlineShapeType.wdInlineShapePicture)
                                {
                                    tempname = sh.Name;
                                    ranges.Add(s.Range);
                                    s.Delete();
                                    removedShapes.Add(sh);
                                }
                            }
                            foreach (Word.Range r in ranges)
                            {
                                r.InlineShapes.AddPicture(@rutasEnModAdmin.RutaDeTemp + "/" + i + bcd + ".jpg", Type.Missing, Type.Missing, Type.Missing);
                                insertado = true;
                            }
                            Word.Shape pic;
                            foreach (Word.InlineShape s in docWord.InlineShapes)
                            {
                                if (s.Type == Word.WdInlineShapeType.wdInlineShapePicture)
                                {
                                    pic = s.ConvertToShape();
                                    pic.Name = tempname;
                                    pic.Top = top;
                                    pic.Left = left;
                                    pic.Height = h;
                                    pic.Width = w;
                                }
                            }
                            if (insertado)
                                break;
                        }

                    }
                    foreach (Word.Shape s in removedShapes)
                        lst.Remove(s);
                }
            }
            catch(Exception ex)
            {
                MessageBox.Show(ex.Message);
            }

        }
        public ActionResult ICS109(Guid id)
        {
            var mission = this.db.Missions.Include("Log").Single(f => f.Id == id);

              string pdfTemplate = Server.MapPath(Url.Content("~/Content/forms/ics109-log.pdf"));

              using (MemoryStream result = new MemoryStream())
              {
            iTextSharp.text.Document resultDoc = new iTextSharp.text.Document();
            PdfCopy copy = new PdfCopy(resultDoc, result);
            resultDoc.Open();

            Queue<Tuple<string, string, string>> rows = null;
            int numPages = -1;
            int totalRows = 0;
            int page = 1;

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

            do
            {
              using (MemoryStream filledForm = new MemoryStream())
              {
            iTextSharp.text.pdf.PdfReader pdfReader = new iTextSharp.text.pdf.PdfReader(pdfTemplate);
            //// create and populate a string builder with each of the
            //// field names available in the subject PDF

            //StringBuilder sb = new StringBuilder();
            //foreach (var de in pdfReader.AcroFields.Fields)
            //{
            //    sb.Append(de.Key.ToString() + Environment.NewLine);
            //}
            //// Write the string builder's content to the form's textbox

            using (MemoryStream buf = new MemoryStream())
            {
              PdfStamper stamper = new PdfStamper(pdfReader, buf);

              var fields = stamper.AcroFields;

              if (rows == null)
              {
                rows = Fill109Rows(mission.Log.OrderBy(f => f.Time), fields, "topmostSubform[0].Page1[0].SUBJECTRow1[0]");
                totalRows = rows.Count;
              }

              foreach (var field in fields.Fields)
              {
                fields.SetField(field.Key, "");
              }

              int currentRow = 1;
              operators.Clear();
              while (rows.Count > 0 && fields.GetField("topmostSubform[0].Page1[0].SUBJECTRow" + currentRow.ToString() + "[0]") != null)
              {
                var row = rows.Dequeue();

                fields.SetField("topmostSubform[0].Page1[0].TIMERow" + currentRow.ToString() + "[0]", row.Item1);
                fields.SetField("topmostSubform[0].Page1[0].SUBJECTRow" + currentRow.ToString() + "[0]", row.Item2);

                if (!operators.Contains(row.Item3)) operators.Add(row.Item3);
                currentRow++;
              }

              // Now we know how many rows on a page. Figure out how many pages we need for all rows.
              if (numPages < 0)
              {
                int rowsPerPage = currentRow - 1;
                int remainder = totalRows % currentRow;
                numPages = ((remainder == 0) ? 0 : 1) + (totalRows / currentRow);
              }

              if (numPages > 0)
              {
                fields.SetField("topmostSubform[0].Page1[0]._1_Incident_Name[0]", "   " + mission.Title);
                fields.SetField("topmostSubform[0].Page1[0]._3_DEM_KCSO[0]", "    " + mission.StateNumber);
                fields.SetField("topmostSubform[0].Page1[0]._5_RADIO_OPERATOR_NAME_LOGISTICS[0]", string.Join(",", operators.Distinct()));
                fields.SetField("topmostSubform[0].Page1[0].Text30[0]", string.Format("{0:yyyy-MM-dd}", mission.Log.DefaultIfEmpty().Min(f => (f == null) ? (DateTime?)null : f.Time)));
                fields.SetField("topmostSubform[0].Page1[0].Text31[0]", string.Format("{0:yyyy-MM-dd}", mission.Log.DefaultIfEmpty().Max(f => (f == null) ? (DateTime?)null : f.Time)));
                fields.SetField("topmostSubform[0].Page1[0].Text28[0]", page.ToString());
                fields.SetField("topmostSubform[0].Page1[0].Text29[0]", numPages.ToString());
                fields.SetField("topmostSubform[0].Page1[0].DateTime[0]", DateTime.Now.ToString("     MMM d, yyyy  HH:mm"));
                fields.SetField("topmostSubform[0].Page1[0]._8_Prepared_by_Name[0]", Strings.DatabaseName);

                fields.RemoveField("topmostSubform[0].Page1[0].PrintButton1[0]");
              }

              stamper.FormFlattening = false;
              stamper.Close();

              pdfReader = new PdfReader(buf.ToArray());
              copy.AddPage(copy.GetImportedPage(pdfReader, 1));
              page++;
            }
              }
              //copy.Close();
            } while (rows != null && rows.Count > 0);

            resultDoc.Close();
            return File(result.ToArray(), "application/pdf", mission.StateNumber + "_ICS109_CommLog.pdf");
              }
        }
Exemplo n.º 7
0
        public void Split(string pdfPath, string destPath, BackgroundWorker worker = null)
        {
            //Inicjalizacja raportowania
            if (this.ReportCheckBox.Checked) {
                this.logsFile = new StreamWriter(Path.Combine(destPath, DateTime.Now.ToString("yyyyMMddHHmmss") + "RAPORT.txt"));
            }

            #region Wstępne rozpoznawanie

            BitmapPDF pdfBitmap = new BitmapPDF(pdfPath);
            PdfReader pdfDoc = new PdfReader(pdfPath);

            int[] results = new int[pdfDoc.NumberOfPages];
            for (int i = 0; i < pdfDoc.NumberOfPages && !worker.CancellationPending; i++) {
                try {
                    results[i] = pdfBitmap.Current.AvgContent;
                    if (logsFile != null) {
                        logsFile.WriteLine(String.Format("Strona {0}: {1}", i + 1, results[i]));
                    }

                    worker.ReportProgress(((i + 1) * 100) / pdfDoc.NumberOfPages);
                    pdfBitmap.MoveNext();
                } catch (Exception ex) {
                    //Będzie zawsze na końcu
                    Console.WriteLine(ex.Message);
                }
            }

            pdfDoc.Close();
            pdfBitmap.Dispose();
            if (logsFile != null)
                logsFile.Close();
            #endregion

            #region Właściwe rozdzielanie
            if (!worker.CancellationPending) {
                int j = 1;
                List<int> pages = new List<int>();

                foreach (int result in results) {
                    if (result > int.Parse(Properties.Settings.Default.MaxSensitivity)) {
                        if (pages.Count > 0) {
                            try {
                                string pdfDest = Path.Combine(destPath, DateTime.Now.ToString("yyyyMMddHHmmss") + j.ToString().PadLeft(4, '0') + ".pdf");
                                this.ExtractPages(pdfPath, pdfDest, pages.ToArray());
                            } catch (Exception ex) {
                                MessageBox.Show("Wystąpił błąd! " + ex.Message, "To jakiś straszny błąd!", MessageBoxButtons.OK, MessageBoxIcon.Error);
                            }

                            pages.Clear();
                        }
                    } else if (result > int.Parse(Properties.Settings.Default.MinSensitivity)) {
                        pages.Add(j);
                    }

                    j++;
                }

                //Na wszelki wypadek, gdyby końcówka została
                if (pages.Count > 0) {
                    try {
                        string pdfDest = Path.Combine(destPath, DateTime.Now.ToString("yyyyMMddHHmmss") + j.ToString().PadLeft(4, '0') + ".pdf");
                        this.ExtractPages(pdfPath, pdfDest, pages.ToArray());
                    } catch (Exception ex) {
                        MessageBox.Show("Wystąpił błąd! " + ex.Message, "To jakiś straszny błąd!", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    }
                }
            }
            #endregion

            worker.ReportProgress(0);
        }
Exemplo n.º 8
0
        /**
         * Checks for
         * {@link com.itextpdf.tool.xml.css.CSS.Property#PAGE_BREAK_AFTER}, if the
         * value is always a <code>Chunk.NEXTPAGE</code> is added to the
         * currentContentList after calling
         * {@link AbstractTagProcessor#end(Tag, List)}.
         */

        public IList<IElement> EndElement(IWorkerContext ctx, Tag tag, IList<IElement> currentContent)
        {
            IList<IElement> list = new List<IElement>();
            if (currentContent.Count == 0)
            {
                list = End(ctx, tag, currentContent);
            }
            else
            {
                IList<IElement> elements = new List<IElement>();
                foreach (IElement el in currentContent)
                {
                    if (el is Chunk && ((Chunk) el).HasAttributes() &&
                        ((Chunk) el).Attributes.ContainsKey(Chunk.NEWPAGE))
                    {
                        if (elements.Count > 0)
                        {
                            IList<IElement> addedElements = End(ctx, tag, elements);
                            foreach (IElement addedElement in addedElements)
                            {
                                list.Add(addedElement);
                            }
                            elements.Clear();
                        }
                        list.Add(el);
                    }
                    else
                    {
                        elements.Add(el);
                    }
                }
                if (elements.Count > 0)
                {
                    IList<IElement> addedElements = End(ctx, tag, elements);
                    foreach (IElement addedElement in addedElements)
                    {
                        list.Add(addedElement);
                    }
                    elements.Clear();
                }
            }
            String pagebreak;
            if (tag.CSS.TryGetValue(CSS.Property.PAGE_BREAK_AFTER, out pagebreak) && Util.EqualsIgnoreCase(CSS.Value.ALWAYS, pagebreak))
            {
                list.Add(Chunk.NEXTPAGE);
            }
            return list;
        }
        private void printRingForUser(UserShows userShow, int UserID, Document doc, ref List<int> defaultUsers, ref int pageCount)
        {
            float[] ringColumns = new float[] { 300, 300, 300, 300 };

            User currentUser = new User(userShow.Userid);
            Shows show = new Shows(userShow.ShowID);

            List<ShowDetails> showDetailsList = ShowDetails.GetShowDetails(userShow.ShowID);

            Rings r = new Rings();
            DataSet ringList = r.GetAllRingsForShow(userShow.ShowID, "ShowDate");

            Dogs d = new Dogs();

            DogClasses dc = new DogClasses();
            DateTime dt = DateTime.Now;
            string currentJudge = "";
            int currentRingID = 0;
            int ShowDetailsID = -1;
            int PrevShowDetailsID = -1;
            PdfPTable rings = new PdfPTable(ringColumns);

            int ringCnt = 0;
            PdfPCell cell = null;
            PdfPTable ringDetails = null;
            PdfPTable classDetailsTable = null;
            List<int> dogsRunningToday = new List<int>();
            PdfPTable headerPage = null;
            List<TeamPairsTrioDto> pairsTeams = new List<TeamPairsTrioDto>();
            try
            {
                foreach (DataRow ringRow in ringList.Tables[0].Rows)
                {
                    Rings ring = new Rings(ringRow);
                    int RingID = Convert.ToInt32(ringRow["RingID"]);
                    int EntryType = Convert.ToInt32(ringRow["EntryType"]);
                    int Lho = Convert.ToInt32(ringRow["Lho"]);
                    ShowDetailsID = Convert.ToInt32(ringRow["ShowDetailsID"]);

                    if (ringRow.IsNull("ClassID"))
                    {
                        continue;
                    }
                    int ClassID = Convert.ToInt32(ringRow["ClassID"]);
                    int ClassNo = Convert.ToInt32(ringRow["ClsNo"]);
                    DateTime rowDT = Convert.ToDateTime(ringRow["ShowDate"]);
                    if (rowDT != dt)
                    {
                        if (currentRingID != 0)
                        {
                            if (ringCnt % MaxColumns != 0)
                            {
                                var remind = ringCnt % MaxColumns;
                                while (remind-- > 0)
                                {
                                    cell = new PdfPCell(new Phrase(new Chunk(" ", pageFont)));
                                    cell.BorderWidth = 0;
                                    rings.AddCell(cell);
                                }
                            }
                            if (dogsRunningToday.Count() > 0 || UserID == -1)
                            {
                                doc.Add(headerPage);
                                doc.Add(rings);
                                if (UserID > -1)
                                {
                                    if (currentUser.UserID != UserID)
                                    {
                                        User defaultHandler = new User(UserID);
                                    }
                                }

                                doc.NewPage();
                                pageCount++;
                            }
                        }

                        dogsRunningToday.Clear();
                        if (UserID > -1)
                        {
                            if (currentUser.UserID == UserID)
                            {
                                headerPage = DrawHeader(show, rowDT, currentUser, userShow);
                            }
                            else
                            {
                                User defaultHandler = new User(UserID);
                                headerPage = DrawHeader(show, rowDT, defaultHandler, userShow);
                            }
                        }
                        else
                        {
                            headerPage = DrawHeader(show, rowDT, null, null);

                        }
                        dt = rowDT;
                        rings = new PdfPTable(ringColumns);
                        rings.WidthPercentage = 100;
                        ringCnt = 0;
                    }

                    if (currentRingID != RingID)
                    {
                        currentJudge = "";
                        ringCnt++;
                        ringDetails = new PdfPTable(1);
                        rings.AddCell(new PdfPCell(ringDetails));

                        //List<Judge> judgeList = Judge.getJudgesForRingList(RingID);
                        string JudgeName = Judge.getJudgeForClass(ClassID).Name;
                        int ClsCount = DogClasses.GetDogsInRing(RingID);

                        cell = new PdfPCell(new Phrase(new Chunk(string.Format("Ring No {0} ({1})", ringRow["RingNo"].ToString(), ClsCount), judgeFont)));
                        cell.BorderWidth = 0;
                        cell.HorizontalAlignment = PdfPCell.ALIGN_CENTER;
                        ringDetails.AddCell(cell);

                        if (currentJudge != JudgeName)
                        {
                            cell = new PdfPCell(new Phrase(new Chunk(Fpp.Core.Utils.TitleCaseString(JudgeName), judgeFont)));
                            cell.BorderWidth = 0;
                            cell.HorizontalAlignment = PdfPCell.ALIGN_CENTER;
                            ringDetails.AddCell(cell);
                            currentJudge = JudgeName;
                        }
                        currentRingID = RingID;
                        classDetailsTable = new PdfPTable(DetailsColWidths);
                        classDetailsTable.DefaultCell.BorderWidth = 0;
                        ringDetails.AddCell(classDetailsTable);
                    }
                    else
                    {
                        string JudgeName = Judge.getJudgeForClass(ClassID).Name;
                        if (currentJudge != JudgeName)
                        {
                            cell = new PdfPCell(new Phrase(new Chunk("  ", judgeFont)));
                            cell.BorderWidth = 0;
                            cell.HorizontalAlignment = PdfPCell.ALIGN_CENTER;
                            ringDetails.AddCell(cell);
                            cell = new PdfPCell(new Phrase(new Chunk(Fpp.Core.Utils.TitleCaseString(JudgeName), judgeFont)));
                            cell.BorderWidth = 0;
                            cell.HorizontalAlignment = PdfPCell.ALIGN_CENTER;
                            ringDetails.AddCell(cell);

                            classDetailsTable = new PdfPTable(DetailsColWidths);
                            classDetailsTable.DefaultCell.BorderWidth = 0;
                            ringDetails.AddCell(classDetailsTable);
                            currentJudge = JudgeName;
                        }
                    }
                    DataSet dogsList = d.GetDogsInClass(userShow.Userid, ClassID);
                    int dogsInClass = d.dogsInClassCount(ClassID);
                    List<DogClassCount> dcCounts = DogClasses.GetEntryCountsByClassId(userShow.ShowID, ClassID);

                    String clsName;
                    var part = Convert.ToInt32(ringRow["Part"]);
                    var lhoInd = "";
                    var dogsInClassDisplay = "";
                    if (dcCounts.Count > 1)
                    {
                        if (Lho == 1) {
                            dogsInClassDisplay = String.Format("({0}/{1})", dcCounts[0].Count, dcCounts[1].Count);
                        }
                        else
                        {
                            dogsInClassDisplay = String.Format("({0}/{1})", dcCounts[1].Count, dcCounts[0].Count);
                        }
                    }
                    else
                    {
                        dogsInClassDisplay = String.Format("({0})", dogsInClass);
                    }

                    if (Lho == 1)
                    {
                        lhoInd = "(FH 1st)";
                    }
                    else if (Lho == 2)
                    {
                        lhoInd = "(LHO 1st)";
                    }
                    if (EntryType != 10)
                    {
                        clsName = new ShowClasses(ClassID).NormalName(withClassNo:false, useAbbrFlag:true);
                    }
                    else
                    {
                        clsName = String.Format("{0} {1} {2} ",
                                        ShowClasses.expandHeight(ringRow),
                                        ringRow["LongName"].ToString().Trim(),
                                        ringRow["name"].ToString().Trim());
                    }
                    clsName = clsName.Replace("(Special Class", "S");
                    clsName = clsName.Replace("(Money Class", "Money");
                    clsName = clsName.Replace("First Place Processing", "FPP");
                    clsName = clsName.Replace("First Contact", "FC");
                    clsName = clsName.Replace("Qualifier", "Q");

                    if (part > 0 && EntryType != 10)
                    {
                        clsName += "Pt " + part;
                    }

                    if (dogsList.Tables[0].Rows.Count > 0)
                    {
                        /*
                        Combined 1-7 All Allsorts Agility sponsored by paws for a walk
                        Combined 6-7 Medium Agility

                            * */
                        var WrapClassDescription = clsName.Length > 45;
                        Phrase[] tmpCells = new Phrase[3];
                        tmpCells[0] = new Phrase(new Chunk(ringRow["ClsNo"].ToString(), dogInClass));
                        tmpCells[1] = new Phrase(new Chunk(clsName, dogInClass));
                        tmpCells[2] = new Phrase(new Chunk(dogsInClassDisplay, dogNotInClass ));

                        int countDogs = 0;
                        int DefaultHandler;

                        Paragraph p = new Paragraph();
                        List<Paragraph> allDogsInClass = new List<Paragraph>();
                        foreach (DataRow dogRow in dogsList.Tables[0].Rows)
                        {
                            var dogLho = Convert.ToInt32(dogRow["Lho"]);
                            int DogID = Convert.ToInt32(dogRow["DogID"]);
                            DefaultHandler = Convert.ToInt32(dogRow["DefaultHandler"]);
                            if (DefaultHandler == 0) DefaultHandler = -1;
                            if ((DefaultHandler == -1 && currentUser.UserID == UserID) ||
                                (DefaultHandler == UserID)
                                )
                            {
                                if (countDogs == 0)
                                {
                                    cell = new PdfPCell(tmpCells[0]);
                                    cell.BorderWidth = 0;
                                    cell.HorizontalAlignment = PdfPCell.ALIGN_RIGHT;
                                    classDetailsTable.AddCell(cell);
                                    var namePara = new Paragraph();
                                    namePara.Add(tmpCells[1]);
                                    namePara.Add(new Phrase(new Chunk(lhoInd, lhoFontBold)));
                                    p.Add(namePara);
                                }
                                if (!dogsRunningToday.Contains(DogID))
                                {
                                    dogsRunningToday.Add(DogID);
                                }
                                String dogName = dogRow["DogName"].ToString();
                                if (dogName.Length == 0)
                                {
                                    dogName = dogRow["KCName"].ToString();
                                }
                                var chunk = new Chunk("   ", dogDetailsInClass);
                                chunk.SetBackground(new Color(System.Drawing.ColorTranslator.FromHtml(dogRow["DogColour"].ToString())));

                                var dogPara = new Paragraph();
                                dogPara.Add(new Phrase(chunk));

                                if (TeamPairsManager.isMultiDog( EntryType ))
                                {
                                    pairsTeams.Add(new TeamPairsTrioDto
                                    {
                                        ClassId = ClassID,
                                        ClassNo = ClassNo,
                                        DogId = DogID,
                                        DogName = dogName,
                                        RO = -1
                                    });
                                }
                                dogPara.Add(new Phrase(new Chunk(String.Format(" [{1}] {0}", Fpp.Core.Utils.TitleCaseString(dogName), dogRow["RO"]), dogDetailsInClass)));
                                dogPara.Add(new Phrase(new Chunk(String.Format("{0}", (dogLho == 0 ? "" : " (LHO)")), font8)));
                                dogPara.Add(Chunk.NEWLINE);

                                int AltHandler = Convert.ToInt32(dogRow["AltHandler"]);
                                String HandlerName = "";
                                if (AltHandler > 0)
                                {
                                    User u = new User(AltHandler);
                                    HandlerName = u.Name;
                                    dogPara.Add(new Phrase(new Chunk(String.Format("Handler:{0}", Fpp.Core.Utils.TitleCaseString(HandlerName)), dogInClass)));
                                }
                                allDogsInClass.Add(dogPara);
                                countDogs++;
                            }
                            else
                            {
                                if (defaultUsers != null && defaultUsers.IndexOf(DefaultHandler) == -1)
                                {
                                    defaultUsers.Add(DefaultHandler);
                                }
                            }
                        }
                        if (countDogs == 0)
                        {
                            cell = new PdfPCell(new Phrase(new Chunk(ringRow["ClsNo"].ToString(), dogNotInClass)));
                            cell.BorderWidth = 0;
                            cell.HorizontalAlignment = PdfPCell.ALIGN_RIGHT;
                            classDetailsTable.AddCell(cell);

                            var namePara = new Paragraph();
                            namePara.Add(new Phrase(new Chunk(clsName, dogNotInClass)));
                            namePara.Add(new Phrase(new Chunk(lhoInd, lhoFontBold)));
                            p.Add(namePara);
                            cell = new PdfPCell(p);
                            cell.BorderWidth = 0;
                            cell.HorizontalAlignment = PdfPCell.ALIGN_LEFT;
                            cell.NoWrap = false;
                            classDetailsTable.AddCell(cell);

                            cell = new PdfPCell(new Phrase(new Chunk(dogsInClassDisplay, dogNotInClass)));
                            cell.BorderWidth = 0;
                            cell.HorizontalAlignment = PdfPCell.ALIGN_RIGHT;
                            classDetailsTable.AddCell(cell);
                        }
                        else
                        {

                            cell = new PdfPCell(p);
                            cell.BorderWidth = 0;
                            cell.HorizontalAlignment = PdfPCell.ALIGN_LEFT;
                            cell.NoWrap = false;

                            classDetailsTable.AddCell(cell);

                            cell = new PdfPCell(tmpCells[2]);
                            cell.BorderWidth = 0;
                            cell.HorizontalAlignment = PdfPCell.ALIGN_RIGHT;
                            classDetailsTable.AddCell(cell);

                            cell = new PdfPCell(new Phrase(new Chunk("", dogDetailsInClass)));
                            cell.BorderWidth = 0;
                            cell.HorizontalAlignment = PdfPCell.ALIGN_LEFT;
                            cell.NoWrap = false;
                            classDetailsTable.AddCell(cell);

                            var tbl4Dogs = new PdfPTable(1);
                            foreach (var item in allDogsInClass)
                            {
                                cell = new PdfPCell(new Phrase(item));
                                cell.BorderWidth = 0;
                                cell.HorizontalAlignment = PdfPCell.ALIGN_LEFT;
                                tbl4Dogs.AddCell(cell);
                            }
                            cell = new PdfPCell();
                            cell.BorderWidth = 0;
                            cell.FixedHeight = 4f;
                            tbl4Dogs.AddCell(cell);

                            cell = new PdfPCell(tbl4Dogs);
                            cell.BorderWidth = 0;
                            cell.Colspan = 2;
                            classDetailsTable.AddCell(cell);
                        }
                    }
                    else
                    {
                        cell = new PdfPCell(new Phrase(new Chunk(ringRow["ClsNo"].ToString(), dogNotInClass)));
                        cell.BorderWidth = 0;
                        cell.HorizontalAlignment = PdfPCell.ALIGN_RIGHT;
                        classDetailsTable.AddCell(cell);

                        var namePara = new Paragraph();
                        namePara.Add(new Phrase(new Chunk(clsName, dogNotInClass)));
                        namePara.Add(new Phrase(new Chunk(lhoInd, lhoFontBold)));
                        cell = new PdfPCell(namePara);
                        cell.BorderWidth = 0;
                        cell.HorizontalAlignment = PdfPCell.ALIGN_LEFT;
                        cell.NoWrap = false;
                        classDetailsTable.AddCell(cell);

                        cell = new PdfPCell(new Phrase(new Chunk(dogsInClassDisplay, dogNotInClass)));
                        cell.BorderWidth = 0;
                        cell.HorizontalAlignment = PdfPCell.ALIGN_RIGHT;
                        classDetailsTable.AddCell(cell);

                    }

                    PrevShowDetailsID = ShowDetailsID;
                }

                if (dogsRunningToday.Count() > 0 || UserID == -1)
                {
                    if (ringCnt % MaxColumns != 0)
                    {
                        var remind = ringCnt % MaxColumns;
                        while (remind-- > 0)
                        {
                            cell = new PdfPCell(new Phrase(new Chunk(" ", pageFont)));
                            cell.BorderWidth = 0;
                            rings.AddCell(cell);
                        }
                        doc.Add(headerPage);
                        doc.Add(rings);
                    }

                    if (UserID > -1)
                    {
                        if (currentUser.UserID != UserID)
                        {
                            User defaultHandler = new User(UserID);
                        }
                    }
                    doc.NewPage();
                    pageCount++;
                }
                else
                {
                    if (dogsRunningToday.Count() > 0)
                    {
                        if (ringCnt % MaxColumns != 0)
                        {
                            var remind = ringCnt % MaxColumns;
                            while (remind-- > 0)
                            {
                                cell = new PdfPCell(new Phrase(new Chunk(" ", pageFont)));
                                cell.BorderWidth = 0;
                                rings.AddCell(cell);
                            }
                            doc.Add(headerPage);
                            doc.Add(rings);
                        }

                        if (UserID > -1)
                        {
                            if (currentUser.UserID != UserID)
                            {
                                User defaultHandler = new User(UserID);
                            }
                        }
                        doc.NewPage();
                        pageCount++;
                    }
                }
            }
            catch (Exception e)
            {
                AppException.LogError($"Error Running Plan:{e.Message},{e.StackTrace}");
            }
        }
Exemplo n.º 10
0
        private void insertarPrimerosCodigosDeBarra(bool EtiquetaMultiples)
        {
            this.generarPrimerosCodigosDeBarra(true);
            List<string> bcdUsados = new List<string>();
            foreach (Etiqueta_C.Estructura_etqMultiple etqM in ListaEtiquetasMultiples)
            {
                string path = @rutasEnModAdmin.RutaDePlantillas + "/temp_EtiquetaActual" + ListaEtiquetasMultiples.IndexOf(etqM) + ".docx";
                appWord.DisplayAlerts = Word.WdAlertLevel.wdAlertsNone;
                appWord.Visible = false;

                doc = appWord.Documents.Open(path);
                List<Word.Shape> lst = new List<Word.Shape>();

                foreach (Word.Shape sh in doc.Shapes)
                {
                    if (sh.Type.ToString() == "msoPicture")
                    {
                        while (sh.Name.Contains("\n"))
                            sh.Name = sh.Name.Replace("\n", "");
                        lst.Add(sh);
                    }
                }
                foreach (string bcd in lista_camposCodBarr)
                {
                    foreach (Control txt in gb_CamposAdicionales.Controls.OfType<TextBox>())
                    {
                        if (!txt.Name.Contains(bcd.Replace("bcd", "")))
                            continue;
                        try
                        {
                            bcdUsados.Add(bcd);
                            float left, top, h, w;
                            string tempname = "";
                            List<Word.Range> ranges = new List<Word.Range>();
                            Word.Shape removed = null;
                            foreach (Word.Shape sh in lst)
                            {
                                if (sh.Name == bcd)
                                {
                                    left = sh.Left;
                                    top = sh.Top;
                                    h = sh.Height;
                                    w = sh.Width;
                                    sh.ConvertToInlineShape();
                                    foreach (Word.InlineShape s in doc.InlineShapes)
                                    {
                                        if (s.Type == Word.WdInlineShapeType.wdInlineShapePicture)
                                        {
                                            tempname = sh.Name;
                                            ranges.Add(s.Range);
                                            s.Delete();
                                            removed = sh;
                                        }
                                    }
                                    foreach (Word.Range r in ranges)
                                    {
                                        if (File.Exists(@rutasEnModAdmin.RutaDeTemp + "/" + bcd + ".jpg"))
                                            r.InlineShapes.AddPicture(@rutasEnModAdmin.RutaDeTemp + "/" + bcd + ".jpg", Type.Missing, Type.Missing, Type.Missing);
                                    }
                                    ranges.Clear();
                                    Word.Shape pic;
                                    foreach (Word.InlineShape s in doc.InlineShapes)
                                    {
                                        if (s.Type == Word.WdInlineShapeType.wdInlineShapePicture)
                                        {
                                            pic = s.ConvertToShape();
                                            pic.Name = tempname;
                                            pic.Top = top;
                                            pic.Left = left;
                                            pic.Height = h;
                                            pic.Width = w;
                                        }
                                    }
                                }
                                
                            }
                            lst.Remove(removed);
                        }
                        catch (Exception ex)
                        {
                            MessageBox.Show(ex.Message + "\n\n" + ex.ToString());
                        }
                    }
                }
                doc.Save();
                doc.Saved = true;
                ((Microsoft.Office.Interop.Word._Document)doc).Close();
                
            }
            foreach (string str in bcdUsados)
                lista_camposCodBarr.Remove(str);

        }
Exemplo n.º 11
0
        private void insertarCodigosDeBarraAWordMasDeUnaEtq(Word.Document doc, int indice ,int etqActual, bool nuevaHoja)
        {
            bool continuar = false;
            while (!continuar)
            {
                if (indice == 0)
                    continuar = true;
                else
                {
                    if (dgv_PesosLotes.Rows[indice - 1].DefaultCellStyle.BackColor == Color.Orange
                        && (indice % 2 != 0 || indice == 1))
                        continuar = false;
                    else
                        continuar = true;
                }
            }

            List<Word.Shape> lst = new List<Word.Shape>();
            foreach (Word.Shape sh in doc.Shapes)
            {
                while (sh.Name.Contains("\n"))
                    sh.Name = sh.Name.Replace("\n", "");
                if (sh.Type.ToString() == "msoPicture")
                    lst.Add(sh);
            }


            List<Word.Range> ranges = new List<Microsoft.Office.Interop.Word.Range>();
            float left, top, h, w;
            bool insertado = false;
            string tempname = "";
            List<Word.Shape> removedShapes = new List<Word.Shape>();
            try
            {
                foreach (string bcd in lista_camposCodBarr)
                {
                    insertado = false;
                    ranges.Clear();
                    foreach (Word.Shape sh in lst)
                    {
                        if (sh.Name == bcd + etqActual)
                        {
                            left = sh.Left;
                            top = sh.Top;
                            h = sh.Height;
                            w = sh.Width;
                            sh.ConvertToInlineShape();
                            foreach (Word.InlineShape s in doc.InlineShapes)
                            {
                                if (s.Type == Word.WdInlineShapeType.wdInlineShapePicture)
                                {
                                    tempname = sh.Name;
                                    ranges.Add(s.Range);
                                    s.Delete();
                                    removedShapes.Add(sh);
                                }
                            }
                            foreach (Word.Range r in ranges)
                            {
                                r.InlineShapes.AddPicture(@rutasEnModAdmin.RutaDeTemp + "/" + indice + bcd + ".jpg", Type.Missing, Type.Missing, Type.Missing);
                                insertado = true;
                            }
                            Word.Shape pic;
                            ranges.Clear();
                            foreach (Word.InlineShape s in doc.InlineShapes)
                            {
                                if (s.Type == Word.WdInlineShapeType.wdInlineShapePicture)
                                {
                                    pic = s.ConvertToShape();
                                    pic.Name = tempname;
                                    pic.Top = top;
                                    pic.Left = left;
                                    pic.Height = h;
                                    pic.Width = w;
                                }
                            }
                            if (insertado)
                                break;
                        }
                    }
                    foreach (Word.Shape s in removedShapes)
                        lst.Remove(s);
                    
                }
                if (dgv_PesosLotes.InvokeRequired)
                {
                    this.Invoke(new Action(() => dgv_PesosLotes.Rows[indice].DefaultCellStyle.BackColor = Color.White));
                    this.Invoke(new Action(() => dgv_PesosLotes.Rows[indice].Cells[1].ReadOnly = false));
                    this.Invoke(new Action(() => dgv_PesosLotes.Rows[indice].Cells[2].ReadOnly = false));
                    this.Invoke(new Action(() => dgv_PesosLotes.Rows[indice].Cells[4].ReadOnly = false));
                    this.Invoke(new Action(() => dgv_PesosLotes.Rows[indice].Cells[5].ReadOnly = false));
                    this.Invoke(new Action(() => dgv_PesosLotes.Rows[indice].Cells[6].ReadOnly = false));
                }
                else
                {
                    dgv_PesosLotes.Rows[indice].DefaultCellStyle.BackColor = Color.White;
                    dgv_PesosLotes.Rows[indice].Cells[1].ReadOnly = false;
                    dgv_PesosLotes.Rows[indice].Cells[2].ReadOnly = false;
                    dgv_PesosLotes.Rows[indice].Cells[4].ReadOnly = false;
                    dgv_PesosLotes.Rows[indice].Cells[5].ReadOnly = false;
                    dgv_PesosLotes.Rows[indice].Cells[6].ReadOnly = false;
                }
            }
            catch
            {
                this.Invoke(new Action(() => dgv_PesosLotes.Rows[indice].DefaultCellStyle.BackColor = Color.Red));
                this.Invoke(new Action(() => dgv_PesosLotes.Rows[indice].Cells[1].ReadOnly = false));
                this.Invoke(new Action(() => dgv_PesosLotes.Rows[indice].Cells[2].ReadOnly = false));
                this.Invoke(new Action(() => dgv_PesosLotes.Rows[indice].Cells[4].ReadOnly = false));
                this.Invoke(new Action(() => dgv_PesosLotes.Rows[indice].Cells[5].ReadOnly = false));
                this.Invoke(new Action(() => dgv_PesosLotes.Rows[indice].Cells[6].ReadOnly = false));
                foreach (DataGridViewCell cell in dgv_PesosLotes.Rows[indice].Cells)
                {
                    this.Invoke(new Action(() => cell.Value = null));
                }
                return;
            }
        }
Exemplo n.º 12
0
        private void insertarCodigosDeBarraAWord(Word.Document doc)
        {
            try
            {
                bool x = this.generarCodigosDeBarra();
                List<Word.Shape> lst = new List<Word.Shape>();
                List<Word.Range> ranges = new List<Microsoft.Office.Interop.Word.Range>();

                float left, top, h, w;
                bool insertado = false;
                string tempname = "";

                foreach (CamposCodigos bcds in ListaCodigos)
                {
                    insertado = false;
                    ranges.Clear();
                    foreach (Word.Shape sh in doc.Shapes)
                    {
                        if (sh.Type.ToString() == "msoPicture")
                        {
                            sh.Name = sh.Name.Trim();
                            if (sh.Name == bcds.nombrecodigo)
                            {
                                left = sh.Left;
                                top = sh.Top;
                                h = sh.Height;
                                w = sh.Width;
                                sh.ConvertToInlineShape();
                                foreach (Word.InlineShape s in doc.InlineShapes)
                                {
                                    if (s.Type == Word.WdInlineShapeType.wdInlineShapePicture)
                                    {
                                        tempname = sh.Name;
                                        ranges.Add(s.Range);
                                        s.Delete();
                                    }
                                }
                                foreach (Word.Range r in ranges)
                                {
                                    if (File.Exists(@rutasEnModAdmin.RutaDeTemp + "/" + bcds.nombrecodigo + ".jpg"))
                                        r.InlineShapes.AddPicture(@rutasEnModAdmin.RutaDeTemp + "/" + bcds.nombrecodigo + ".jpg", Type.Missing, Type.Missing, Type.Missing);
                                    insertado = true;
                                }
                                Word.Shape pic;
                                foreach (Word.InlineShape s in doc.InlineShapes)
                                {
                                    if (s.Type == Word.WdInlineShapeType.wdInlineShapePicture)
                                    {
                                        pic = s.ConvertToShape();
                                        pic.Name = tempname;
                                        pic.Top = top;
                                        pic.Left = left;
                                        pic.Height = h;
                                        pic.Width = w;
                                    }
                                }
                            }

                        }
                        if (insertado)
                            break;
                    }

                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
                return;
            }
            foreach (CamposCodigos camp in ListaCodigos)
            {
                if (File.Exists(@rutasEnModAdmin.RutaDeTemp + "/" + camp.nombrecodigo + ".jpg"))
                    File.Delete(@rutasEnModAdmin.RutaDeTemp + "/" + camp.nombrecodigo + ".jpg");
            }
        }
        private void printRingForUser(UserShows userShow, int UserID, Document doc, ref List<int> defaultUsers, ref int pageCount)
        {
            String html = "";
            float[] ringColumns = new float[] { 300, 300, 300, 300};

            Font pageFont = FontFactory.GetFont("Arial", 22, Font.NORMAL);
            Font headerFont = new Font(Font.HELVETICA, 16, Font.BOLD, Color.BLACK);
            Font judgeFont = FontFactory.GetFont("Arial", 9, Font.BOLD);
            Font notInClassFont = new Font(Font.HELVETICA, 6, Font.NORMAL, Color.BLACK);
            Font inClassFont = new Font(Font.HELVETICA, 9, Font.NORMAL, Color.BLACK);
            Font font = new Font(Font.HELVETICA, 10, Font.NORMAL, Color.BLACK);
            Font font1 = FontFactory.GetFont("Arial", 18, Font.BOLD);
            Font dogNotInClass = new Font(Font.HELVETICA, 6, Font.NORMAL, Color.BLACK);
            Font dogInClass = new Font(Font.HELVETICA, 9, Font.NORMAL, Color.BLACK);
            Font dogDetailsInClass = new Font(Font.HELVETICA, 9, Font.BOLD, Color.BLACK);
            Fpp.WebModules.Business.User currentUser = new User(userShow.Userid);
            Shows show = new Shows(userShow.ShowID);

            List<ShowDetails> showDetailsList = ShowDetails.GetShowDaysList(userShow.ShowID);
            doc.Add(new Paragraph(show.ShowName, pageFont));

            Rings r = new Rings();
            DataSet ringList = r.GetAllRingsForShow(userShow.ShowID, "ShowDate");

            Dogs d = new Dogs();

            DogClasses dc = new DogClasses();
            DateTime dt = DateTime.Now;
            int currentRingID = 0;
            int ShowDetailsID = -1;
            int PrevShowDetailsID = -1;
            PdfPTable rings = new PdfPTable(ringColumns);

            int ringCnt = 0;
            PdfPCell cell = null;
            PdfPTable ringDetails = null;
            PdfPTable classDetailsTable = null;
            List<int> dogsRunningToday = new List<int>();
            foreach (DataRow ringRow in ringList.Tables[0].Rows)
            {
                int RingID = Convert.ToInt32(ringRow["RingID"]);
                ShowDetailsID = Convert.ToInt32(ringRow["ShowDetailsID"]);

                if (ringRow.IsNull("ClassID"))
                {
                    continue;
                }
                int ClassID = Convert.ToInt32(ringRow["ClassID"]);
                DateTime rowDT = Convert.ToDateTime(ringRow["ShowDate"]);
                if (rowDT != dt)
                {
                    if (currentRingID != 0)
                    {
                        if (ringCnt % 4 != 0)
                        {
                            var remind = ringCnt % 4;
                            while (remind-- > 0)
                            {
                                cell = new PdfPCell(new Phrase(new Chunk(" ", pageFont)));
                                cell.BorderWidth = 0;
                                rings.AddCell(cell);
                            }
                        }

                        doc.Add(rings);
                        if (currentUser.UserID == UserID)
                        {
                            doc.Add(getHandlerDetails(userShow, currentUser, PrevShowDetailsID, dogsRunningToday));
                        }
                        else
                        {
                            User defaultHandler = new User(UserID);
                            doc.Add(getHandlerDetails(userShow, defaultHandler, PrevShowDetailsID, dogsRunningToday));
                        }
                        doc.NewPage();
                        if (dogsRunningToday.Count > 0)
                        {
                            pageCount++;
                        }
                    }
                    dogsRunningToday.Clear();
                    doc.Add(new Paragraph(rowDT.ToString("dddd d MMM"), headerFont));
                    doc.Add(new Paragraph("  ", judgeFont));
                    dt = rowDT;
                    rings = new PdfPTable(ringColumns);
                    rings.WidthPercentage = 100;
                    ringCnt = 0;
                }

                if (currentRingID != RingID)
                {
                    ringCnt++;
                    ringDetails = new PdfPTable(1);
                    rings.AddCell(new PdfPCell( ringDetails));

                    List<Judge> judgeList = Judge.getJudgesForRingList(RingID);

                    cell = new PdfPCell(new Phrase(new Chunk("Ring No " + ringRow["RingNo"].ToString(), judgeFont)));
                    cell.BorderWidth = 0;
                    cell.HorizontalAlignment = PdfPCell.ALIGN_CENTER;
                    ringDetails.AddCell(cell);

                    foreach (Judge judge in judgeList)
                    {
                        cell = new PdfPCell(new Phrase(new Chunk(judge.Name, judgeFont)));
                        cell.BorderWidth = 0;
                        cell.HorizontalAlignment = PdfPCell.ALIGN_CENTER;
                        ringDetails.AddCell(cell);
                    }
                    currentRingID = RingID;
                    classDetailsTable = new PdfPTable(new float[] { 50, 225, 100 });
                    classDetailsTable.DefaultCell.BorderWidth = 0;
                    ringDetails.AddCell(classDetailsTable);
                }
                html += "<tr>";
                DataSet dogsList = d.GetDogsInClass(userShow.Userid, ClassID);
                int DogsInClass = d.dogsInClassCount(ClassID);

                String clsName = String.Format("{0} {1} {2} {3}",
                                ShowClasses.expandCatagory(ringRow),
                                ShowClasses.expandHeight(ringRow),
                                ringRow["LongName"],
                                ringRow["name"]);
                String grades = ShowClasses.shortenGrades(ringRow);
                int ix = clsName.IndexOf("Grd");
                if (ix == -1) ix = clsName.IndexOf("Cmb");
                if (ix > -1)
                {
                    clsName = clsName.Substring(0, ix + 3) + " " + grades + " " + clsName.Substring(ix + 4);
                }
                else
                {
                    ix = clsName.IndexOf(" ");
                    clsName = clsName.Substring(0, ix) + " " + grades + " " + clsName.Substring(ix + 1);
                }

                if (dogsList.Tables[0].Rows.Count > 0)
                {
                    Phrase[] tmpCells = new Phrase[3];
                    tmpCells[0] = new Phrase(new Chunk(ringRow["ClsNo"].ToString(), dogInClass));
                    tmpCells[1] = new Phrase(new Chunk(clsName, dogInClass));
                    tmpCells[2] = new Phrase(new Chunk(String.Format("({0})", DogsInClass), dogInClass));

                    int countDogs = 0;
                    int DefaultHandler;
                    Paragraph p = new Paragraph();
                    foreach (DataRow dogRow in dogsList.Tables[0].Rows)
                    {
                        int DogID = Convert.ToInt32(dogRow["DogID"]);
                        DefaultHandler = Convert.ToInt32(dogRow["DefaultHandler"]);
                        if (DefaultHandler == 0) DefaultHandler = -1;
                        if ((DefaultHandler == -1 && currentUser.UserID == UserID) ||
                            (DefaultHandler == UserID)
                            )
                        {
                            if (countDogs == 0)
                            {
                                cell = new PdfPCell(tmpCells[0]);
                                cell.BorderWidth = 0;
                                cell.HorizontalAlignment = PdfPCell.ALIGN_RIGHT;
                                classDetailsTable.AddCell(cell);
                                p.Add(tmpCells[1]);
                                p.Add(Chunk.NEWLINE);
                            }
                            if (!dogsRunningToday.Contains(DogID))
                            {
                                dogsRunningToday.Add(DogID);
                            }
                            String img = "<img src='data:image/gif;base64," + CreateImage(dogRow["DogColour"].ToString()) + "' />";
                            String dogName = dogRow["DogName"].ToString();
                            if (dogName.Length == 0)
                            {
                                dogName = dogRow["KCName"].ToString();
                            }
                            var chunk = new Chunk("   ", dogDetailsInClass);
                            chunk.SetBackground(new Color( System.Drawing.ColorTranslator.FromHtml(dogRow["DogColour"].ToString())  ));
                            p.Add(new Phrase(chunk));
                            p.Add(new Phrase(new Chunk(String.Format(" [{1}] {0}", dogName, dogRow["RO"]), dogDetailsInClass)));
                            p.Add(Chunk.NEWLINE);

                            int AltHandler = Convert.ToInt32(dogRow["AltHandler"]);
                            String HandlerName = "";
                            if (AltHandler > 0)
                            {
                                User u = new User(AltHandler);
                                HandlerName = u.Name;

                                html += "<div class='altHandler'>Handler:" + AltHandler + "</div>";
                                p.Add(Chunk.NEWLINE);
                                p.Add(new Phrase(new Chunk(String.Format("Handler:", AltHandler),dogInClass)));
                            }
                            countDogs++;
                        }
                        else
                        {
                            if (defaultUsers != null && defaultUsers.IndexOf(DefaultHandler) == -1)
                            {
                                defaultUsers.Add(DefaultHandler);
                            }
                        }
                    }
                    if (countDogs == 0)
                    {
                        cell = new PdfPCell(new Phrase(new Chunk(ringRow["ClsNo"].ToString(), dogNotInClass)));
                        cell.BorderWidth = 0;
                        cell.HorizontalAlignment = PdfPCell.ALIGN_RIGHT;
                        classDetailsTable.AddCell(cell);

                        cell = new PdfPCell(new Phrase(new Chunk(clsName, dogNotInClass)));
                        cell.BorderWidth = 0;
                        cell.HorizontalAlignment = PdfPCell.ALIGN_LEFT;
                        cell.NoWrap = true;
                        classDetailsTable.AddCell(cell);

                        cell = new PdfPCell(new Phrase(new Chunk(String.Format("({0})", DogsInClass), dogNotInClass)));
                        cell.BorderWidth = 0;
                        cell.HorizontalAlignment = PdfPCell.ALIGN_RIGHT;
                        classDetailsTable.AddCell(cell);
                    }
                    else
                    {

                        cell = new PdfPCell(p);
                        cell.BorderWidth = 0;
                        cell.HorizontalAlignment = PdfPCell.ALIGN_LEFT;
                        cell.NoWrap = true;
                        classDetailsTable.AddCell(cell);

                        cell = new PdfPCell(tmpCells[2]);
                        cell.BorderWidth = 0;
                        cell.HorizontalAlignment = PdfPCell.ALIGN_RIGHT;
                        classDetailsTable.AddCell(cell);
                    }
                }
                else
                {
                    cell = new PdfPCell(new Phrase(new Chunk(ringRow["ClsNo"].ToString(), dogNotInClass)));
                    cell.BorderWidth = 0;
                    cell.HorizontalAlignment = PdfPCell.ALIGN_RIGHT;
                    classDetailsTable.AddCell(cell);

                    cell = new PdfPCell(new Phrase(new Chunk(clsName, dogNotInClass)));
                    cell.BorderWidth = 0;
                    cell.HorizontalAlignment = PdfPCell.ALIGN_LEFT;
                    classDetailsTable.AddCell(cell);

                    cell = new PdfPCell(new Phrase(new Chunk(String.Format("({0})", DogsInClass), dogNotInClass)));
                    cell.BorderWidth = 0;
                    cell.HorizontalAlignment = PdfPCell.ALIGN_RIGHT;
                    classDetailsTable.AddCell(cell);
                }

                PrevShowDetailsID = ShowDetailsID;
            }

            if (ringCnt % 4 != 0)
            {
                var remind = ringCnt % 4;
                while (remind-- > 0)
                {
                    cell = new PdfPCell(new Phrase(new Chunk(" ", pageFont)));
                    cell.BorderWidth = 0;
                    rings.AddCell(cell);

                }
            }

            if (currentUser.UserID == UserID)
            {
                doc.Add(getHandlerDetails(userShow, currentUser, PrevShowDetailsID, dogsRunningToday));
            }
            else
            {
                User defaultHandler = new User(UserID);
                doc.Add(getHandlerDetails(userShow, defaultHandler, PrevShowDetailsID, dogsRunningToday));
            }
            doc.NewPage();
        }
Exemplo n.º 14
0
        public void ExecuteCommand()
        {
           
            try
            {
                commandType = "[General Settings] ";
                LogHelper.Logger(commandType + "Saving logs at " + _logPath, _logPath);
                LogHelper.Logger(commandType + "Saving pdfs at " + _saveLocation, _logPath);
                var avianCommand = _helperAvian.Command;
                var seasonalCommand = _helperSeasonal.Command;
                var countryCommand = _helperCountry.Command;
                //add all temporary filenames in a list;
                var filenames = new List<string>();
                filenames.Add(_saveLocation + avianFilename + _filetype);
                filenames.Add(_saveLocation + seasonalFilename + _filetype);
                filenames.Add(_saveLocation + countryFilename + _filetype);
                commandType = "[PDF Generation] ";
                //LogHelper.Logger(commandType + avianCommand, _logPath);
                //LogHelper.Logger(commandType + seasonalCommand, _logPath);
                //LogHelper.Logger(commandType + countryCommand, _logPath);
                LogHelper.Logger(commandType + "Generating pdf.", _logPath);


                //avianCommand = "dir";
                try
                {
                    CommandHelper.ExecuteCommandSync(_tabserver, avianCommand);
                    CommandHelper.ExecuteCommandSync(_tabserver, seasonalCommand);
                    CommandHelper.ExecuteCommandSync(_tabserver, countryCommand);
                    
                }
                catch (Exception e)
                {
                    
                    LogHelper.Logger(commandType + e.Message, _logPath);
                }
                
                //Create Weekly PDF
                var yearnow = DateTime.Now.Year.ToString();
                var filename = yearnow + "-" + _weekNumber + _filetype;
                var targetPdf = _saveLocation + filename;
                
                
                try
                {

                    var tries = 0;
                    var NextRun = DateTime.Now;
                    var Now = DateTime.Now;
                    var exist = false;
                    while (!exist && tries < NO_OF_TRIES)
                    {
                        if (NextRun <= Now)
                        {
                            tries++;
                         
                            if (CheckIfExist(avianFilename) && CheckIfExist(seasonalFilename) && CheckIfExist(countryFilename))
                            {
                                LogHelper.Logger(commandType + "Merging pdf.", _logPath);
                                if (PdfMerger(filenames.ToArray(), targetPdf))
                                {
                                    LogHelper.Logger(commandType + " weekly PDF generation success.", _logPath);
                                    //Delete temporary files
                                    foreach (string file in filenames)
                                    {
                                        File.Delete(file);
                                    }
                                    //Create Yearly PDF
                                    filenames.Clear();
                                    LogHelper.Logger(commandType + " summary PDF generation.", _logPath);
                                    filenames.Add(targetPdf);
                                    var yearSummary = _saveLocation + yearnow + _filetype;
                                    if (PdfMerger(filenames.ToArray(), yearSummary))
                                    {
                                        LogHelper.Logger(commandType + " PDF generation success.", _logPath);
                                    }
                                    else
                                        LogHelper.Logger(commandType + " PDF generation failed.", _logPath);

                                }
                                else
                                    LogHelper.Logger(commandType + " PDF generation failed.", _logPath);

                                exist = true;
                                break;
                            }
                            else
                            {
                                NextRun = Now.AddMinutes(_waitingTime);
                                Console.WriteLine("Waiting for report to be generated");
                            }
                        }
                        Now = DateTime.Now;
                        Thread.Sleep(new TimeSpan(0,_waitingTime,0));
                     
                        var parameters = new Dictionary<string, object>();
                        parameters.Add("@flu_year", Now.Year);
                        parameters.Add("@flu_week", _weekNumber);
                        parameters.Add("@archive_id", 0);
                        parameters.Add("@new_id", 0);
                        dataBL.SaveData(StoredProcedure.ArchiveSave, parameters);
                    }

                    if(tries == 5 && !exist)
                        LogHelper.Logger(commandType + " PDF generation failed.", _logPath);
                    
                }
                catch (Exception e)
                {
                    LogHelper.Logger(commandType + e.Message, _logPath);
                }
              

               
            }
            catch (Exception e)
            {
                LogHelper.Logger(commandType + e.Message, _logPath);
            }
           

        }
Exemplo n.º 15
0
 private void StatsDashboard_Load(object sender, EventArgs e)
 {
     c_analiza.SelectedIndex = 1;
     c_tip_analize.SelectedIndex = 1;
     lista_teksta = new List<Tekst>();
     lista_stats = new List<Statistika>();
     lista_stats_text = new List<Statistika>();
     lista_PDF = new List<StatistikaTekst>();
     podsuma = 0;
     OdbcConnection connection = new OdbcConnection();
     connection.ConnectionString = "DSN=PostgreSQL35W;UID=masterwordcounter;PWD=masterwordcounter";
     connection.Open();
     string q = "SELECT id,name,content,author FROM texts";
     OdbcCommand getAllTexts = new OdbcCommand(q, connection);
     OdbcDataReader odr = getAllTexts.ExecuteReader();
     lista_teksta.Clear();
     while (odr.Read())
     {
         Tekst t = new Tekst();
         t.Id = odr.GetInt32(0);
         t.Sadrzaj = odr.GetString(2);
         t.Naziv = odr.GetString(1);
         t.Autor = odr.GetString(3);
         lista_teksta.Add(t);
     }
     c_tekst.DataSource = null;
     c_tekst.DataSource = lista_teksta;
     connection.Close();
     odr.Close();
 }
Exemplo n.º 16
0
	    /*
	     * (non-Javadoc)
	     * 
	     * @see
	     * com.itextpdf.tool.xml.TagProcessor#endElement(com.itextpdf.tool.xml.Tag,
	     * java.util.List, com.itextpdf.text.Document)
	     */
	    public override IList<IElement> End(IWorkerContext ctx, Tag tag, IList<IElement> currentContent) {
		    HtmlCell cell = new HtmlCell();
            try {
                HtmlPipelineContext htmlPipelineContext = GetHtmlPipelineContext(ctx);
                cell = new HtmlCellCssApplier().Apply(cell, tag, htmlPipelineContext, htmlPipelineContext);
            } catch (NoCustomContextException e1) {
                throw new RuntimeWorkerException(LocaleMessages.GetInstance().GetMessage(LocaleMessages.NO_CUSTOM_CONTEXT), e1);
            }
		    IList<IElement> l = new List<IElement>(1);
            IList<IElement> chunks = new List<IElement>();
		    foreach (IElement e in currentContent) {
                if (e is Chunk || e is NoNewLineParagraph || e is LineSeparator) {
                    if (e == Chunk.NEWLINE) {
                        int index = currentContent.IndexOf(e);
                        if (index == currentContent.Count - 1) {
                            continue;
                        } else {
                            IElement nextElement = currentContent[index + 1];
                            if (nextElement is Paragraph) {
                                continue;
                            }
                            if (chunks.Count == 0) {
                                continue;
                            }

                        }
                    } else if (e is LineSeparator) {
                        chunks.Add(Chunk.NEWLINE);
                    }
                    chunks.Add(e);
                    continue;
                } else if (chunks.Count > 0) {
                    Paragraph p = new Paragraph();
                    p.MultipliedLeading = 1.2f;
                    p.AddAll(chunks);
                    p.Alignment = cell.HorizontalAlignment;
                    cell.AddElement(p);
                    chunks.Clear();
                }

                if (e is Paragraph) {
                    ((Paragraph)e).Alignment = cell.HorizontalAlignment;
                }

			    cell.AddElement(e);
		    }
            if ( chunks.Count > 0 ) {
                Paragraph p = new Paragraph();
                p.MultipliedLeading = 1.2f;
                p.AddAll(chunks);
                p.Alignment = cell.HorizontalAlignment;
                cell.AddElement(p);
            }
    	    l.Add(cell);
		    return l;
	    }
        private void btn_Scan_Click(object sender, EventArgs e)
        {
            if (buttonOnStop)
            {
                portScanner.Stop();
                userpressedStop = true;
                return;
            }

            userpressedStop = false;
            List<Service> ScanList = new List<Service>();
            bool allesStimmt = false;
            int start;
            int end;
            string iP;
            string iPEnd;
            int difPort;
            int difIP;
            string IP1 = string.Empty;
            string IP2 = string.Empty;
            string IP3 = string.Empty;
            string IP4 = string.Empty;
            string IPRange = string.Empty;
            string toSplit = string.Empty;
            ScanList.Clear();
            lv_Port.Items.Clear();
            info.Clear();
            int waitForNextThread = 0;
            int requestTimeout = Convert.ToInt32(numericUpDownRequestTimeout.Value);
            if (comboBoxScanAttitude.SelectedItem == comboBoxScanAttitude.Items[1])
                waitForNextThread = Convert.ToInt32(numericUpDownTimebetweenRequests.Value);

            if (radioButton_IPrange.Checked)
            {
                toSplit = maskedTextBoxIP.Text;
                IPRange = txt_IPrange.Text;
            }
            else
            {
                toSplit = DNSServer();
                IPRange = string.Empty;
            }

            if (toSplit == string.Empty)
                return;

            string[] splitme = toSplit.Split(new Char[]{'.'});
            foreach (string split in splitme)
            {
                if (split == string.Empty)
                {
                    MessageBox.Show("Parts of the IP were left empty", "Input failure",MessageBoxButtons.OK, MessageBoxIcon.Hand);
                    return;
                }
            }
            if (splitme.Length > 3)
            {
                IP1 = splitme[0].Replace(" ","");
                IP2 = splitme[1].Replace(" ","");
                IP3 = splitme[2].Replace(" ","");
                IP4 = splitme[3].Replace(" ","");
            }
            else { MessageBox.Show("Parts of the IP were left empty", "Input failure",MessageBoxButtons.OK, MessageBoxIcon.Hand);
            return;
            }

            if (IPRange == string.Empty)
                IPRange = splitme[3];
            try
            {   //bisschen verschachtelt alles was nicht zutrifft wirft ne Messagebox mit nem Fehler zurück
                if (Convert.ToInt32(IP4) <= Convert.ToInt32(IPRange))
                {
                    iP = IP1 + "." + IP2 + "." + IP3 + "." + IP4;
                    iPEnd = IP1 + "." + IP2 + "." + IP3 + "." + IPRange;

                    if (ipRichtig(iP) && ipRichtig(iPEnd))
                    {
                        allesStimmt = true;

                        if (radioButtonPortRange.Checked == true)
                        {
                            if(txt_Start.Text == string.Empty)
                            {
                                MessageBox.Show("You did choose a port range but the start port field is emtpy", "Input failure", MessageBoxButtons.OK, MessageBoxIcon.Hand);
                                return;
                            }
                            if (txt_End.Text == string.Empty)
                            {
                                txt_End.Text = txt_Start.Text;
                            }

                            if (portZahl(txt_End.Text) && portZahl(txt_Start.Text))
                            {

                                start = Convert.ToInt32(txt_Start.Text);
                                end = Convert.ToInt32(txt_End.Text);

                                if (start <= end)
                                {
                                    allesStimmt = true;

                                    ScanList.Clear();
                                    for (int i = start; i <= end; i++)
                                    {
                                        for (int iIP = Convert.ToInt32(IP4); iIP <= Convert.ToInt32(IPRange); iIP++)
                                        {
                                            Service service = new Service();
                                            service.ServiceName = ReturnService(i);
                                            service.Port = i;
                                            service.IP = IP1 + "." + IP2 + "." + IP3 + "." + iIP.ToString();
                                            ScanList.Add(service);
                                        }

                                    }
                                    if (start < 0 || end < 0)
                                    {
                                        allesStimmt = false;
                                        MessageBox.Show("The ports have to be positive", "Input failure",MessageBoxButtons.OK, MessageBoxIcon.Hand);
                                    }

                                }
                                else
                                {
                                    MessageBox.Show("The start port has to be lower than the end port", "Input failure", MessageBoxButtons.OK, MessageBoxIcon.Hand);
                                    allesStimmt = false;
                                }
                            }
                            else
                            {
                                MessageBox.Show("You have to enter numbers for the ports", "Input failure", MessageBoxButtons.OK, MessageBoxIcon.Hand);
                                allesStimmt = false;
                            }
                        }

                        if (radioButtonWebserverSelected.Checked == true)
                        {
                            ScanList.Clear();
                            for (int iIP = Convert.ToInt32(IP4); iIP <= Convert.ToInt32(IPRange); iIP++)
                            {
                                Service serviceHttp = new Service();
                                serviceHttp.ServiceName = ReturnService(80);
                                serviceHttp.Port = 80;
                                serviceHttp.IP = IP1 + "." + IP2 + "." + IP3 + "." + iIP.ToString(); ;
                                ScanList.Add(serviceHttp);
                            }
                            for (int iIP = Convert.ToInt32(IP4); iIP <= Convert.ToInt32(IPRange); iIP++)
                            {
                                Service serviceHttps = new Service();
                                serviceHttps.ServiceName = ReturnService(443);
                                serviceHttps.Port = 443;
                                serviceHttps.IP = IP1 + "." + IP2 + "." + IP3 + "." + iIP.ToString(); ;
                                ScanList.Add(serviceHttps);
                            }
                        }
                        if (raBuChoose.Checked == true)
                        {
                            ScanList.Clear();
                            foreach (int zahl in PortArray())
                            {
                                for (int iIP = Convert.ToInt32(IP4); iIP <= Convert.ToInt32(IPRange); iIP++)
                                {
                                    Service serviceHttps = new Service();
                                    serviceHttps.ServiceName = ReturnService(zahl);
                                    serviceHttps.Port = zahl;
                                    serviceHttps.IP = IP1 + "." + IP2 + "." + IP3 + "." + iIP.ToString();
                                    ScanList.Add(serviceHttps);
                                }
                            }
                        }
                        difPort = ScanList.Count / (Convert.ToInt32(IPRange) - Convert.ToInt32(IP4) + 1);
                        difIP = Convert.ToInt32(IPRange) - Convert.ToInt32(IP4) + 1;
                        prg_Scannning.Value = 0;
                        //das Maximum ist die Anzahl der IP´s mal die Anzahl der zu überprüfenden Ports
                        prg_Scannning.Maximum = difIP * difPort;
                        prg_Scannning.Step = 1;

                        if (allesStimmt == true)
                        {
                            LastFinishedIndex = 0;
                            portScanner.RequestTimeout = requestTimeout;
                            portScanner.Waitfornextthread = waitForNextThread;
                            portScanner.StartScan(ScanList);
                            btn_Scan.Text = "Stop";
                            buttonOnStop = true;
                            btn_Scan.Image = Properties.Resources.control_stop;
                            btn_Scan.ImageAlign = ContentAlignment.MiddleLeft;
                        }
                    }
                    else
                    {
                        MessageBox.Show("No valid IP", "Input failure", MessageBoxButtons.OK, MessageBoxIcon.Hand);
                        allesStimmt = false;
                    }
                }
                else
                {
                    MessageBox.Show("The start Ip has to be lower than the end IP", "Input failure", MessageBoxButtons.OK, MessageBoxIcon.Hand);
                    allesStimmt = false;
                }
            }
            catch (Exception)
            {
                MessageBox.Show("Please enter numbers for the IP", "Input failure");
                allesStimmt = false;
            }
        }
Exemplo n.º 18
0
        /// <summary>
        /// Parse out the html and format it using iTextSharp's stuff
        /// </summary>
        /// <remarks>
        /// http://blog.dmbcllc.com/2009/07/28/itextsharp-html-to-pdf-parsing-html/ (not being used)
        /// </remarks>
        /// <param name="text"></param>
        private void AddHtmlText(string text, PdfPCell pCell = null)
        {
            var elements = new List<HtmlElement>();

            var reader = new XmlTextReader(text, XmlNodeType.Element, null);
            while (reader.Read())
            {
                switch (reader.NodeType)
                {
                    // opening element
                    case XmlNodeType.Element:

                        elements.Add(new HtmlElement(reader.Name, true));

                        break;
                    // closing element
                    case XmlNodeType.EndElement:

                        elements.Add(new HtmlElement(reader.Name, true, true));

                        // is this a closing for a full iTextsharp element?
                        if (IsReadyToProcess(reader.Name))
                        {

                            if (listTags.Contains(reader.Name))
                            {
                                // build the list object
                                var paragraph = BuildListObject(elements, reader.Name, pCell);

                                if (pCell == null) _doc.Add(paragraph);

                                //if (pCell != null) pCell.AddElement(paragraph);
                                //else _doc.Add(paragraph);

                                elements.Clear();
                            }
                            else
                            {
                                var paragraph = BuildDocObject(elements, pCell);
                                if (pCell != null) pCell.AddElement(paragraph);
                                else _doc.Add(paragraph);

                                elements.Clear();
                            }

                        }

                        break;
                    case XmlNodeType.Text:

                        // add the text into the stack
                        elements.Add(new HtmlElement(reader.Value));

                        break;
                    case XmlNodeType.Whitespace:

                        // do nothing for now

                        break;
                }
            }
        }
Exemplo n.º 19
0
        private void printHorizontalStackPanel()
        {
            if (SharedData.PageSetup.MainTablePreferences.TableType != TableType.HorizontalStackPanel)
                return;

            var hasTableRowNumberColumn = SharedData.HasTableRowNumberColumn;
            var columnsNumber = SharedData.HorizontalStackPanelColumnsPerRow;
            if (hasTableRowNumberColumn)
                columnsNumber--;

            var itemsToTake = columnsNumber;
            var customRow = new List<CellData>();

            foreach (var row in SharedData.MainTableDataSource.Rows())
            {
                if (row == null) continue;
                var rowObjectColumnsCount = row.Count;
                var tempRow = row.Take(itemsToTake).ToList();
                var diff = (columnsNumber * rowObjectColumnsCount) - customRow.Count - tempRow.Count;
                bool rowIsReady;
                if (diff == 0)
                {
                    rowIsReady = true;
                    itemsToTake = columnsNumber;
                }
                else
                {
                    itemsToTake = diff;
                    rowIsReady = false;
                }
                customRow.AddRange(tempRow);

                if (!rowIsReady) continue;
                var index = hasTableRowNumberColumn ? 1 : 0;
                for (int i = 0; i < customRow.Count; i++)
                {
                    if ((i > 0) && (i % rowObjectColumnsCount == 0))
                        index++; // All columns of an object will create a single cell here.
                    customRow[i].PropertyIndex = index;
                }

                fireRowStartedInjectCustomRowsEvent(customRow);
                addSingleRow(customRow);
                fireRowAddedInjectCustomRowsEvent(customRow);

                customRow.Clear();
            }
        }
        public void formatIndicator(Int16 indicatorID, Int16 formatID)
        {
            var indicator = db.Indicators.FirstOrDefault(x => x.Indicator_ID == indicatorID);
            var fieldList = new List<string>();

            var format = db.Formats.FirstOrDefault(x => x.Format_ID == formatID).Format_Code;
            if (format != null)
            {

                for (var fiscalYear = 1; fiscalYear < 99; fiscalYear++)
                {
                    fieldList.Clear();
                    fieldList.Add(FiscalYear.FYStrFull("FY_3", fiscalYear));
                    fieldList.Add(FiscalYear.FYStrFull("FY_2", fiscalYear));
                    fieldList.Add(FiscalYear.FYStrFull("FY_1", fiscalYear));
                    fieldList.Add(FiscalYear.FYStrFull("FY_", fiscalYear) + "Q1");
                    fieldList.Add(FiscalYear.FYStrFull("FY_", fiscalYear) + "Q2");
                    fieldList.Add(FiscalYear.FYStrFull("FY_", fiscalYear) + "Q3");
                    fieldList.Add(FiscalYear.FYStrFull("FY_", fiscalYear) + "Q4");
                    fieldList.Add(FiscalYear.FYStrFull("FY_", fiscalYear) + "YTD");
                    fieldList.Add(FiscalYear.FYStrFull("FY_", fiscalYear) + "Target");
                    fieldList.Add(FiscalYear.FYStrFull("FY_", fiscalYear) + "Performance_Threshold");
                    fieldList.Add(FiscalYear.FYStrFull("FY_", fiscalYear) + "Comparator");

                    var type = indicator.GetType();

                    var fieldTest = FiscalYear.FYStrFull("FY_", fiscalYear) + "Q1";
                    var propertyTest = type.GetProperty(fieldTest);
                    if (propertyTest == null)
                    {
                        fiscalYear = 100;
                    }
                    else
                    {
                        foreach (var field in fieldList)
                        {
                            var property = type.GetProperty(field);
                            if (property != null)
                            {
                                var num = Helpers.Color.getNum((string)property.GetValue(indicator, null));
                                if (num != null)
                                {
                                    var currValue = float.Parse(num);
                                    var formatedValue = currValue.ToString(format);
                                    property.SetValue(indicator, Convert.ChangeType(formatedValue, property.PropertyType), null);
                                    db.Entry(indicator).State = EntityState.Modified;
                                    db.SaveChanges();
                                }
                            }
                        }
                    }
                }
            }
        }
 private bool ValidateData()
 {
     bool result = true;
     string message = "";
     List<string> errors = new List<string>();
     if (orderDetails.Count <= 0)
     {
         result = false;
         message = "- Không có dữ liệu sản phẩm";
     }
     for (int i = 0; i < orderDetails.Count; i++)
     {
         if ((orderDetails[i].ProductId != 0 && orderDetails[i].AttributeId != 0 &&
             orderDetails[i].UnitId != 0 && orderDetails[i].NumberUnit > 0) ||
             (orderDetails[i].ProductId == 0 && orderDetails[i].AttributeId == 0 &&
             orderDetails[i].UnitId == 0))
             continue;
         result = false;
         message += "- Dòng " + (i + 1) + " thiếu :";
         if (orderDetails[i].ProductId == 0)
             errors.Add(" Sản phẩm");
         if (orderDetails[i].NumberUnit <= 0)
             errors.Add(" Số lượng");
         if (orderDetails[i].UnitId == 0)
             errors.Add(" Đơn vị tính");
         message += string.Join(",", errors);
         errors.Clear();
         message += "\n";
     }
     if (!result)
         MessageBox.Show(message, "Lỗi hóa đơn", MessageBoxButtons.OK, MessageBoxIcon.Error);
     return result;
 }
        public ActionResult viewPRExcel(Int16 fiscalYear, Int16? coeID)
        {
            ModelState.Clear();
            var viewModel = new PRViewModel
            {
                //allCoEs = db.CoEs.ToList(),
                allCoEs = db.CoEs.ToList(),
                allMaps = db.Indicator_CoE_Maps.ToList(),
                allFootnoteMaps = db.Indicator_Footnote_Maps.ToList()
            };

            // Create the workbook
            var wb = new XLWorkbook();

            var prBlue = ExcelGlobalVariables.prBlue;// XLColor.FromArgb(0, 51, 102);
            var prGreen = ExcelGlobalVariables.prGreen;//XLColor.FromArgb(0, 118, 53);
            var prYellow = ExcelGlobalVariables.prYellow; //XLColor.FromArgb(255, 192, 0);
            var prRed = ExcelGlobalVariables.prRed;// XLColor.FromArgb(255, 0, 0);
            var prHeader1Fill = ExcelGlobalVariables.prHeader1Fill;//prBlue;
            var prHeader1Font = ExcelGlobalVariables.prHeader1Font;//XLColor.White;
            var prHeader2Fill = ExcelGlobalVariables.prHeader2Fill;//XLColor.White;
            var prHeader2Font = ExcelGlobalVariables.prHeader2Font;//XLColor.Black;
            var prBorder = ExcelGlobalVariables.prBorder;//XLColor.FromArgb(0, 0, 0);
            var prAreaFill = ExcelGlobalVariables.prAreaFill;//XLColor.FromArgb(192, 192, 192);
            var prAreaFont = ExcelGlobalVariables.prAreaFont;//XLColor.Black;
            var prBorderWidth = XLBorderStyleValues.Thin;
            var prFontSize = 10;
            var prTitleFont = 20;
            var prFootnoteSize = 8;
            var prHeightSeperator = 7.5;

            var prAreaObjectiveFontsize = 8;
            var indentLength = 2;
            var newLineHeight = 12.6;

            var defNote = "Portal data from the Canadian Institute for Health Information (CIHI) has been used to generate data within this report with acknowledgement to CIHI, the Ministry of Health and Long-Term Care (MOHLTC) and Stats Canada (as applicable). Views are not those of the acknowledged sources. Facility identifiable data other than Mount Sinai Hospital (MSH) is not to be published without the consent of that organization (except where reported at an aggregate level). As this is not a database supported by MSH, please demonstrate caution with use and interpretation of the information. MSH is not responsible for any changes derived from the source data/canned reports. Data may be subject to change.";

            var prNumberWidth = 4;
            var prIndicatorWidth = 55;
            var prValueWidth = 11;
            var prDefWidth = 100;
            var prRatiWidth = 50;
            var prCompWidth = 50;

            //var fitRatio = 3.77;
            var fitRatio = 1.7;
            List<int> fitAdjustableRows = new List<int>();

            var prFootnoteCharsNewLine = 125;
            var prObjectivesCharsNewLine = 226;

            var allCoes = new List<CoEs>();
            if (coeID != 0 && coeID != null)
            {
                allCoes = viewModel.allCoEs.Where(x => x.CoE_ID == coeID).ToList();
            }
            else
            {
                allCoes = viewModel.allCoEs.ToList();
            }

            foreach (var coe in allCoes)
            {
                var wsPRName = coe.CoE_Abbr != null && coe.CoE_Abbr != "" ? coe.CoE_Abbr : "Indicators";
                var wsDefName = coe.CoE_Abbr != null && coe.CoE_Abbr != "" ? "Def_" + coe.CoE_Abbr : "Def_Indicators";
                var wsPR = wb.Worksheets.Add(wsPRName);
                var wsDef = wb.Worksheets.Add(wsDefName);
                List<IXLWorksheet> wsList = new List<IXLWorksheet>();
                wsList.Add(wsPR);
                wsList.Add(wsDef);

                foreach (var ws in wsList)
                {
                    var currentRow = 4;
                    ws.Row(2).Height = 21;
                    int startRow;
                    int indicatorNumber = 1;

                    ws.PageSetup.Margins.Top = 0;
                    ws.PageSetup.Margins.Header = 0;
                    ws.PageSetup.Margins.Left = 0.5;
                    ws.PageSetup.Margins.Right = 0.5;
                    ws.PageSetup.Margins.Bottom = 0.5;
                    ws.PageSetup.PageOrientation = XLPageOrientation.Landscape;
                    ws.PageSetup.PaperSize = XLPaperSize.LegalPaper;
                    ws.PageSetup.FitToPages(1, 1);

                    string[,] columnHeaders = new string[0, 0];
                    if (ws.Name == wsPRName)
                    {
                        var prHeadder2Title = FiscalYear.FYStrFull("FY_", fiscalYear) + "Performance";
                        prHeadder2Title = prHeadder2Title.Replace("_", " ");
                        columnHeaders = new string[,]{
                            {"Number",""},
                            {"Indicator",""},
                            {FiscalYear.FYStrFull("FY_3", fiscalYear), ""},
                            {FiscalYear.FYStrFull("FY_2", fiscalYear),""},
                            {FiscalYear.FYStrFull("FY_1", fiscalYear),""},
                            {prHeadder2Title,"Q1"},
                            {prHeadder2Title,"Q2"},
                            {prHeadder2Title,"Q3"},
                            {prHeadder2Title,"Q4"},
                            {prHeadder2Title,"YTD"},
                            {FiscalYear.FYStrFull("FY_", fiscalYear) + "Target",""},
                            {FiscalYear.FYStrFull("FY_", fiscalYear) + "Performance_Threshold",""},
                            {FiscalYear.FYStrFull("FY_", fiscalYear) + "Comparator",""}
                        };
                    }
                    else if (ws.Name == wsDefName)
                    {
                        columnHeaders = new string[,]{
                            {"Number",""},
                            {"Indicator",""},
                            {FiscalYear.FYStrFull("FY_", fiscalYear) + "Definition_Calculation",""},
                            {FiscalYear.FYStrFull("FY_", fiscalYear) + "Target_Rationale",""},
                            {FiscalYear.FYStrFull("FY_", fiscalYear) + "Comparator_Source",""}
                        };
                    }

                    var currentCol = 1;
                    var prHeader2ColStart = 99;
                    var prHeader2ColEnd = 1;
                    int maxCol = columnHeaders.GetUpperBound(0) + 1;

                    var prTitle = ws.Cell(currentRow, 1);
                    prTitle.Value = coe.CoE;
                    prTitle.Style.Font.FontSize = prTitleFont;
                    prTitle.Style.Font.Bold = true;
                    prTitle.Style.Font.FontColor = prHeader1Font;
                    prTitle.Style.Fill.BackgroundColor = prHeader1Fill;
                    ws.Range(ws.Cell(currentRow, 1), ws.Cell(currentRow, maxCol)).Merge();
                    ws.Range(ws.Cell(currentRow + 1, 1), ws.Cell(currentRow + 1, maxCol)).Merge();
                    ws.Row(currentRow + 1).Height = prHeightSeperator;
                    currentRow += 2;
                    startRow = currentRow;

                    for (int i = 0; i <= columnHeaders.GetUpperBound(0); i++)
                    {
                        if (columnHeaders[i, 1] == "")
                        {
                            var columnField = columnHeaders[i, 0];
                            string cellValue;
                            Type t = typeof(Indicators);
                            cellValue = t.GetProperty(columnField) != null ?
                                ModelMetadataProviders.Current.GetMetadataForProperty(null, typeof(Indicators), columnField).DisplayName :
                                ModelMetadataProviders.Current.GetMetadataForProperty(null, typeof(Indicator_CoE_Maps), columnField).DisplayName;
                            ws.Cell(currentRow, currentCol).Value = cellValue;
                            ws.Range(ws.Cell(currentRow, currentCol), ws.Cell(currentRow + 1, currentCol)).Merge();
                            currentCol++;
                        }
                        else
                        {
                            var columnField = columnHeaders[i, 1];
                            var columnFieldTop = columnHeaders[i, 0];
                            ws.Cell(currentRow + 1, currentCol).Value = columnField;
                            ws.Cell(currentRow, currentCol).Value = columnFieldTop;
                            if (currentCol < prHeader2ColStart) { prHeader2ColStart = currentCol; }
                            if (currentCol > prHeader2ColEnd) { prHeader2ColEnd = currentCol; }
                            currentCol++;
                        }
                    }
                    currentCol--;
                    ws.Range(ws.Cell(currentRow, prHeader2ColStart).Address, ws.Cell(currentRow, prHeader2ColEnd).Address).Merge();
                    var prHeader1 = ws.Range(ws.Cell(currentRow, 1).Address, ws.Cell(currentRow + 1, currentCol).Address);
                    var prHeader2 = ws.Range(ws.Cell(currentRow + 1, prHeader2ColStart).Address, ws.Cell(currentRow + 1, prHeader2ColEnd).Address);

                    prHeader1.Style.Alignment.Vertical = XLAlignmentVerticalValues.Center;
                    prHeader1.Style.Alignment.Horizontal = XLAlignmentHorizontalValues.Center;

                    prHeader1.Style.Fill.BackgroundColor = prHeader1Fill;
                    prHeader1.Style.Font.FontColor = prHeader1Font;

                    prHeader2.Style.Fill.BackgroundColor = prHeader2Fill;
                    prHeader2.Style.Font.FontColor = prHeader2Font;

                    currentRow += 2;

                    List<Footnotes> footnotes = new List<Footnotes>();
                    foreach (var areaMap in coe.Area_CoE_Map.Where(x => x.Fiscal_Year == fiscalYear).OrderBy(x => x.Area.Sort))
                    {
                        var cellLengthObjective = 0;
                        var prArea = ws.Range(ws.Cell(currentRow, 1), ws.Cell(currentRow, maxCol));
                        //fitAdjustableRows.Add(currentRow);
                        prArea.Merge();
                        prArea.Style.Fill.BackgroundColor = prAreaFill;
                        prArea.Style.Font.FontColor = prAreaFont;
                        prArea.FirstCell().RichText.AddText(areaMap.Area.Area).Bold = true;
                        cellLengthObjective += areaMap.Area.Area.Length;

                        if (ws == wsPR)
                        {
                            var indent = new string('_', indentLength);

                            var stringSeperators = new string[] { "•" };
                            if (areaMap.Objective != null)
                            {
                                var objectives = Regex.Matches(areaMap.Objective, @"\[.*?\]").Cast<Match>().Select(m => m.Value.Substring(1, m.Value.Length - 2)).ToList();
                                //for (var i = 1; i < objectives.Length; i++)
                                var i = 1;
                                foreach (var objective in objectives)
                                {
                                    prArea.FirstCell().RichText.AddNewLine();
                                    ws.Row(currentRow).Height += newLineHeight;
                                    prArea.FirstCell().RichText.AddText(indent).SetFontColor(prAreaFill).SetFontSize(prAreaObjectiveFontsize);
                                    prArea.FirstCell().RichText.AddText(" " + i +". " + objective).FontSize = prAreaObjectiveFontsize;
                                    i++;
                                }
                            }
                        }

                        currentRow++;

                        var allMaps = viewModel.allMaps.Where(x => x.Fiscal_Year == fiscalYear).Where(e => e.Indicator.Area.Equals(areaMap.Area)).Where(d => d.CoE.CoE != null && d.CoE.CoE.Contains(coe.CoE)).OrderBy(f => f.Number).ToList();
                        var allNValues = new List<Indicator_CoE_Maps>();
                        if (ws.Name == wsPRName)
                        {
                            allNValues = viewModel.allMaps.Where(x => x.Fiscal_Year == fiscalYear && x.Indicator.Indicator_N_Value == true).ToList();
                        }
                        var allMapsWithNValues = new List<Indicator_CoE_Maps>();
                        foreach (var nValue in allNValues)
                        {
                            var indicatorIndex = allMaps.FirstOrDefault(x => x.Indicator_ID == nValue.Indicator.Indicator_N_Value_ID);
                            if (indicatorIndex != null)
                            {
                                var position = allMaps.IndexOf(indicatorIndex);
                                allMapsWithNValues.Add(indicatorIndex);
                                allMaps.Insert(position + 1, nValue);
                            }
                        }
                        foreach (var map in allMaps)
                        {
                            fitAdjustableRows.Add(currentRow);
                            currentCol = 1;

                            int rowSpan = 1;
                            if (allMapsWithNValues.Contains(map) || !allNValues.Contains(map))
                            {
                                if (allMapsWithNValues.Contains(map))
                                {
                                    rowSpan = 2;
                                    ws.Range(ws.Cell(currentRow, currentCol), ws.Cell(currentRow + 1, currentCol)).Merge();
                                    ws.Range(ws.Cell(currentRow, currentCol + 1), ws.Cell(currentRow + 1, currentCol + 1)).Merge();
                                }
                                ws.Cell(currentRow, currentCol).Style.Border.OutsideBorder = prBorderWidth;
                                ws.Cell(currentRow, currentCol).Style.Border.OutsideBorderColor = prBorder;
                                ws.Cell(currentRow, currentCol).Value = indicatorNumber;
                                indicatorNumber++;
                                ws.Cell(currentRow, currentCol).Style.Alignment.Horizontal = XLAlignmentHorizontalValues.Center;
                                currentCol++;

                                ws.Cell(currentRow, currentCol).Style.Border.OutsideBorder = prBorderWidth;
                                ws.Cell(currentRow, currentCol).Style.Border.OutsideBorderColor = prBorder;
                                int j = 0;
                                ws.Cell(currentRow, currentCol).Value = map.Indicator.Indicator;
                                foreach (var footnote in map.Indicator.Indicator_Footnote_Map.Where(x => x.Fiscal_Year == fiscalYear).Where(e => e.Indicator_ID == map.Indicator_ID).OrderBy(e => e.Indicator_ID))
                                {
                                    if (!footnotes.Contains(footnote.Footnote)) { footnotes.Add(footnote.Footnote); }
                                    if (j != 0)
                                    {
                                        ws.Cell(currentRow, currentCol).RichText.AddText(",").VerticalAlignment = XLFontVerticalTextAlignmentValues.Superscript;
                                    }
                                    ws.Cell(currentRow, currentCol).RichText.AddText(footnote.Footnote.Footnote_Symbol).VerticalAlignment = XLFontVerticalTextAlignmentValues.Superscript;
                                    j++;
                                }
                                ws.Cell(currentRow, currentCol).Style.Alignment.Horizontal = XLAlignmentHorizontalValues.Left;
                                currentCol++;
                            }
                            else
                            {
                                ws.Cell(currentRow, currentCol).Style.Border.OutsideBorder = prBorderWidth;
                                ws.Cell(currentRow, currentCol).Style.Border.OutsideBorderColor = prBorder;
                                currentCol += 2;
                                rowSpan = 0;
                            }

                            if (ws.Name == wsPRName)
                            {
                                for (var i = 3; i <= 15; i++)
                                {
                                    ws.Column(i).Width = ws.Name == wsPRName ? prValueWidth : prDefWidth;
                                }

                                var obj = map.Indicator;
                                var type = obj.GetType();
                                string[,] columnIndicators = new string[,]{
                                    {(string)type.GetProperty(FiscalYear.FYStrFull("FY_3",fiscalYear)).GetValue(obj,null),
                                     (string)type.GetProperty(FiscalYear.FYStrFull("FY_3",fiscalYear) + "_Sup").GetValue(obj,null),
                                     "",
                                     "1"
                                    },
                                    {(string)type.GetProperty(FiscalYear.FYStrFull("FY_2",fiscalYear)).GetValue(obj,null),
                                     (string)type.GetProperty(FiscalYear.FYStrFull("FY_2",fiscalYear) + "_Sup").GetValue(obj,null),
                                     "",
                                     "1"
                                    },
                                    {(string)type.GetProperty(FiscalYear.FYStrFull("FY_1",fiscalYear)).GetValue(obj,null),
                                     (string)type.GetProperty(FiscalYear.FYStrFull("FY_1",fiscalYear) + "_Sup").GetValue(obj,null),
                                     "",
                                     "1"
                                    },
                                    {(string)type.GetProperty(FiscalYear.FYStrFull("FY_",fiscalYear) + "Q1").GetValue(obj,null),
                                     (string)type.GetProperty(FiscalYear.FYStrFull("FY_",fiscalYear) + "Q1_Sup").GetValue(obj,null),
                                     (string)type.GetProperty(FiscalYear.FYStrFull("FY_",fiscalYear) + "Q1_Color").GetValue(obj,null),
                                     "1"
                                    },
                                    {(string)type.GetProperty(FiscalYear.FYStrFull("FY_",fiscalYear) + "Q2").GetValue(obj,null),
                                     (string)type.GetProperty(FiscalYear.FYStrFull("FY_",fiscalYear) + "Q2_Sup").GetValue(obj,null),
                                     (string)type.GetProperty(FiscalYear.FYStrFull("FY_",fiscalYear) + "Q2_Color").GetValue(obj,null),
                                     "1"
                                    },
                                    {(string)type.GetProperty(FiscalYear.FYStrFull("FY_",fiscalYear) + "Q3").GetValue(obj,null),
                                     (string)type.GetProperty(FiscalYear.FYStrFull("FY_",fiscalYear) + "Q3_Sup").GetValue(obj,null),
                                     (string)type.GetProperty(FiscalYear.FYStrFull("FY_",fiscalYear) + "Q3_Color").GetValue(obj,null),
                                     "1",
                                    },
                                    {(string)type.GetProperty(FiscalYear.FYStrFull("FY_",fiscalYear) + "Q4").GetValue(obj,null),
                                     (string)type.GetProperty(FiscalYear.FYStrFull("FY_",fiscalYear) + "Q4_Sup").GetValue(obj,null),
                                     (string)type.GetProperty(FiscalYear.FYStrFull("FY_",fiscalYear) + "Q4_Color").GetValue(obj,null),
                                     "1"
                                    },
                                    {(string)type.GetProperty(FiscalYear.FYStrFull("FY_",fiscalYear) + "YTD").GetValue(obj,null),
                                     (string)type.GetProperty(FiscalYear.FYStrFull("FY_",fiscalYear) + "YTD_Sup").GetValue(obj,null),
                                     (string)type.GetProperty(FiscalYear.FYStrFull("FY_",fiscalYear) + "YTD_Color").GetValue(obj,null),
                                     "1"
                                    },
                                    {(string)type.GetProperty(FiscalYear.FYStrFull("FY_",fiscalYear) + "Target").GetValue(obj,null),
                                     (string)type.GetProperty(FiscalYear.FYStrFull("FY_",fiscalYear) + "Target_Sup").GetValue(obj,null),
                                     "",
                                     rowSpan.ToString()
                                    },
                                    {(string)type.GetProperty(FiscalYear.FYStrFull("FY_",fiscalYear) + "Performance_Threshold").GetValue(obj,null),
                                     (string)type.GetProperty(FiscalYear.FYStrFull("FY_",fiscalYear) + "Performance_Threshold_Sup").GetValue(obj,null),
                                     "",
                                    rowSpan.ToString()
                                    },
                                    {(string)type.GetProperty(FiscalYear.FYStrFull("FY_",fiscalYear) + "Comparator").GetValue(obj,null),
                                     (string)type.GetProperty(FiscalYear.FYStrFull("FY_",fiscalYear) + "Comparator_Sup").GetValue(obj,null),
                                     "",
                                     rowSpan.ToString()
                                    },
                                };
                                var startCol = currentCol;
                                int k = 1;
                                for (var i = 0; i <= columnIndicators.GetUpperBound(0); i++)
                                {
                                    for (var j = 0; j <= columnIndicators.GetUpperBound(1); j++)
                                    {
                                        if (columnIndicators[i, j] != null)
                                        {
                                            columnIndicators[i, j] = columnIndicators[i, j].Replace("<b>", "");
                                            columnIndicators[i, j] = columnIndicators[i, j].Replace("</b>", "");
                                            columnIndicators[i, j] = columnIndicators[i, j].Replace("<u>", "");
                                            columnIndicators[i, j] = columnIndicators[i, j].Replace("</u>", "");
                                            columnIndicators[i, j] = columnIndicators[i, j].Replace("<i>", "");
                                            columnIndicators[i, j] = columnIndicators[i, j].Replace("</i>", "");
                                            columnIndicators[i, j] = columnIndicators[i, j].Replace("<sup>", "");
                                            columnIndicators[i, j] = columnIndicators[i, j].Replace("</sup>", "");
                                            columnIndicators[i, j] = columnIndicators[i, j].Replace("<sub>", "");
                                            columnIndicators[i, j] = columnIndicators[i, j].Replace("</sub>", "");
                                        }
                                    }
                                    if (i != columnIndicators.GetUpperBound(0) && columnIndicators[i, 0] == "=")
                                    {
                                        k = 1;
                                        while (columnIndicators[i + k, 0] == "=") { k++; }
                                        ws.Range(ws.Cell(currentRow, startCol + i - 1), ws.Cell(currentRow, startCol + i + k - 1)).Merge();
                                        i += k - 1;
                                        k = 1;
                                    }
                                    else if (columnIndicators[i, 0] != "=")
                                    {
                                        ws.Cell(currentRow, currentCol + i).Style.Border.OutsideBorder = prBorderWidth;
                                        ws.Cell(currentRow, currentCol + i).Style.Border.OutsideBorderColor = prBorder;
                                        if (columnIndicators[i, 3] != "0")
                                        {
                                            if (columnIndicators[i, 3] == "2") {
                                                ws.Range(ws.Cell(currentRow, currentCol + i), ws.Cell(currentRow + 1, currentCol + i)).Merge();
                                            }
                                            if (allNValues.Contains(map))
                                            {
                                                ws.Cell(currentRow, currentCol + i).Style.Border.TopBorder = XLBorderStyleValues.None;
                                            }
                                            else if (allMapsWithNValues.Contains(map))
                                            {
                                                ws.Cell(currentRow, currentCol + i).Style.Border.BottomBorder = XLBorderStyleValues.None;
                                            }
                                            var cell = ws.Cell(currentRow, currentCol + i);
                                            string cellValue = "";

                                            if (columnIndicators[i, 0] != null)
                                            {
                                                cellValue = columnIndicators[i, 0].ToString();
                                            }

                                            if (cellValue.Contains("$"))
                                            {
                                            }

                                            cell.Value = "'" + cellValue;
                                            if (columnIndicators[i, 1] != null)
                                            {
                                                cell.RichText.AddText(columnIndicators[i, 1]).VerticalAlignment = XLFontVerticalTextAlignmentValues.Superscript;
                                            }
                                            switch (columnIndicators[i, 2])
                                            {
                                                case "cssWhite":
                                                    cell.RichText.SetFontColor(XLColor.Black);
                                                    cell.Style.Fill.BackgroundColor = XLColor.White;
                                                    break;
                                                case "cssGreen":
                                                    cell.RichText.SetFontColor(XLColor.White);
                                                    cell.Style.Fill.BackgroundColor = prGreen;
                                                    break;
                                                case "cssYellow":
                                                    cell.RichText.SetFontColor(XLColor.Black);
                                                    cell.Style.Fill.BackgroundColor = prYellow;
                                                    break;
                                                case "cssRed":
                                                    cell.RichText.SetFontColor(XLColor.White);
                                                    cell.Style.Fill.BackgroundColor = prRed;
                                                    break;
                                            }
                                            cell.Style.Alignment.Horizontal = XLAlignmentHorizontalValues.Center;
                                        }
                                    }
                                }
                                currentRow++;
                            }
                            else if (ws.Name == wsDefName)
                            {
                                ws.Column(3).Width = prDefWidth;
                                ws.Column(4).Width = prRatiWidth;
                                ws.Column(5).Width = prCompWidth;

                                var obj = map.Indicator;
                                var type = obj.GetType();

                                string defn = (string)type.GetProperty(FiscalYear.FYStrFull("FY_", fiscalYear) + "Definition_Calculation").GetValue(obj, null);
                                string rationale = (string)type.GetProperty(FiscalYear.FYStrFull("FY_", fiscalYear) + "Target_Rationale").GetValue(obj, null);
                                string comp = (string)type.GetProperty(FiscalYear.FYStrFull("FY_", fiscalYear) + "Comparator_Source").GetValue(obj, null);

                                double maxLines = 1;
                                double lines;

                                if (defn != null)
                                {
                                    lines = defn.Length / ws.Column(currentCol).Width;
                                    maxLines = maxLines < lines ? lines : maxLines;
                                    ws.Cell(currentRow, currentCol).Value = defn;
                                }
                                ws.Cell(currentRow, currentCol).Style.Alignment.Horizontal = XLAlignmentHorizontalValues.Left;
                                currentCol++;

                                if (rationale != null)
                                {
                                    lines = rationale.Length / ws.Column(currentCol).Width;
                                    maxLines = maxLines < lines ? lines : maxLines;
                                    ws.Cell(currentRow, currentCol).Value = rationale;
                                }
                                ws.Cell(currentRow, currentCol).Style.Alignment.Horizontal = XLAlignmentHorizontalValues.Left;
                                currentCol++;

                                if (comp != null)
                                {
                                    lines = comp.Length / ws.Column(currentCol).Width;
                                    maxLines = maxLines < lines ? lines : maxLines;
                                    ws.Cell(currentRow, currentCol).Value = comp;
                                }
                                ws.Cell(currentRow, currentCol).Style.Alignment.Horizontal = XLAlignmentHorizontalValues.Left;
                                currentCol++;

                                ws.Row(currentRow).Height = newLineHeight * Math.Ceiling(maxLines);
                                currentRow++;
                            }
                        }
                    }

                    var footnoteRow = ws.Range(ws.Cell(currentRow, 1), ws.Cell(currentRow, maxCol));
                    footnoteRow.Merge();
                    footnoteRow.Style.Font.FontSize = prFootnoteSize;

                    /*Footnotes defaultFootnote = db.Footnotes.FirstOrDefault(x => x.Footnote_Symbol == "*");
                    if (!footnotes.Contains(defaultFootnote))
                    {
                        footnotes.Add(defaultFootnote);
                    }*/

                    int cellLengthFootnote = 0;
                    if (ws.Name == wsPRName)
                    {
                        foreach (var footnote in footnotes.OrderBy(x=>x.Footnote_Order))
                        {
                            ws.Cell(currentRow, 1).RichText.AddText(footnote.Footnote_Symbol).VerticalAlignment = XLFontVerticalTextAlignmentValues.Superscript;
                            ws.Cell(currentRow, 1).RichText.AddText(" " + footnote.Footnote + ";");
                            ws.Cell(currentRow, 1).Style.Alignment.Vertical = XLAlignmentVerticalValues.Top;
                            cellLengthFootnote += footnote.Footnote_Symbol.ToString().Length + footnote.Footnote.ToString().Length + 2;
                            if (cellLengthFootnote > prFootnoteCharsNewLine)
                            {
                                ws.Cell(currentRow, 1).RichText.AddNewLine();
                                cellLengthFootnote = 0;
                                ws.Row(currentRow).Height += newLineHeight;
                            }
                        }
                    }
                    else
                    {
                        ws.Cell(currentRow, 1).Value = defNote;
                        ws.Row(currentRow).Height = 28;
                    }

                    var pr = ws.Range(ws.Cell(startRow, 1), ws.Cell(currentRow - 1, maxCol));

                    if (pr.Worksheet.Name == wsDefName)
                    {
                        pr.Style.Border.InsideBorder = prBorderWidth;
                        pr.Style.Border.InsideBorderColor = prBorder;
                    }
                    pr.Style.Border.OutsideBorder = prBorderWidth;
                    pr.Style.Border.OutsideBorderColor = prBorder;
                    pr.Style.Font.FontSize = prFontSize;

                    pr = ws.Range(ws.Cell(startRow, 1), ws.Cell(currentRow, maxCol));
                    pr.Style.Alignment.Vertical = XLAlignmentVerticalValues.Center;
                    pr.Style.Alignment.WrapText = true;

                    ws.Column(1).Width = prNumberWidth;
                    ws.Column(2).Width = prIndicatorWidth;
                    footnotes.Clear();
                    indicatorNumber = 1;

                    var totalHeight = ExcelFunctions.getTotalHeight(ws, 4);
                    var totalWidth = ExcelFunctions.getTotalWidth(ws, 1);
                    var fitHeight = (int)(totalWidth / fitRatio);
                    var fitWidth = (int)(totalHeight * fitRatio);

                    if (ws.Name == "Def_WIH Obs") { System.Diagnostics.Debugger.Break(); }

                    if (fitHeight > totalHeight)
                    {
                        var fitAddHeightTotal = (fitHeight - totalHeight);
                        var fitAddHeightPerRow = fitAddHeightTotal / fitAdjustableRows.Count;
                        foreach (var row in fitAdjustableRows)
                        {
                            ws.Row(row).Height += fitAddHeightPerRow;
                        }
                    }
                    else
                    {
                        while ((fitWidth - totalWidth) / fitWidth > 0.001)
                        {
                            var fitAddWidthTotal = (fitWidth - totalWidth) / 10;
                            var fitAddWidthPerRow = fitAddWidthTotal / (ws.LastColumnUsed().ColumnNumber() - 1);
                            foreach (var col in ws.Columns(2, ws.LastColumnUsed().ColumnNumber()))
                            {
                                col.Width += fitAddWidthPerRow / 5.69;
                            }
                            ExcelFunctions.AutoFitWorksheet(ws, 2, 3, newLineHeight);
                            totalHeight = ExcelFunctions.getTotalHeight(ws, 4);
                            totalWidth = ExcelFunctions.getTotalWidth(ws, 1);
                            fitHeight = (int)(totalWidth / fitRatio);
                            fitWidth = (int)(totalHeight * fitRatio);
                        }
                    }
                }
            }

            MemoryStream preImage = new MemoryStream();
            wb.SaveAs(preImage);

            //Aspose.Cells.Workbook test = new Aspose.Cells.Workbook(preImage);
            //test.Save(this.HttpContext.ApplicationInstance.Server.MapPath("~/App_Data/logo.pdf"), Aspose.Cells.SaveFormat.Pdf);

            MemoryStream postImage = new MemoryStream();
            SLDocument postImageWb = new SLDocument(preImage);

            string picPath = this.HttpContext.ApplicationInstance.Server.MapPath("~/App_Data/logo.png");
            SLPicture picLogo = new SLPicture(picPath);
            string picPathOPEO = this.HttpContext.ApplicationInstance.Server.MapPath("~/App_Data/logoOPEO.png");
            SLPicture picLogoOPEO = new SLPicture(picPathOPEO);
            string picMonthlyPath = this.HttpContext.ApplicationInstance.Server.MapPath("~/App_Data/Monthly.png");
            SLPicture picMonthly = new SLPicture(picMonthlyPath);
            string picQuaterlyPath = this.HttpContext.ApplicationInstance.Server.MapPath("~/App_Data/quaterly.png");
            SLPicture picQuaterly = new SLPicture(picQuaterlyPath);
            string picNAPath = this.HttpContext.ApplicationInstance.Server.MapPath("~/App_Data/na.png");
            SLPicture picNA = new SLPicture(picNAPath);
            string picTargetPath = this.HttpContext.ApplicationInstance.Server.MapPath("~/App_Data/target.png");
            SLPicture picTarget = new SLPicture(picTargetPath);

            foreach (var ws in wb.Worksheets)
            {
                postImageWb.SelectWorksheet(ws.Name);

                for (int i = 1; i < 20; ++i)
                {
                    var a = postImageWb.GetRowHeight(i);
                }

                picLogo.SetPosition(0, 0);
                picLogo.ResizeInPercentage(25, 25);
                postImageWb.InsertPicture(picLogo);

                picLogoOPEO.SetRelativePositionInPixels(0, ws.LastColumnUsed().ColumnNumber() + 1, -140, 0);
                picLogoOPEO.ResizeInPercentage(45, 45);
                postImageWb.InsertPicture(picLogoOPEO);

                if (ws.Name.Substring(0, 3) != "Def")
                {
                    picTarget.SetRelativePositionInPixels(ws.LastRowUsed().RowNumber() + 1, ws.LastColumnUsed().ColumnNumber() + 1, -240, 1);
                    picNA.SetRelativePositionInPixels(ws.LastRowUsed().RowNumber() + 1, ws.LastColumnUsed().ColumnNumber() + 1, -400, 1);
                    picMonthly.SetRelativePositionInPixels(ws.LastRowUsed().RowNumber() + 1, ws.LastColumnUsed().ColumnNumber() + 1, -500, 1);
                    picQuaterly.SetRelativePositionInPixels(ws.LastRowUsed().RowNumber() + 1, ws.LastColumnUsed().ColumnNumber() + 1, -490, 1);

                    picMonthly.ResizeInPercentage(70, 70);
                    picQuaterly.ResizeInPercentage(70, 70);
                    picNA.ResizeInPercentage(70, 70);
                    picTarget.ResizeInPercentage(70, 70);

                    postImageWb.InsertPicture(picMonthly);
                    postImageWb.InsertPicture(picQuaterly);
                    postImageWb.InsertPicture(picNA);
                    postImageWb.InsertPicture(picTarget);
                }
            }

            // Prepare the response
            HttpResponse httpResponse = this.HttpContext.ApplicationInstance.Context.Response;
            httpResponse.Clear();
            httpResponse.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
            httpResponse.AddHeader("content-disposition", "attachment;filename=\"test.xlsx\"");
            //httpResponse.ContentType = "application/pdf";
            //httpResponse.AddHeader("content-disposition", "attachment;filename=\"test.pdf\"");

            // Flush the workbook to the Response.OutputStream
            using (MemoryStream memoryStream = new MemoryStream())
            {
                postImageWb.SaveAs(memoryStream);
                memoryStream.WriteTo(httpResponse.OutputStream);
                memoryStream.Close();
            }

            httpResponse.End();

            return View(viewModel);
        }
Exemplo n.º 23
0
        /*
         * (non-Javadoc)
         *
         * @see
         * com.itextpdf.tool.xml.ITagProcessor#endElement(com.itextpdf.tool.xml.Tag,
         * java.util.List, com.itextpdf.text.Document)
         */
	public override IList<IElement> End(IWorkerContext ctx, Tag tag, IList<IElement> currentContent) {
        IList<IElement> l = new List<IElement>(1);
        if (currentContent.Count > 0) {
            List<IElement> elements = new List<IElement>();
            List<ListItem> listItems = new List<ListItem>();
            foreach (IElement el in currentContent) {
                if (el is ListItem) {
                    if (elements.Count > 0) {
                        ProcessParagraphItems(ctx, tag, elements, l);
                        elements.Clear();
                    }
                    listItems.Add((ListItem)el);
                } else {
                    if (listItems.Count > 0) {
                        ProcessListItems(ctx, tag, listItems, l);
                        listItems.Clear();
                    }
                    elements.Add(el);
                }
            }
            if (elements.Count > 0) {
                ProcessParagraphItems(ctx, tag, elements, l);
                elements.Clear();
            } else if (listItems.Count > 0) {
                ProcessListItems(ctx, tag, listItems, l);
                listItems.Clear();
            }
        }
		return l;
	}
Exemplo n.º 24
0
        private void btn_Scan_Click(object sender, EventArgs e)
        {
            List<Service> ScanList = new List<Service>();
            bool allesStimmt = false;
            int start;
            int end;
            string iP;
            string iPEnd;
            int difPort;
            int difIP;

            ScanList.Clear();
            lv_Port.Items.Clear();
            info.Clear();

            if (txt_IPrange.Text == string.Empty)
                txt_IPrange.Text = txt_IP4.Text;
            try
            {   //bisschen verschachtelt alles was nicht zutrifft wirft ne Messagebox mit nem Fehler zurück
                if (Convert.ToInt32(txt_IP4.Text) <= Convert.ToInt32(txt_IPrange.Text))
                {
                    iP = txt_IP1.Text + "." + txt_IP2.Text + "." + txt_IP3.Text + "." + txt_IP4.Text;
                    iPEnd = txt_IP1.Text + "." + txt_IP2.Text + "." + txt_IP3.Text + "." + txt_IPrange.Text;

                    if (ipRichtig(iP) && ipRichtig(iPEnd))
                    {
                        allesStimmt = true;

                        if (radioButton1.Checked == true)
                        {
                            if (txt_End.Text == string.Empty)
                            {
                                txt_End.Text = txt_Start.Text;
                            }

                            if (portZahl(txt_End.Text) && portZahl(txt_Start.Text))
                            {

                                start = Convert.ToInt32(txt_Start.Text);
                                end = Convert.ToInt32(txt_End.Text);

                                if (start <= end)
                                {
                                    allesStimmt = true;

                                    ScanList.Clear();
                                    for (int i = start; i <= end; i++)
                                    {
                                        for (int iIP = Convert.ToInt32(txt_IP4.Text); iIP <= Convert.ToInt32(txt_IPrange.Text); iIP++)
                                        {
                                            Service service = new Service();
                                            service.ServiceName = readText.ReturnService(i);
                                            service.Port = i;
                                            service.IP = txt_IP1.Text + "." + txt_IP2.Text + "." + txt_IP3.Text + "." + iIP.ToString();
                                            ScanList.Add(service);
                                        }

                                    }
                                    if (start < 0 || end < 0)
                                    {
                                        allesStimmt = false;
                                        MessageBox.Show("The ports have to be positive", "Input failure");
                                    }

                                }
                                else
                                {
                                    MessageBox.Show("The start port has to be lower than the end port", "Input failure");
                                    allesStimmt = false;
                                }
                            }
                            else
                            {
                                MessageBox.Show("You have to enter numbers for the ports", "Input failure");
                                allesStimmt = false;
                            }
                        }

                        if (radioButton2.Checked == true)
                        {
                            ScanList.Clear();
                            for (int iIP = Convert.ToInt32(txt_IP4.Text); iIP <= Convert.ToInt32(txt_IPrange.Text); iIP++)
                            {
                                Service serviceHttp = new Service();
                                serviceHttp.ServiceName = readText.ReturnService(80);
                                serviceHttp.Port = 80;
                                serviceHttp.IP = txt_IP1.Text + "." + txt_IP2.Text + "." + txt_IP3.Text + "." + iIP.ToString(); ;
                                ScanList.Add(serviceHttp);
                            }
                            for (int iIP = Convert.ToInt32(txt_IP4.Text); iIP <= Convert.ToInt32(txt_IPrange.Text); iIP++)
                            {
                                Service serviceHttps = new Service();
                                serviceHttps.ServiceName = readText.ReturnService(443);
                                serviceHttps.Port = 443;
                                serviceHttps.IP = txt_IP1.Text + "." + txt_IP2.Text + "." + txt_IP3.Text + "." + iIP.ToString(); ;
                                ScanList.Add(serviceHttps);
                            }
                        }
                        if (raBuChoose.Checked == true)
                        {
                            ScanList.Clear();
                            foreach (int zahl in readText.PortArray())
                            {
                                for (int iIP = Convert.ToInt32(txt_IP4.Text); iIP <= Convert.ToInt32(txt_IPrange.Text); iIP++)
                                {
                                    Service serviceHttps = new Service();
                                    serviceHttps.ServiceName = readText.ReturnService(zahl);
                                    serviceHttps.Port = zahl;
                                    serviceHttps.IP = txt_IP1.Text + "." + txt_IP2.Text + "." + txt_IP3.Text + "." + iIP.ToString();
                                    ScanList.Add(serviceHttps);
                                }
                            }
                        }
                        difPort = ScanList.Count / (Convert.ToInt32(txt_IPrange.Text) - Convert.ToInt32(txt_IP4.Text) + 1);
                        difIP = Convert.ToInt32(txt_IPrange.Text) - Convert.ToInt32(txt_IP4.Text) + 1;
                        prg_Scannning.Value = 0;
                        //das Maximum ist die Anzahl der IP´s mal die Anzahl der zu überprüfenden Ports
                        prg_Scannning.Maximum = difIP * difPort;
                        prg_Scannning.Step = 1;

                        if (allesStimmt == true)
                        {
                            btn_Scan.Enabled = false;
                            btn_Cancel.Enabled = true;
                            LastFinishedIndex = 0;
                            portScanner.StartScan(ScanList);
                        }
                    }
                    else
                    {
                        MessageBox.Show("No valid IP", "Input failure");
                        allesStimmt = false;
                    }
                }
                else
                {
                    MessageBox.Show("The start Ip has to be lower than the end IP", "Input failure");
                    allesStimmt = false;
                }
            }
            catch (Exception)
            {
                MessageBox.Show("Please enter numbers for the IP", "Input failure");
                allesStimmt = false;
            }
        }