Beispiel #1
0
        /// <summary>
        /// If the accept is clicked, check the given values
        /// If these are valid, start to create the note board
        /// Otherwise, mark the wrong field as red
        /// </summary>
        private void btnAccept_Click(object sender, EventArgs e)
        {
            DialogResult = DialogResult.Yes;
            Color RED   = Color.FromArgb(255, 192, 192);
            Color WHITE = Color.White;

            DateTime[] periods = new DateTime[4];
            DateTime[,] holidays = new DateTime[2, 2];
            TextBox[] textboxes = new TextBox[4] {
                StartPeriod1, EndPeriod1, StartPeriod2, EndHY
            };
            TextBox[] textBoxHolidays = new TextBox[2] {
                Holiday1, Holiday2
            };

            foreach (TextBox tbx in textboxes)
            {
                // Reset the color
                tbx.BackColor = WHITE;

                // Weekends are not allowed as start or end of a Kursabschnitt
                try
                {
                    periods[Array.IndexOf(textboxes, tbx)] = DateTime.ParseExact(tbx.Text, "dd.MM.yyyy", DEUTSCHCULT);
                    if (DateTimeCalcUtils.GetWeekday(periods[Array.IndexOf(textboxes, tbx)]) == "Sa" ||
                        DateTimeCalcUtils.GetWeekday(periods[Array.IndexOf(textboxes, tbx)]) == "So")
                    {
                        DialogResult  = DialogResult.None;
                        tbx.BackColor = RED;
                    }
                }
                catch (FormatException)
                {
                    DialogResult = DialogResult.None;
                    periods[Array.IndexOf(textboxes, tbx)] = new DateTime();
                    tbx.BackColor = RED;
                }
            }

            for (byte i = 0; i < textBoxHolidays.Length; i++)
            {
                textBoxHolidays[i].BackColor = WHITE;

                string[] prds = textBoxHolidays[i].Text.Split('-');
                try
                {
                    holidays[i, 0] = DateTime.ParseExact(prds[0], "dd.MM.yyyy", DEUTSCHCULT);
                    holidays[i, 1] = DateTime.ParseExact(prds[1], "dd.MM.yyyy", DEUTSCHCULT);
                }
                catch (FormatException)
                {
                    DialogResult   = DialogResult.None;
                    holidays[i, 0] = new DateTime();
                    holidays[i, 1] = new DateTime();
                    textBoxHolidays[i].BackColor = RED;
                }
            }

            for (byte i = 0; i < textboxes.Length - 1; i++)
            {
                if (periods[i + 1] < periods[i])
                {
                    DialogResult = DialogResult.None;
                    textboxes[i + 1].BackColor = RED;
                    periods[i + 1]             = new DateTime();
                }
            }

            for (byte i = 0; i < 2; i++)
            {
                if (holidays[i, 1] < holidays[i, 0])
                {
                    DialogResult = DialogResult.None;
                    textBoxHolidays[i].BackColor = RED;
                }
            }

            if (DialogResult == DialogResult.Yes)
            {
                Hide();
                if (CreateBoard(periods, holidays))
                {
                    MessageBox.Show("Ein leerer Bemerkungsbogen wurde erfolgreich generiert.\r\nAbschnitts: " +
                                    $"{periods[0]:dd.MM.yyyy} ~ {periods[1]:dd.MM.yyyy} | {periods[2]:dd.MM.yyyy} ~ {periods[3]:dd.MM.yyyy}",
                                    "Erfolg", MessageBoxButtons.OK, MessageBoxIcon.Information);
                }
                Close();
            }
        }
Beispiel #2
0
 /// <summary>
 /// Get the weekday of this Daynote object as string
 /// </summary>
 /// <returns>A string represents on which weekday this Daynote object is</returns>
 public string GetWeekdayS()
 {
     return(DateTimeCalcUtils.GetWeekday(_date));
 }
Beispiel #3
0
        /// <summary>
        /// Export this course to the given path as pdf
        /// </summary>
        /// <param name="periods">An array of DateTime contains 3 items representing the start of the year,
        ///                     the start of the second period and the end of the half year.</param>
        /// <param name="storedPath">The path where the exported pdf should be stored.
        ///                     This path does NOT contain the name of this pdf file.
        ///                     The name will be like this format:
        ///                     CourseName-Teacher-Class.pdf</param>
        /// <param name="logoFilePath">A optional parameter represents where the logo is stored.
        ///                     If this is not given, then the logo will be replaced by the words "Sollstuden für Kurs"</param>
        /// <returns>A boolean value represents whether the export is successful or not.</returns>
        public bool ExportAsPDF(DateTime[] periods, string storedPath, string logoFilePath = "default")
        {
            string      title    = $"{this._courseName}-{this._teacher}-{this._className}";
            PdfDocument document = new PdfDocument();
            PdfPage     page     = document.AddPage();
            XGraphics   xGps     = XGraphics.FromPdfPage(page);

            #region Preset Format
            double ROWS = 30;
            //double SMALLWEEKDAYRECTWIDTH = Formats.getPixel(5);
            double SMALLDATERECTWIDTH = Formats.GetPixel(30);
            double SMALLNOTERECTWIDTH = Formats.GetPixel(55);
            double SMALLRECTHEIGHT    = Formats.GetPixel(7);
            double TOPHEIGHT          = Formats.GetPixel(40);
            double LEFTBLANK          = Formats.GetPixel(10);
            double CENTERBLANK        = Formats.GetPixel(20);
            //double RIGHTBLANK = Formats.getPixel(10);
            double OFFSET = Formats.GetPixel(1.5);
            //IN PIXEL
            XPoint[] smallRectStartCo = new XPoint[4] {
                new XPoint(), new XPoint(), new XPoint(), new XPoint()
            };

            #endregion

            #region Preset Text Format
            XFont          boldFont      = new XFont("Times New Roman", 10, XFontStyle.Bold);
            XFont          regularFont   = new XFont("Times New Roman", 10);
            XFont          titleFont     = new XFont("Times New Roman", 24, XFontStyle.Bold);
            XFont          subtitleFont  = new XFont("Times New Roman", 16, XFontStyle.Bold);
            XFont          smallNoteFont = new XFont("Times New Roman", 8);
            XTextFormatter xtf           = new XTextFormatter(xGps);
            XBrush[]       brushes       = new XBrush[2] {
                new XSolidBrush(XColor.FromArgb(230, 230, 230)), new XSolidBrush(XColor.FromArgb(210, 210, 210))
            };
            #endregion

            #region Responsive Design & Error check

            if (this._lines.Count > ROWS * 2)
            {
                ROWS           *= 1.3;
                SMALLRECTHEIGHT = Formats.GetPixel(6);
            }
            if (this._lines.Count > ROWS * 2)
            {
                ROWS           *= 1.3;
                SMALLRECTHEIGHT = Formats.GetPixel(4.5);
                OFFSET          = Formats.GetPixel(1);

                boldFont    = new XFont("Times New Roman", 8, XFontStyle.Bold);
                regularFont = new XFont("Times New Roman", 8);
            }
            //Round it to a whole number
            ROWS = Math.Round(ROWS);
            //If the data is too long or too short
            if (this._lines.Count > ROWS * 2)
            {
                throw new ArgumentException("the weeklyplan is too long: " + this._lines.Count + " : " + this._courseName + this._className + this._teacher);
            }
            else if (_lines.Count < 3)
            {
                throw new ArgumentException("the weeklyplan is too short: " + this._lines.Count + " course: " + this._courseName + this._className + this._teacher);
            }
            #endregion

            #region Points

            smallRectStartCo[0].X = LEFTBLANK;
            smallRectStartCo[0].Y = TOPHEIGHT;
            smallRectStartCo[1].X = LEFTBLANK + SMALLDATERECTWIDTH;
            smallRectStartCo[1].Y = TOPHEIGHT;
            smallRectStartCo[2].X = LEFTBLANK + SMALLDATERECTWIDTH + SMALLNOTERECTWIDTH + CENTERBLANK;
            smallRectStartCo[2].Y = TOPHEIGHT;
            smallRectStartCo[3].X = LEFTBLANK + CENTERBLANK + 2 * SMALLDATERECTWIDTH + SMALLNOTERECTWIDTH;
            smallRectStartCo[3].Y = TOPHEIGHT;

            #endregion

            #region HEAD
            //Set the Logo
            if (logoFilePath == "default")
            {
                XRect rectSubtitle = new XRect(0, 0, Formats.GetPixel(46), Formats.GetPixel(30));
                xGps.DrawString("Sollstuden für Kurs", subtitleFont, XBrushes.Gray, rectSubtitle, XStringFormats.TopLeft);
            }
            else
            {
                XImage lgIcon = XImage.FromFile(logoFilePath);
                if (lgIcon == null)
                {
                    throw new ArgumentNullException(nameof(logoFilePath), "the stream of this file path is null");
                }
                xGps.DrawImage(lgIcon, 0, 0, Formats.GetPixel(46), Formats.GetPixel(30));

                XRect rectSubtitle = new XRect(Formats.GetPixel(55), Formats.GetPixel(2), Formats.GetPixel(100), Formats.GetPixel(10));
                xGps.DrawString("Sollstuden für Kurs", subtitleFont, XBrushes.Gray, rectSubtitle, XStringFormats.TopLeft);
            }

            //Set the title
            XRect rectTitle = new XRect(Formats.GetPixel(55), Formats.GetPixel(10), Formats.GetPixel(100), Formats.GetPixel(20));
            xGps.DrawString(title, titleFont, XBrushes.Black, rectTitle, XStringFormats.TopLeft);

            //Set the current date and the half year
            DateTime dtNow    = DateTime.Now;
            XRect    rectDate = new XRect(Formats.GetPixel(180), Formats.GetPixel(2), Formats.GetPixel(28), Formats.GetPixel(5));
            xGps.DrawString($"Stand: {dtNow:dd-MM-yyyy}", regularFont, XBrushes.Gray, rectDate, XStringFormats.TopRight);

            XRect rectYear = new XRect(Formats.GetPixel(180), Formats.GetPixel(7), Formats.GetPixel(28), Formats.GetPixel(5));
            xGps.DrawString(DateTimeCalcUtils.GetHalfYear(this._lines[0].GetDate()), boldFont, XBrushes.Gray, rectYear, XStringFormats.TopRight);
            #endregion

            #region Main Body

            XRect rectCurrentLine;
            //The first column
            for (int i = 0; i < this._lines.Count && i < ROWS; i++)
            {
                //The color
                if (i % 2 != 0)
                {
                    xGps.DrawRectangle(brushes[0], new XRect(new XPoint(smallRectStartCo[0].X, smallRectStartCo[0].Y - OFFSET), new XPoint(smallRectStartCo[1].X + SMALLNOTERECTWIDTH, smallRectStartCo[1].Y + SMALLRECTHEIGHT - OFFSET)));
                }
                else
                {
                    xGps.DrawRectangle(brushes[1], new XRect(new XPoint(smallRectStartCo[0].X, smallRectStartCo[0].Y - OFFSET), new XPoint(smallRectStartCo[1].X + SMALLNOTERECTWIDTH, smallRectStartCo[1].Y + SMALLRECTHEIGHT - OFFSET)));
                }

                rectCurrentLine = new XRect(smallRectStartCo[0], new XPoint(LEFTBLANK + SMALLDATERECTWIDTH, smallRectStartCo[0].Y + SMALLRECTHEIGHT));
                xtf.DrawString(_lines[i].GetWeekdayS() + "  " + _lines[i].GetDateS(), boldFont, XBrushes.Black, rectCurrentLine, XStringFormats.TopLeft);
                rectCurrentLine = new XRect(smallRectStartCo[1], new XPoint(smallRectStartCo[1].X + SMALLNOTERECTWIDTH, smallRectStartCo[1].Y + SMALLRECTHEIGHT));
                xtf.DrawString(_lines[i].GetNotes(), regularFont, XBrushes.Black, rectCurrentLine, XStringFormats.TopLeft);

                smallRectStartCo[0].Y += SMALLRECTHEIGHT;
                smallRectStartCo[1].Y += SMALLRECTHEIGHT;
            }
            //The second column if exists
            if (this._lines.Count > ROWS)
            {
                for (int i = 0; i < _lines.Count - ROWS && i < ROWS; i++)
                {
                    //The color
                    if (i % 2 != 0)
                    {
                        xGps.DrawRectangle(brushes[0], new XRect(new XPoint(smallRectStartCo[2].X, smallRectStartCo[2].Y - OFFSET), new XPoint(smallRectStartCo[3].X + SMALLNOTERECTWIDTH, smallRectStartCo[3].Y + SMALLRECTHEIGHT - OFFSET)));
                    }
                    else
                    {
                        xGps.DrawRectangle(brushes[1], new XRect(new XPoint(smallRectStartCo[2].X, smallRectStartCo[2].Y - OFFSET), new XPoint(smallRectStartCo[3].X + SMALLNOTERECTWIDTH, smallRectStartCo[3].Y + SMALLRECTHEIGHT - OFFSET)));
                    }

                    rectCurrentLine = new XRect(smallRectStartCo[2], new XPoint(smallRectStartCo[3].X, smallRectStartCo[2].Y + SMALLRECTHEIGHT));
                    xtf.DrawString(_lines[i + (int)ROWS].GetWeekdayS() + "  " + _lines[i + (int)ROWS].GetDateS(), boldFont, XBrushes.Black, rectCurrentLine, XStringFormats.TopLeft);
                    rectCurrentLine = new XRect(smallRectStartCo[3], new XPoint(smallRectStartCo[3].X + SMALLNOTERECTWIDTH, smallRectStartCo[3].Y + SMALLRECTHEIGHT));
                    xtf.DrawString(_lines[i + (int)ROWS].GetNotes(), regularFont, XBrushes.Black, rectCurrentLine, XStringFormats.TopLeft);

                    smallRectStartCo[2].Y += SMALLRECTHEIGHT;
                    smallRectStartCo[3].Y += SMALLRECTHEIGHT;
                }
            }
            #endregion

            #region Bottom

            XRect        rect;
            const string INFO1 = "Alle Termine dieser Liste müssen in der Kursmappe eingetragen sein," +
                                 "auch die unterrichtsfreien Tage. Alle Termine(außer den Ferien)" +
                                 "müssen durch ihre Paraphe bestätigt werden. Tragen Sie bitte auch" +
                                 "die Fehlstundenzahl sowie die Soll - Ist - Stunden(Kursheft S.5) ein. ";
            const string INFO2 = "Hinweis: Schüler, die aus schulischen Gründen den Unterricht " +
                                 "versäumt haben(Klausur, schul.Veranstaltung usw.) müssen im " +
                                 "Kursheft aufgeführt werden. Diese Stunden dürfen auf dem " +
                                 "Zeugnis aber nicht als Fehlstunden vermerkt werden.";
            string OUTPUT = INFO1 + "\r\n\r\n" + INFO2;

            //If there is no lines at the second column, put the info direct at the second line.
            if (this._lines.Count - ROWS > 0)
            {
                rect = new XRect(smallRectStartCo[2].X, smallRectStartCo[2].Y + SMALLRECTHEIGHT, SMALLDATERECTWIDTH + SMALLNOTERECTWIDTH, Formats.A4.pixelHeight - (smallRectStartCo[2].Y + SMALLRECTHEIGHT));
                xtf.DrawString(OUTPUT, smallNoteFont, XBrushes.Black, rect, XStringFormats.TopLeft);
            }
            //Otherwise, add spaces
            else
            {
                rect = new XRect(smallRectStartCo[2].X, smallRectStartCo[2].Y, SMALLDATERECTWIDTH + SMALLNOTERECTWIDTH, Formats.A4.pixelHeight - (smallRectStartCo[2].Y + SMALLRECTHEIGHT));
                xtf.DrawString(OUTPUT, smallNoteFont, XBrushes.Black, rect, XStringFormats.TopLeft);
            }

            rect = new XRect(smallRectStartCo[0].X, smallRectStartCo[0].Y + Formats.GetPixel(1), SMALLNOTERECTWIDTH + SMALLDATERECTWIDTH, Formats.A4.pixelHeight - (smallRectStartCo[0].Y + SMALLRECTHEIGHT / 2));
            xGps.DrawString($"1. Kursabschnitt: {periods[0]:dd-MM-yyyy} - {periods[1].AddDays(-17):dd-MM-yyyy}", regularFont, XBrushes.Black, rect, XStringFormats.TopLeft);
            smallRectStartCo[0].Y += SMALLRECTHEIGHT / 2 + Formats.GetPixel(2);
            rect = new XRect(smallRectStartCo[0].X, smallRectStartCo[0].Y + Formats.GetPixel(1), SMALLNOTERECTWIDTH + SMALLDATERECTWIDTH, Formats.A4.pixelHeight - (smallRectStartCo[0].Y + SMALLRECTHEIGHT / 2));
            xGps.DrawString($"2. Kursabschnitt: {periods[1]:dd-MM-yyyy} - {periods[2]:dd-MM-yyyy}", regularFont, XBrushes.Black, rect, XStringFormats.TopLeft);
            #endregion

            #region Clean Up

            //Test illegal character to avoid the error when saving the document
            foreach (char c in title.ToCharArray())
            {
                //Test if there is illegal character in the title
                if (!((c >= 97 && c <= 123) || (c >= 48 && c <= 57) || (c >= 65 && c <= 90) ||
                      c == 45 || c == 46 || c == 64 || c == 95 || c == 32 || c == 'ä' || c == 'ö' || c == 'ü' ||
                      c == 'ß' || c == 'Ä' || c == 'Ö' || c == 'Ü'))
                {
                    //Replace it with .
                    title = title.Replace(c, '.');
                }
            }

            document.Save($"{storedPath}\\{title}.pdf");
            document.Close();
            document.Dispose();
            GC.Collect();

            Debug.WriteLine($"{storedPath}\\{title}.pdf ist exportiert.");
            #endregion
            return(true);
        }
Beispiel #4
0
        /// <summary>
        /// Create a note board based on the given date periods
        /// </summary>
        /// <param name="dates">An array of DateTime objects represents the start of year, of the second period and the end of the half year. </param>
        /// <returns>A boolean value represents whether this operation finished successfully or not</returns>
        private bool CreateBoard(DateTime[] dates, DateTime[,] holidays)
        {
            if (dates.Length != 4)
            {
                throw new ArgumentException("The augument \"dates\" (array of DateTime) must have 4 items", nameof(dates));
            }
            if (holidays.Length != 4)
            {
                throw new ArgumentException("The augument \"holidays\" (array of DateTime) must have 4 items", nameof(holidays));
            }

            //start a new sheet
            Excel.Worksheet sheet1;
            sheet1 = (Excel.Worksheet)Globals.ThisAddIn.Application.Worksheets.Add();

            Excel.Range tRange;

            //Entire Sheet Setting:
            Excel.Range er = sheet1.get_Range("A:A", System.Type.Missing);
            er.EntireColumn.EntireRow.ColumnWidth = 30;
            er.EntireColumn.EntireRow.RowHeight   = 30;

            for (int i = 1; i < 4; i++)
            {
                sheet1.Cells[1, (i + 1) * 2].EntireColumn.ColumnWidth  = 10;
                sheet1.Cells[1, (i + 1) * 2].EntireColumn.WrapText     = true;
                sheet1.Cells[1, (i + 1) * 2].EntireColumn.NumberFormat = "@";
                sheet1.Cells[1, (i + 1) * 2 - 1] = "Besonderheit " + i;
                sheet1.Cells[1, (i + 1) * 2]     = "Stufe";
            }


            //Titles:
            sheet1.Cells[1, 1] = "Wochentage";
            sheet1.Cells[1, 2] = "Datum";
            sheet1.Cells[1, 9] = dates[0].ToString("dd.MM.yyyy", DEUTSCHCULT) + "~" + dates[1].ToString("dd.MM.yyyy", DEUTSCHCULT) + "~" + dates[2].ToString("dd.MM.yyyy", DEUTSCHCULT) + "~" + dates[3].ToString("dd.MM.yyyy", DEUTSCHCULT);
            sheet1.Cells[2, 9] = $"{holidays[0, 0]:dd.MM.yyyy}~{holidays[0, 1]:dd.MM.yyyy}";
            sheet1.Cells[3, 9] = $"{holidays[1, 0]:dd.MM.yyyy}~{holidays[1, 1]:dd.MM.yyyy}";
            sheet1.Cells[1, 1].EntireRow.Font.Bold = true;
            sheet1.Cells[1, 1].EntireRow.Font.Size = 14;

            sheet1.Application.ActiveWindow.SplitRow    = 1;
            sheet1.Application.ActiveWindow.FreezePanes = true;


            #region 1. + 2. column: Weekdays and Dates
            int[] dateLength = new int[3] {
                0, DateTimeCalcUtils.BusinessDaysUntil(dates[0], dates[1]), DateTimeCalcUtils.BusinessDaysUntil(dates[0], dates[1]) + DateTimeCalcUtils.BusinessDaysUntil(dates[2], dates[3]) - 1
            };

            DateTime[] startDates = new DateTime[3] {
                dates[0], dates[2], dates[3]
            };
            string[] titlesStart = new string[3] {
                "Anfang d. 1. Abschnitts", "Anfang d. 2. Abschnitts", "Ende des Schulhalbjahres"
            };
            sheet1.get_Range("B:B", System.Type.Missing).NumberFormat = "dd.MM.yyyy";  //It MAY cause a problem

            for (int i = 0; i < dateLength.Length; i++)
            {
                tRange       = sheet1.Range[sheet1.Cells[dateLength[i] + 3 + i, 1], sheet1.Cells[dateLength[i] + 3 + i, 1]];
                tRange.Value = DEUTSCHCULT.DateTimeFormat.GetDayName(startDates[i].DayOfWeek);


                tRange       = sheet1.Range[sheet1.Cells[dateLength[i] + 3 + i, 2], sheet1.Cells[dateLength[i] + 3 + i, 2]];
                tRange.Value = startDates[i].Date;

                if (i < 2)
                {
                    sheet1.Cells[dateLength[i] + 2 + i, 2] = titlesStart[i];
                    sheet1.Cells[dateLength[i] + 2 + i, 2].EntireRow.Interior.Color = Color.FromArgb(146, 208, 80);
                    ((Excel.Range)sheet1.Range[sheet1.Cells[dateLength[i] + 2 + i, 2], sheet1.Cells[dateLength[i] + 2 + i, 2]]).Font.Size = 14;
                    tRange.AutoFill(sheet1.Range[sheet1.Cells[dateLength[i] + 3 + i, 2], sheet1.Cells[dateLength[i + 1] + i + 2, 2]], Excel.XlAutoFillType.xlFillWeekdays);

                    tRange = sheet1.Range[sheet1.Cells[dateLength[i] + 3 + i, 1], sheet1.Cells[dateLength[i] + 3 + i, 1]];
                    tRange.AutoFill(sheet1.Range[sheet1.Cells[dateLength[i] + 3 + i, 1], sheet1.Cells[dateLength[i + 1] + i + 2, 1]], Excel.XlAutoFillType.xlFillWeekdays);
                }
            }
            sheet1.Cells[dateLength[2] + 3 + 1, 1] = DEUTSCHCULT.DateTimeFormat.GetDayName(dates[3].DayOfWeek);
            sheet1.Cells[dateLength[2] + 3 + 2, 1] = "";
            sheet1.Cells[dateLength[2] + 3 + 1, 2] = dates[3].Date;
            sheet1.Cells[dateLength[2] + 3 + 2, 2] = titlesStart[2];
            sheet1.Cells[dateLength[2] + 3 + 2, 2].EntireRow.Interior.Color = Color.FromArgb(146, 208, 80);
            ((Excel.Range)sheet1.Range[sheet1.Cells[dateLength[2] + 3 + 2, 2], sheet1.Cells[dateLength[2] + 3 + 2, 2]]).Font.Size = 14;
            #endregion

            sheet1.Cells[1, 1].EntireColumn.AutoFit();
            sheet1.Activate();

            return(true);
        }
Beispiel #5
0
        /// <summary>
        /// Read all the note from the given Worksheet object, create the Daynotes objects and add them to this CoursePlan object.
        /// </summary>
        /// <param name="noteBoard">A excel worksheet object represents the note board. </param>
        /// <param name="dates">An array of DateTime objects contains all the start time of this course </param>
        /// <param name="isRegular">An array of string represents this course appears every week or every two weeks.
        ///                 "" represents regular, "g" represents only on even weeks and "u" only on odd weeks.
        ///                 The order of this array should be the same as the order of the array "dates". </param>
        public void ReadNoteBoard(Excel.Worksheet noteBoard, DateTime[] dates, string[] isRegular)
        {
            DateTimeCalcUtils.SortDate(ref dates, ref isRegular);
            //Initialize the counter
            int k = 0;

            //Traverse the note board
            for (int i = 3; i < noteBoard.UsedRange.Rows.Count - 1; i++)
            {
                //Jump the title lines
                if (((Excel.Range)noteBoard.Cells[i, 2]).Text == "Anfang d. 2. Abschnitts")
                {
                    //Jump the holiday
                    for (int n = 0; n < dates.Length; n++)
                    {
                        dates[n] = dates[n].AddDays(14);
                    }
                    //To the next row of the note board
                    continue;
                }
                //Jump the title lines
                else if (((Excel.Range)noteBoard.Cells[i, 2]).Text == "Ende des Schuljahres" || ((Excel.Range)noteBoard.Cells[i, 2]).Text == "")
                {
                    continue;
                }

                DateTime lineDate = ((Excel.Range)noteBoard.Cells[i, 2]).Value;

                //If the date fits
                if (DateTime.Compare(lineDate, dates[k]) == 0)
                {
                    //If this weekday is regular, or it fits to the rule
                    if (string.IsNullOrEmpty(isRegular[k]) ||
                        (DateTimeCalcUtils.IsEvenWeek(lineDate) && isRegular[k] == "g") ||
                        (!DateTimeCalcUtils.IsEvenWeek(lineDate) && isRegular[k] == "u"))
                    {
                        Daynote currentDaynotes = new Daynote(lineDate);

                        //Go through the three notes on the same row
                        for (int j = 3; j < 8; j += 2)
                        {
                            string currentNote      = ((Excel.Range)noteBoard.Cells[i, j]).Value;
                            string currentLineGrade = ((Excel.Range)noteBoard.Cells[i, j + 1]).Value;

                            //When the note is not empty
                            if (currentNote != null)
                            {
                                //If the grade fits to the current course
                                if (currentLineGrade == this._className || currentLineGrade == this.GetGrade() || currentLineGrade == null)
                                {
                                    currentDaynotes.AddNote(currentNote);
                                }
                            }
                        }
                        //Add the daynote to the plan
                        this.AddLine(currentDaynotes);
                    }

                    dates[k] = dates[k].AddDays(7);

                    //Move the counter of the DatesA array
                    if (k < dates.Length - 1)
                    {
                        k++;
                    }
                    else
                    {
                        k = 0;
                    }
                }
            }
        }
        /// <summary>
        /// Export the plans based on the given coursePlan and the note board
        /// </summary>
        /// <returns>An Integer represents how many pdf files were exported</returns>
        private void ExportPlans()
        {
            //Initialize the lists for the loop
            List <CoursePlan> plans     = new List <CoursePlan>();
            List <DateTime[]> dates     = new List <DateTime[]>();
            List <string[]>   isRegular = new List <string[]>();

            foreach (string CurrentValidClass in _PDFClasses)
            {
                //Get the datatable that contains all the information for the current class
                try
                {
                    DataTable currentClassDT = _coursePlan.Select($"Class = '{CurrentValidClass}'").CopyToDataTable();

                    //Get a List containing all unique subjects
                    var subjectList = currentClassDT.AsEnumerable().Select(s => new
                    {
                        Subject = s.Field <string>("Subject")
                    })
                                      .Distinct().ToList();

                    //Traverse the list of subjects
                    foreach (var currentSubject in subjectList)
                    {
                        //Check the subject and remove the illegal chars
                        //As the subjectList contains the strings like {Subject = GE} etc.
                        string sbj = currentSubject.ToString().Substring(12, currentSubject.ToString().Length - 2 - 12);

                        //Get the information of a specific course
                        DataRow[] currentCourse = currentClassDT.Select($"Subject = '{sbj}'");

                        if (currentCourse.Length != 0 && !string.IsNullOrEmpty((string)currentCourse[0].ItemArray[1]))
                        {
                            //Create a new plan
                            CoursePlan currentPlan = new CoursePlan(currentCourse[0].ItemArray[3].ToString(), currentCourse[0].ItemArray[1].ToString().Substring(0, 2),
                                                                    currentCourse[0].ItemArray[2].ToString());
                            List <DateTime> currentDT        = new List <DateTime>();
                            List <string>   currentIsRegular = new List <string>();
                            foreach (DataRow row in currentCourse)
                            {
                                //Assuming that all the rows are not same
                                int indexOfRow = Array.IndexOf(currentCourse, row);

                                //If this row does not contain any number or any class
                                // TODO
                                if (string.IsNullOrEmpty((string)row.ItemArray[0]) || string.IsNullOrEmpty((string)row.ItemArray[1]))
                                {
                                    continue;
                                }
                                //If this is the first line or the dates are not the same
                                if (indexOfRow == 0 ||
                                    !currentDT.Contains(DateTimeCalcUtils.GetNearestWeekdayS(_periods[0], DateTimeCalcUtils.GetWeekdayFromNumber(int.Parse(currentCourse[indexOfRow].ItemArray[5].ToString(), DEUTSCHCULT)))))
                                {
                                    currentDT.Add(DateTimeCalcUtils.GetNearestWeekdayS(_periods[0], DateTimeCalcUtils.GetWeekdayFromNumber(int.Parse(currentCourse[indexOfRow].ItemArray[5].ToString(), DEUTSCHCULT))));

                                    //If the course is on the 8th hour, then it will only be on even weeks
                                    if (row.ItemArray[6].ToString() == "8")
                                    {
                                        currentIsRegular.Add("g");
                                    }
                                    //On the 9th hour, then only on odd weeks
                                    else if (row.ItemArray[6].ToString() == "9")
                                    {
                                        currentIsRegular.Add("u");
                                    }
                                    //Otherwise every week
                                    else
                                    {
                                        currentIsRegular.Add("");
                                    }
                                }
                                //If the isRegular value, however, are not the same, then if there's a course on this day on every week, set isRegular to regular("")
                                else if (!string.IsNullOrEmpty(currentIsRegular.Last()) &&
                                         //If this course will be held on 8th AND on 9th hour
                                         //Then change the IsRegular to every week
                                         (
                                             (row.ItemArray[6].ToString() != "8" && row.ItemArray[6].ToString() != "9") ||
                                             (row.ItemArray[6].ToString() == "8" && currentIsRegular.Last() == "u") ||
                                             (row.ItemArray[6].ToString() == "9" && currentIsRegular.Last() == "g"))
                                         )
                                {
                                    currentIsRegular[currentIsRegular.Count - 1] = "";
                                }
                            }

                            //Add them to the list
                            plans.Add(currentPlan);
                            dates.Add(currentDT.ToArray());
                            isRegular.Add(currentIsRegular.ToArray());
                        }
                    }
                }
                //If there is no course for this class, the there would be an exception thrown by .CopyToDataTable()
                //Therefore, catch this exception and just continue to the next class
                catch (InvalidOperationException)
                {
                    continue;
                }
            }

            //Start a new thread showing the progress
            Thread progressWindowThread = new Thread(delegate()
            {
                FormProgress formProgress = new FormProgress(this, plans.Count);
                formProgress.ShowDialog();
            });

            progressWindowThread.Start();

            //Export them
            if (plans.Count == dates.Count && dates.Count == isRegular.Count && isRegular.Count != 0)
            {
                for (int i = 0; i < plans.Count; i++)
                {
                    CoursePlan currentCoursePlan = plans[i];
                    currentCoursePlan.ReadNoteBoard(_noteBoard, dates[i], isRegular[i], _holidays);

                    //After all the note board processed
                    //Export the current course plan
                    try
                    {
                        _           = currentCoursePlan.ExportAsPDF(_periods, _PDFStorePath);
                        CurrentInfo = $"{currentCoursePlan.GetTitle()} wurde exportiert. ";
                        ExportedPDFs++;
                    }
                    catch (ArgumentException e)
                    {
                        MessageBox.Show(e.Message, "Warning", MessageBoxButtons.OK, MessageBoxIcon.Warning, MessageBoxDefaultButton.Button1, (MessageBoxOptions)0x40000);
                    }
                }
            }
            else
            {
                System.Diagnostics.Debug.WriteLine("The Plans is empty: no plan stored");
                ExportedPDFs = -1;
            }

            //Close the progress window
            progressWindowThread.Abort();
            System.Diagnostics.Debug.WriteLine($"{ExportedPDFs} wurde exportiert unter: {_PDFStorePath}");
        }
Beispiel #7
0
        /// <summary>
        /// Export this course to the given path as pdf
        /// </summary>
        /// <param name="periods">An array of DateTime contains 3 items representing the start of the year,
        ///                     the start of the second period and the end of the half year.</param>
        /// <param name="storedPath">The path where the exported pdf should be stored.
        ///                     This path does NOT contain the name of this pdf file.
        ///                     The name will be like this format:
        ///                     CourseName-Teacher-Class.pdf</param>
        /// <param name="logoFilePath">A optional parameter represents where the logo is stored.
        ///                     If this is not given, then the logo will be replaced by the words "Sollstuden für Kurs"</param>
        /// <returns>A boolean value represents whether the export is successful or not.</returns>
        public bool ExportAsPDF(DateTime[] periods, string storedPath)
        {
            DateTime     dtNow        = DateTime.Now;
            string       fileName     = $"{this._courseName}-{this._teacher}-{this._className}";
            string       title1       = $"Jahrgangstufe {this._className.Substring(0, 2)}.{DateTimeCalcUtils.GetHalfYearAsNumber(_lines[0].GetDate())}    {DateTimeCalcUtils.GetHalfYear(_lines[0].GetDate())}";
            string       title2       = $"Sollstunde für Kurs  {this._courseName}-{this._teacher}-{this._className}";
            const string columnTitle1 = "Tag";
            const string columnTitle2 = "Datum";
            const string columnTitle3 = "Besonderheit";

            PdfDocument document = new PdfDocument();
            PdfPage     page     = document.AddPage();
            XGraphics   xGps     = XGraphics.FromPdfPage(page);

            #region Preset Format
            const double ROWS = 70;
            //double SMALLWEEKDAYRECTWIDTH = Formats.getPixel(5);
            double SMALLDAYRECTWIDTH  = Formats.GetPixel(10);
            double SMALLDATERECTWIDTH = Formats.GetPixel(20);
            double SMALLNOTERECTWIDTH = Formats.GetPixel(55);
            double SMALLRECTHEIGHT    = Formats.GetPixel(3.6);
            double TOPHEIGHT          = Formats.GetPixel(21);
            double LEFTBLANK          = Formats.GetPixel(10);
            double CENTERBLANK        = Formats.GetPixel(20);
            //double RIGHTBLANK = Formats.getPixel(10);
            double OFFSET = Formats.GetPixel(0.6);
            //IN PIXEL
            XPoint[] smallRectStartCo = new XPoint[6] {
                new XPoint(), new XPoint(), new XPoint(), new XPoint(), new XPoint(), new XPoint()
            };

            #endregion

            #region Preset Text Format
            XFont          boldFont      = new XFont("Times New Roman", 7.5, XFontStyle.Bold);
            XFont          regularFont   = new XFont("Times New Roman", 7.5);
            XFont          titleFont     = new XFont("Times New Roman", 12, XFontStyle.Bold);
            XFont          subtitleFont  = new XFont("Times New Roman", 9, XFontStyle.Bold);
            XFont          smallNoteFont = new XFont("Times New Roman", 6.5);
            XTextFormatter xtf           = new XTextFormatter(xGps);
            XBrush[]       brushes       = new XBrush[2] {
                new XSolidBrush(XColor.FromArgb(230, 230, 230)), new XSolidBrush(XColor.FromArgb(210, 210, 210))
            };
            XPen pen     = new XPen(XColors.Gray, 0.5);
            XPen darkPen = new XPen(XColors.Black, 0.8);
            #endregion

            //If the data is too long or too short
            if (this._lines.Count > ROWS)
            {
                throw new ArgumentException($"The weeklyplan is too long: {_lines.Count}. \nAt: {_courseName}-{_className}-{_teacher}");
            }
            else if (_lines.Count < 3)
            {
                throw new ArgumentException($"The weeklyplan is too short: {_lines.Count}. \nAt: {_courseName}-{_className}-{_teacher}");
            }

            #region Points

            smallRectStartCo[0].X = LEFTBLANK;
            smallRectStartCo[0].Y = TOPHEIGHT;
            smallRectStartCo[1].X = LEFTBLANK + SMALLDAYRECTWIDTH;
            smallRectStartCo[1].Y = TOPHEIGHT;
            smallRectStartCo[2].X = LEFTBLANK + SMALLDAYRECTWIDTH + SMALLDATERECTWIDTH;
            smallRectStartCo[2].Y = TOPHEIGHT;
            smallRectStartCo[3].X = LEFTBLANK + SMALLDAYRECTWIDTH + SMALLDATERECTWIDTH + SMALLNOTERECTWIDTH + CENTERBLANK;
            smallRectStartCo[3].Y = TOPHEIGHT;
            smallRectStartCo[4].X = LEFTBLANK + 2 * SMALLDAYRECTWIDTH + SMALLDATERECTWIDTH + SMALLNOTERECTWIDTH + CENTERBLANK;
            smallRectStartCo[4].Y = TOPHEIGHT;
            smallRectStartCo[5].X = LEFTBLANK + CENTERBLANK + 2 * SMALLDAYRECTWIDTH + 2 * SMALLDATERECTWIDTH + SMALLNOTERECTWIDTH;
            smallRectStartCo[5].Y = TOPHEIGHT;

            #endregion

            #region HEAD

            //Set the titles
            XRect rectTitle = new XRect(Formats.GetPixel(10), Formats.GetPixel(3), Formats.GetPixel(85), Formats.GetPixel(5));
            xGps.DrawString(title1, titleFont, XBrushes.Black, rectTitle, XStringFormats.TopLeft);

            rectTitle = new XRect(Formats.GetPixel(10), Formats.GetPixel(8), Formats.GetPixel(85), Formats.GetPixel(5));
            xGps.DrawString(title2, titleFont, XBrushes.Black, rectTitle, XStringFormats.TopLeft);

            rectTitle = new XRect(smallRectStartCo[3].X, Formats.GetPixel(3), Formats.GetPixel(85), Formats.GetPixel(5));
            xGps.DrawString(title1, titleFont, XBrushes.Black, rectTitle, XStringFormats.TopLeft);

            rectTitle = new XRect(smallRectStartCo[3].X, Formats.GetPixel(8), Formats.GetPixel(85), Formats.GetPixel(5));
            xGps.DrawString(title2, titleFont, XBrushes.Black, rectTitle, XStringFormats.TopLeft);

            // column titles
            rectTitle = new XRect(new XPoint(smallRectStartCo[0].X, smallRectStartCo[0].Y - SMALLRECTHEIGHT - 5), new XPoint(LEFTBLANK + SMALLDATERECTWIDTH, smallRectStartCo[0].Y));
            xGps.DrawString(columnTitle1, boldFont, XBrushes.Black, rectTitle, XStringFormats.TopLeft);
            rectTitle = new XRect(new XPoint(smallRectStartCo[1].X, smallRectStartCo[0].Y - SMALLRECTHEIGHT - 5), new XPoint(LEFTBLANK + SMALLDATERECTWIDTH, smallRectStartCo[0].Y));
            xGps.DrawString(columnTitle2, boldFont, XBrushes.Black, rectTitle, XStringFormats.TopLeft);
            rectTitle = new XRect(new XPoint(smallRectStartCo[2].X, smallRectStartCo[0].Y - SMALLRECTHEIGHT - 5), new XPoint(smallRectStartCo[2].X + SMALLNOTERECTWIDTH, smallRectStartCo[2].Y));
            xGps.DrawString(columnTitle3, boldFont, XBrushes.Black, rectTitle, XStringFormats.TopLeft);

            rectTitle = new XRect(new XPoint(smallRectStartCo[3].X, smallRectStartCo[3].Y - SMALLRECTHEIGHT - 5), new XPoint(smallRectStartCo[3].X, smallRectStartCo[3].Y));
            xGps.DrawString(columnTitle1, boldFont, XBrushes.Black, rectTitle, XStringFormats.TopLeft);
            rectTitle = new XRect(new XPoint(smallRectStartCo[4].X, smallRectStartCo[3].Y - SMALLRECTHEIGHT - 5), new XPoint(smallRectStartCo[4].X, smallRectStartCo[3].Y));
            xGps.DrawString(columnTitle2, boldFont, XBrushes.Black, rectTitle, XStringFormats.TopLeft);
            rectTitle = new XRect(new XPoint(smallRectStartCo[5].X, smallRectStartCo[3].Y - SMALLRECTHEIGHT - 5), new XPoint(smallRectStartCo[5].X + SMALLNOTERECTWIDTH, smallRectStartCo[5].Y));
            xGps.DrawString(columnTitle3, boldFont, XBrushes.Black, rectTitle, XStringFormats.TopLeft);

            #endregion

            #region Main Body

            XRect rectCurrentLine;
            //The first column
            for (int i = 0; i < this._lines.Count && i < ROWS; i++)
            {
                //The color
                if (i % 2 != 0)
                {
                    xGps.DrawRectangle(brushes[0], new XRect(new XPoint(smallRectStartCo[0].X, smallRectStartCo[0].Y - OFFSET), new XPoint(smallRectStartCo[2].X + SMALLNOTERECTWIDTH, smallRectStartCo[2].Y + SMALLRECTHEIGHT - OFFSET)));
                }
                else
                {
                    xGps.DrawRectangle(brushes[1], new XRect(new XPoint(smallRectStartCo[0].X, smallRectStartCo[0].Y - OFFSET), new XPoint(smallRectStartCo[2].X + SMALLNOTERECTWIDTH, smallRectStartCo[2].Y + SMALLRECTHEIGHT - OFFSET)));
                }

                rectCurrentLine = new XRect(smallRectStartCo[0], new XPoint(LEFTBLANK + SMALLDAYRECTWIDTH, smallRectStartCo[0].Y + SMALLRECTHEIGHT));
                xtf.DrawString(_lines[i].GetWeekdayS(), boldFont, XBrushes.Black, rectCurrentLine, XStringFormats.TopLeft);
                rectCurrentLine = new XRect(smallRectStartCo[1], new XPoint(LEFTBLANK + SMALLDATERECTWIDTH, smallRectStartCo[1].Y + SMALLRECTHEIGHT));
                xtf.DrawString(_lines[i].GetDateS(), boldFont, XBrushes.Black, rectCurrentLine, XStringFormats.TopLeft);
                rectCurrentLine = new XRect(smallRectStartCo[2], new XPoint(smallRectStartCo[2].X + SMALLNOTERECTWIDTH, smallRectStartCo[2].Y + SMALLRECTHEIGHT));
                xtf.DrawString(_lines[i].GetNotes(), regularFont, XBrushes.Black, rectCurrentLine, XStringFormats.TopLeft);

                smallRectStartCo[0].Y += SMALLRECTHEIGHT;
                smallRectStartCo[1].Y += SMALLRECTHEIGHT;
                smallRectStartCo[2].Y += SMALLRECTHEIGHT;
            }
            //The second column
            for (int i = 0; i < _lines.Count && i < ROWS; i++)
            {
                //The color
                if (i % 2 != 0)
                {
                    xGps.DrawRectangle(brushes[0], new XRect(new XPoint(smallRectStartCo[3].X, smallRectStartCo[3].Y - OFFSET), new XPoint(smallRectStartCo[5].X + SMALLNOTERECTWIDTH, smallRectStartCo[5].Y + SMALLRECTHEIGHT - OFFSET)));
                }
                else
                {
                    xGps.DrawRectangle(brushes[1], new XRect(new XPoint(smallRectStartCo[3].X, smallRectStartCo[3].Y - OFFSET), new XPoint(smallRectStartCo[5].X + SMALLNOTERECTWIDTH, smallRectStartCo[5].Y + SMALLRECTHEIGHT - OFFSET)));
                }

                rectCurrentLine = new XRect(smallRectStartCo[3], new XPoint(smallRectStartCo[4].X, smallRectStartCo[3].Y + SMALLRECTHEIGHT));
                xtf.DrawString(_lines[i].GetWeekdayS(), boldFont, XBrushes.Black, rectCurrentLine, XStringFormats.TopLeft);
                rectCurrentLine = new XRect(smallRectStartCo[4], new XPoint(smallRectStartCo[5].X, smallRectStartCo[4].Y + SMALLRECTHEIGHT));
                xtf.DrawString(_lines[i].GetDateS(), boldFont, XBrushes.Black, rectCurrentLine, XStringFormats.TopLeft);
                rectCurrentLine = new XRect(smallRectStartCo[5], new XPoint(smallRectStartCo[5].X + SMALLNOTERECTWIDTH, smallRectStartCo[5].Y + SMALLRECTHEIGHT));
                xtf.DrawString(_lines[i].GetNotes(), regularFont, XBrushes.Black, rectCurrentLine, XStringFormats.TopLeft);

                smallRectStartCo[3].Y += SMALLRECTHEIGHT;
                smallRectStartCo[4].Y += SMALLRECTHEIGHT;
                smallRectStartCo[5].Y += SMALLRECTHEIGHT;
            }

            #endregion

            #region Bottom

            // Seperate lines
            xGps.DrawLine(darkPen, smallRectStartCo[0].X, TOPHEIGHT - 4, smallRectStartCo[2].X + SMALLNOTERECTWIDTH + 5, TOPHEIGHT - 4);
            xGps.DrawLine(pen, smallRectStartCo[1].X - 6, TOPHEIGHT - Formats.GetPixel(5.5), smallRectStartCo[1].X - 6, smallRectStartCo[0].Y);
            xGps.DrawLine(pen, smallRectStartCo[2].X - 15, TOPHEIGHT - Formats.GetPixel(5.5), smallRectStartCo[2].X - 15, smallRectStartCo[1].Y);

            xGps.DrawLine(darkPen, smallRectStartCo[3].X, TOPHEIGHT - 4, smallRectStartCo[5].X + SMALLNOTERECTWIDTH + 5, TOPHEIGHT - 4);
            xGps.DrawLine(pen, smallRectStartCo[4].X - 6, TOPHEIGHT - Formats.GetPixel(5), smallRectStartCo[4].X - 6, smallRectStartCo[0].Y);
            xGps.DrawLine(pen, smallRectStartCo[5].X - 15, TOPHEIGHT - Formats.GetPixel(5.5), smallRectStartCo[5].X - 15, smallRectStartCo[1].Y);



            XRect        rect;
            const string INFO1 = "Alle Termine dieser Liste müssen in der Kursmappe eingetragen sein, " +
                                 "auch die unterrichtsfreien Tage. Alle Termine(außer den Ferien) " +
                                 "müssen durch ihre Paraphe bestätigt werden. Tragen Sie bitte auch " +
                                 "die Fehlstundenzahl sowie die Soll - Ist - Stunden(Kursheft S.5) ein. ";
            const string INFO2 = "Hinweis: Schüler, die aus schulischen Gründen den Unterricht " +
                                 "versäumt haben(Klausur, schul.Veranstaltung usw.) müssen im " +
                                 "Kursheft aufgeführt werden. Diese Stunden dürfen auf dem " +
                                 "Zeugnis aber nicht als Fehlstunden vermerkt werden.";
            string OUTPUT = INFO1 + "\r\n" + INFO2;


            rect = new XRect(smallRectStartCo[0].X, smallRectStartCo[0].Y + Formats.GetPixel(1), SMALLNOTERECTWIDTH + SMALLDATERECTWIDTH, Formats.A4.pixelHeight - (smallRectStartCo[0].Y + SMALLRECTHEIGHT / 2));
            xGps.DrawString($"1. Kursabschnitt: {periods[0]:dd.MM.yyyy} - {periods[1]:dd.MM.yyyy}", smallNoteFont, XBrushes.Black, rect, XStringFormats.TopLeft);
            smallRectStartCo[0].Y += SMALLRECTHEIGHT / 2 + Formats.GetPixel(1);
            rect = new XRect(smallRectStartCo[0].X, smallRectStartCo[0].Y + Formats.GetPixel(1), SMALLNOTERECTWIDTH + SMALLDATERECTWIDTH, Formats.A4.pixelHeight - (smallRectStartCo[0].Y + SMALLRECTHEIGHT / 2));
            xGps.DrawString($"2. Kursabschnitt: {periods[2]:dd.MM.yyyy} - {periods[3]:dd.MM.yyyy}", smallNoteFont, XBrushes.Black, rect, XStringFormats.TopLeft);

            smallRectStartCo[0].Y += SMALLRECTHEIGHT / 2 + Formats.GetPixel(3);
            rect = new XRect(smallRectStartCo[0].X, smallRectStartCo[0].Y + Formats.GetPixel(1), SMALLNOTERECTWIDTH + SMALLDATERECTWIDTH, Formats.A4.pixelHeight - (smallRectStartCo[0].Y + SMALLRECTHEIGHT / 2));
            xtf.DrawString(OUTPUT, smallNoteFont, XBrushes.Black, rect, XStringFormats.TopLeft);


            //Set the current date and the half year
            XRect rectDate = new XRect(Formats.GetPixel(180), Formats.GetPixel(289), Formats.GetPixel(28), Formats.GetPixel(4));
            xGps.DrawString($"Stand: {dtNow:dd.MM.yyyy}", regularFont, XBrushes.Gray, rectDate, XStringFormats.TopRight);

            XRect rectYear = new XRect(Formats.GetPixel(180), Formats.GetPixel(293), Formats.GetPixel(28), Formats.GetPixel(4));
            xGps.DrawString(DateTimeCalcUtils.GetHalfYear(this._lines[0].GetDate()), boldFont, XBrushes.Gray, rectYear, XStringFormats.TopRight);
            #endregion

            #region Clean Up

            //Test illegal character to avoid the error when saving the document
            foreach (char c in fileName.ToCharArray())
            {
                //Test if there is illegal character in the title
                if (!((c >= 97 && c <= 123) || (c >= 48 && c <= 57) || (c >= 65 && c <= 90) ||
                      c == 45 || c == 46 || c == 64 || c == 95 || c == 32 || c == 'ä' || c == 'ö' || c == 'ü' ||
                      c == 'ß' || c == 'Ä' || c == 'Ö' || c == 'Ü'))
                {
                    //Replace it with .
                    fileName = fileName.Replace(c, '.');
                }
            }

            document.Save($"{storedPath}\\{fileName}.pdf");
            document.Close();
            document.Dispose();

            Debug.WriteLine($"{storedPath}\\{fileName}.pdf ist exportiert.");
            #endregion
            return(true);
        }
Beispiel #8
0
        /// <summary>
        /// Read all the note from the given Worksheet object, create the Daynotes objects and add them to this CoursePlan object.
        /// </summary>
        /// <param name="noteBoard">A excel worksheet object represents the note board. </param>
        /// <param name="dates">An array of DateTime objects contains all the start time of this course </param>
        /// <param name="isRegular">An array of string represents this course appears every week or every two weeks.
        ///                 "" represents regular, "g" represents only on even weeks and "u" only on odd weeks.
        ///                 The order of this array should be the same as the order of the array "dates". </param>
        public void ReadNoteBoard(Excel.Worksheet noteBoard, DateTime[] dates, string[] isRegular, DateTime[,] holidays)
        {
            DateTimeCalcUtils.SortDate(ref dates, ref isRegular);
            //Initialize the counter
            int k = 0;

            //Get the end of the term
            var      dateCell = noteBoard.Cells[1, 9] as Excel.Range;
            DateTime endDate  = DateTime.Parse((dateCell.Text as string).Split('~').Last(),
                                               new CultureInfo("de-DE"),
                                               DateTimeStyles.NoCurrentDateDefault);

            //Traverse the note board
            for (int i = 3; i < noteBoard.UsedRange.Rows.Count; i++)
            {
                //Jump the title lines
                if (((Excel.Range)noteBoard.Cells[i, 2]).Text == "Anfang d. 2. Abschnitts" ||
                    ((Excel.Range)noteBoard.Cells[i, 2]).Text == "")
                {
                    continue;
                }
                else if (((Excel.Range)noteBoard.Cells[i, 2]).Text == "Ende des Schuljahres")
                {
                    break;
                }
                else if (DateTime.Compare(dates[k], endDate) > 0)
                {
                    break;
                }

                // If the dates is in holiday, jump it
                // Also add a daynote that says holiday until
                // Use date of the holiday begin
                bool inFirstHoliday = DateTime.Compare(dates[k], holidays[0, 0]) >= 0 &&
                                      DateTime.Compare(dates[k], holidays[0, 1]) <= 0;
                bool inSecondHoliday = DateTime.Compare(dates[k], holidays[1, 0]) >= 0 &&
                                       DateTime.Compare(dates[k], holidays[1, 1]) <= 0;
                if (inFirstHoliday || inSecondHoliday)
                {
                    // Jump the holidays
                    // Not use +14 days because not every holiday has 14 days
                    for (int j = 0; j < dates.Length; j++)
                    {
                        bool nowInFirstHoliday = DateTime.Compare(dates[j], holidays[0, 0]) >= 0 &&
                                                 DateTime.Compare(dates[j], holidays[0, 1]) <= 0;
                        bool nowInSecondHoliday = DateTime.Compare(dates[j], holidays[1, 0]) >= 0 &&
                                                  DateTime.Compare(dates[j], holidays[1, 1]) <= 0;
                        while (nowInFirstHoliday || nowInSecondHoliday)
                        {
                            dates[j]          = dates[j].AddDays(7);
                            nowInFirstHoliday = DateTime.Compare(dates[j], holidays[0, 0]) >= 0 &&
                                                DateTime.Compare(dates[j], holidays[0, 1]) <= 0;
                            nowInSecondHoliday = DateTime.Compare(dates[j], holidays[1, 0]) >= 0 &&
                                                 DateTime.Compare(dates[j], holidays[1, 1]) <= 0;
                        }
                    }

                    // Check the k index, if not correct, change it
                    for (int j = 0; j < dates.Length; j++)
                    {
                        if (DateTime.Compare(dates[k], dates[j]) > 0)
                        {
                            k = j;
                            j = 0;
                        }
                    }

                    // Add note about the holiday
                    if (inFirstHoliday)
                    {
                        Daynote holidayUntil = new Daynote(holidays[0, 0]);
                        holidayUntil.AddNote($"bis {holidays[0, 1]:dd.MM.yyyy} {DateTimeCalcUtils.GetHolidayType(holidays[0, 0])}");
                        this.AddLine(holidayUntil);
                    }
                    else if (inSecondHoliday)
                    {
                        Daynote holidayUntil = new Daynote(holidays[1, 0]);
                        holidayUntil.AddNote($"bis {holidays[1, 1]:dd.MM.yyyy} {DateTimeCalcUtils.GetHolidayType(holidays[1, 0])}");
                        this.AddLine(holidayUntil);
                    }
                }

                // Get the date of the current line of the note board
                DateTime lineDate = ((Excel.Range)noteBoard.Cells[i, 2]).Value;

                //If the date fits
                if (DateTime.Compare(lineDate, dates[k]) == 0)
                {
                    //If this weekday is regular, or it fits to the rule
                    if (string.IsNullOrEmpty(isRegular[k]) ||
                        (DateTimeCalcUtils.IsEvenWeek(lineDate) && isRegular[k] == "g") ||
                        (!DateTimeCalcUtils.IsEvenWeek(lineDate) && isRegular[k] == "u"))
                    {
                        Daynote currentDaynotes = new Daynote(lineDate);

                        //Go through the three notes on the same row
                        for (int j = 3; j < 8; j += 2)
                        {
                            string currentNote      = ((Excel.Range)noteBoard.Cells[i, j]).Value;
                            string currentLineGrade = ((Excel.Range)noteBoard.Cells[i, j + 1]).Value;

                            //When the note is not empty
                            if (currentNote != null)
                            {
                                //If the grade fits to the current course
                                if (currentLineGrade == this._className ||
                                    currentLineGrade == this.GetGrade() ||
                                    string.IsNullOrEmpty(currentLineGrade))
                                {
                                    currentDaynotes.AddNote(currentNote);
                                }
                            }
                        }
                        //Add the daynote to the plan
                        this.AddLine(currentDaynotes);
                    }

                    dates[k] = dates[k].AddDays(7);

                    //Move the counter of the DatesA array
                    if (k < dates.Length - 1)
                    {
                        k++;
                    }
                    else
                    {
                        k = 0;
                    }
                }
            }

            // string secondHoliday = $"bis {holidays[1, 1]:dd.MM.yyyy} {DateTimeCalcUtils.GetHolidayType(holidays[1, 0])}";
            // if (!_lines.Last().GetNotes().Contains(secondHoliday))
            //     _lines.Last().AddNote(secondHoliday);
        }
        /// <summary>
        /// If the accept is clicked, check the given values
        /// If these are valid, start to create the note board
        /// Otherwise, mark the wrong field as red
        /// </summary>
        private void btnAccept_Click(object sender, EventArgs e)
        {
            DialogResult = DialogResult.None;
            Color RED = Color.FromArgb(255, 192, 192);

            DateTime[] periods = new DateTime[3];
            //Check the validity of the given dates
            //Store the text boxes into an array called textboxs
            TextBox[] textboxes = new TextBox[3] {
                StartPeriod1, StartPeriod2, EndHY
            };

            bool allRight = true;

            foreach (TextBox tbx in textboxes)
            {
                tbx.BackColor = Color.White;
                try
                {
                    periods[Array.IndexOf(textboxes, tbx)] = DateTime.ParseExact(tbx.Text, "dd-MM-yyyy", DEUTSCHCULT);
                    if (DateTimeCalcUtils.GetWeekday(periods[Array.IndexOf(textboxes, tbx)]) == "Sa" ||
                        DateTimeCalcUtils.GetWeekday(periods[Array.IndexOf(textboxes, tbx)]) == "So")
                    {
                        throw new FormatException("The dates could not be on the weekends");
                    }
                }
                catch (FormatException)
                {
                    allRight      = false;
                    tbx.BackColor = RED;
                }

                catch (Exception err)
                {
                    Console.WriteLine("Error in \'FormForGeneratingSheet2.cs\'");
                    Console.WriteLine($"Generic Exception Handler: {err}");
                    throw;
                }
            }

            if (allRight)
            {
                for (int i = 0; i < 2; i++)
                {
                    try
                    {
                        //Test if the dates do not fit or the periods are too short
                        DateTimeCalcUtils.BusinessDaysUntil(periods[i], periods[i + 1].AddDays(-17));
                    }
                    catch (ArgumentException)
                    {
                        allRight = false;
                        textboxes[i + 1].BackColor = RED;
                    }
                }
            }

            if (allRight)
            {
                this.DialogResult = DialogResult.Yes;
                this.Hide();
                if (CreateBoard(periods))
                {
                    MessageBox.Show("Ein leerer Bemerkungsbogen wurde erfolgreich generiert.\r\nAbschnitts: " +
                                    $"{periods[0]:dd-MM-yyyy} ~ {periods[1]:dd-MM-yyyy} ~ {periods[2]:dd-MM-yyyy}",
                                    "Erfolg", MessageBoxButtons.OK, MessageBoxIcon.Information);
                }
                this.Close();
            }
        }