Exemplo n.º 1
0
 public static List<ChartData> CreateCompanyList2()
 {
     List<ChartData> company2 = new List<ChartData>();
     company2.Add(new ChartData() { Mounth = "January", Money = 80 });
     company2.Add(new ChartData() { Mounth = "February", Money = 160 });
     company2.Add(new ChartData() { Mounth = "March", Money = 130 });
     return company2;
 }
Exemplo n.º 2
0
 public static List<ChartData> CreateCompanyList1()
 {
     List<ChartData> company1 = new List<ChartData>();
     company1.Add(new ChartData() { Mounth = "January", Money = 100 });
     company1.Add(new ChartData() { Mounth = "February", Money = 120 });
     company1.Add(new ChartData() { Mounth = "March", Money = 140 });
     return company1;
 }
Exemplo n.º 3
0
        private void Terminos_y_resultado_Load(object sender, EventArgs e)
        {
            float result = 0;
            int contador = 0;

            List<int> fin = new List<int>();
            for (int i = 0; i < cats.Count; i++)
            {

                if (i > 0)
                {
                    if (cats.ElementAt(i).Contains("--"))
                    {
                        contador++;
                    }
                    else
                    {
                        fin.Add(contador);
                        contador = 0;
                    }
                    if (i == cats.Count - 1)
                        fin.Add(contador);

                }
            }

            result = 0;
            int pos = 0;
            int parainsertar = 0;
            for (int i = 0; i < fin.Count; i++)
            {
                for (int j = 0; j < fin.ElementAt(i); j++)
                {
                    result += results.ElementAt(pos + j);
                }
                results.Insert(parainsertar, result);
                result = 0;
                if (pos == 0)
                    pos += fin.ElementAt(i) + 1;
                else
                    pos += fin.ElementAt(i);
                parainsertar += fin.ElementAt(i) + 1;

            }

            Resultadofinal.Text = indice.ToString();
            Idesempeño.Text = calif.ToString();
            richTextBox1.Font = new Font(richTextBox1.Font.FontFamily, 16);
            for (int i = 0; i < cats.Count; i++)
                richTextBox1.Text += cats.ElementAt(i) + ": " + results.ElementAt(i).ToString() + "\n";
        }
Exemplo n.º 4
0
        public virtual List<CostDetail> GetRelatedImplantCostDetail(string codProductPartTask, IQueryable<Cost> costs)
        {
            List<CostDetail> lst = new List<CostDetail>();

            var x = CreatorImplantCostDetail();

            x.ComputedBy = this;
            x.ProductPart = this.ProductPart;

            //devo pescare il costo e associarlo al dettaglio
            if (x.CodCost == null)
            {
                var xxxx = costs.ToList();

                var cost = costs.Where(pp => pp.CodProductPartImplantTask == codProductPartTask).FirstOrDefault();
                //da non usare MAIIII                    x.TaskCost = cost;
                x.CodCost = cost.CodCost;
                x.CodCostDetail = cost.CodCost;

                x.CostDetailCostCodeRigen();
            }

            //GUID
            x.Guid = this.Guid;
            this.Computes.Add(x);
            lst.Add(x);

            return lst;
        }
        public ActionResult Index()
        {
            string category = "Computers";
            var useperiods = db.UsePeriods
                .Where(up => up.EndDate == null || up.EndDate >= DateTime.Now)
                .Where(up => up.Asset is Computer)
                .OrderBy(up => up.AssetId)
                .Select(up => new { AssetId = up.AssetId, Name = up.UserAccount.Name,
                    Function = up.Function, SerialNumber = up.Asset.SerialNumber })
                .ToList()
                ;

            List<AssetSelectListItem> list2 = new List<AssetSelectListItem>();
            foreach (var item in useperiods)
            {
                AssetSelectListItem asli = new AssetSelectListItem();
                asli.CompoundId = category.Substring(0, 1) + item.AssetId.ToString();
                asli.Identifier = asli.CompoundId + " - ";
                if (string.IsNullOrEmpty(item.Name))
                {
                    if (string.IsNullOrEmpty(item.Function))
                    {
                        asli.Identifier += item.SerialNumber;
                    }
                    else { asli.Identifier += item.Function; }
                }
                else { asli.Identifier += item.Name; }
                list2.Add(asli);
            }

            ViewBag.CompoundId = new SelectList(list2, "CompoundId", "Identifier");
            return View(new RepairInfo());
        }
Exemplo n.º 6
0
 public Csapatok( string versenyAzonosito ) {
     csapatok = new List<Csapat>( );
     foreach( var versenyeredmenyek in Model.Data.Data.Eredmenyek._versenyEredmenyek.Where( eredmeny => eredmeny.VersenyAzonosito.Equals( versenyAzonosito ) ) ) {
         foreach( var csapatazonosito in versenyeredmenyek.Eredmenyek._eredmenyek.OrderBy( eredmeny => eredmeny.Csapat ).GroupBy( eredmeny => eredmeny.Csapat ).Select( grouping => grouping.Key ) ) {
             csapatok.Add( new Csapat {
                 Azonosito = csapatazonosito,
                 InduloAdatok = new InduloAdatok( versenyAzonosito, csapatazonosito )
             } );
         }
     }
 }
Exemplo n.º 7
0
        /// <summary>
        /// 从中XML读取物理图信息
        /// </summary>
        /// <returns> List</returns>
        public List<PhysicalDiagramInfo> GetPDInfo()
        {
            try
            {
                List<PhysicalDiagramInfo> PDList = new List<PhysicalDiagramInfo>();
                DocX doc = InitDocX();
                if (mTables == null)
                {
                    mTables = GetTableInfo();
                }
                PhysicalDiagramInfo pdInfo = new PhysicalDiagramInfo();
                string pid = System.Guid.NewGuid().ToString();
                pdInfo.Id = pid;
                pdInfo.Name = "所有数据";
                PDList.Add(pdInfo);

                PhysicalDiagramInfo pd = new PhysicalDiagramInfo();
                string pid1 = System.Guid.NewGuid().ToString();
                pd.Id = pid1;
                pd.Name = "数据表";
                pd.PhyParentId = pid;
                PDList.Add(pd);

                foreach (TableInfo t in mTables)
                {
                    pd = new PhysicalDiagramInfo();
                    pd.Id = System.Guid.NewGuid().ToString();
                    pd.Name = t.Code;
                    pd.IfEnd = true;
                    pd.PhyParentId = pid1;
                    PDList.Add(pd);

                }
                return PDList;
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
Exemplo n.º 8
0
        public static void Flatten(this XElement e, XName name, List<XElement> flat)
        {
            // Add this element (without its children) to the flat list.
            XElement clone = CloneElement(e);
            clone.Elements().Remove();

            // Filter elements using XName.
            if (clone.Name == name)
                flat.Add(clone);

            // Process the children.
            if (e.HasElements)
                foreach (XElement elem in e.Elements(name)) // Filter elements using XName
                    elem.Flatten(name, flat);
        }
        private static void parseFile(DocX file)
        {
            string initiator = file.CustomProperties.Where(x => x.Value.Name == "ФИО инициатора").First().Value.Value.ToString();
              string phone = file.CustomProperties.Where(x => x.Value.Name == "Телефон инициатора").First().Value.Value.ToString();
              string date = file.CustomProperties.Where(x => x.Value.Name == "Текущая дата").First().Value.Value.ToString();
              string bankroll = file.CustomProperties.Where(x => x.Value.Name == "Средства").First().Value.Value.ToString();
              string department = file.CustomProperties.Where(x => x.Value.Name == "Р*Подразделение...*Наименование").First().Value.Value.ToString();
              string content = file.CustomProperties.Where(x => x.Value.Name == "Аннотация").First().Value.Value.ToString();
              string financing = file.CustomProperties.Where(x => x.Value.Name == "Финансирование").First().Value.Value.ToString();

            List<item> items = new List<item>();
              var equipmentTable = file.Tables[0];
            for (int i = 1; i < equipmentTable.Rows.Count; i++)
            {
              items.Add(manageNotesHandler.createDirItem(equipmentTable.Rows[i].Cells[0].Paragraphs.First().Text, Convert.ToInt32(equipmentTable.Rows[i].Cells[1].Paragraphs.First().Text), equipmentTable.Rows[i].Cells[2].Paragraphs.First().Text));
            }
            manageNotesHandler.addDirNote(content, department, initiator, phone, date, bankroll, financing, items);
        }
        protected override void RenderSectionText(string text)
        {
            StringBuilder builder = new StringBuilder();

            string[] lines = text.Split('\n');

            foreach (string line in lines)
            {
                if (line.StartsWith("-"))
                {
                    break;
                }
                else
                {
                    builder.AppendLine(line);
                }
            }

            List<ProsAndCons> prosAndConsList = new List<ProsAndCons>();

            for (int i = 0; i < lines.Length; i++)
            {
                string line = lines[i];

                if (line.StartsWith("- "))
                {
                    ProsAndCons prosAndCons = new ProsAndCons();

                    prosAndCons.Title = line.TrimStart("- ".ToCharArray());

                    prosAndCons.Pros = FindPros(i, lines).ToList();

                    prosAndCons.Cons = FindCons(i, lines).ToList();

                    prosAndConsList.Add(prosAndCons);
                }
            }

            RenderParagraph(builder.ToString(), _formatting.SectionText);

            RenderProsAndCons(prosAndConsList);
        }
Exemplo n.º 11
0
        public override List<ProductPartTask> GetInitalizedPartTask()
        {
            var tsksInPart = new List<ProductPartTask>();

            ProductPartTask pt;

            String[] codTypeOfTasks = { "STAMPAMORBIDO" };

            foreach (var item in codTypeOfTasks)
            {
                pt = new ProductPartTask();
                //default selection
                pt.OptionTypeOfTask = SystemTaskList.FirstOrDefault(x => x.CodTypeOfTask == item).OptionTypeOfTasks.FirstOrDefault(y => y.CodOptionTypeOfTask == item + "_NO");
                pt.CodOptionTypeOfTask = pt.OptionTypeOfTask.CodOptionTypeOfTask;
                pt.Hidden = true;
                tsksInPart.Add(pt);
            }

            return tsksInPart;
        }
Exemplo n.º 12
0
        public string[] ValidateBookmarks(params string[] bookmarkNames)
        {
            var headers = new[] {Document.Headers.first, Document.Headers.even, Document.Headers.odd}.Where(h => h != null).ToList();
            var footers = new[] {Document.Footers.first, Document.Footers.even, Document.Footers.odd}.Where(f => f != null).ToList();

            var nonMatching = new List<string>();
            foreach (var bookmarkName in bookmarkNames)
            {
                if (headers.SelectMany(h => h.Paragraphs).Any(p => p.ValidateBookmark(bookmarkName))) return new string[0];
                if (footers.SelectMany(h => h.Paragraphs).Any(p => p.ValidateBookmark(bookmarkName))) return new string[0];
                if (Paragraphs.Any(p => p.ValidateBookmark(bookmarkName))) return new string[0];
                nonMatching.Add(bookmarkName);
            }

            return nonMatching.ToArray();
        }
        public ActionResult dropdown_for_courses(int? symposium_id)
        {
            if (System.Web.HttpContext.Current.User.Identity.IsAuthenticated == true)
            {
                if (symposium_id == null)
                {
                    var symposiums = db.Symposiums.ToList();
                    int i = 0;
                    int count = 0;
                    foreach (var item in symposiums)
                    {

                        count = count + item.Courses.Count();
                    }
                    Course[] found_courses = new Course[db.Courses.Count()];
                    found_courses[0] = db.Courses.First();
                    int ix = 0;
                    var all_courses = db.Courses.ToList();
                    List<Course> list = new List<Course>();
                    foreach (var item in all_courses)
                    {
                        if (list.Where(x => x.courseNumber == item.courseNumber).FirstOrDefault() == null)
                        {
                            list.Add(item);
                            ix++;
                        }
                    }

                       ViewBag.CourseNames = db.Courses.Select(x=> x.courseName).ToArray();

                        ViewBag.CourseNumbers = db.Courses.Select(x => x.courseName);

                    ViewBag.Courses = list;
                    ViewBag.Course_Count = db.Courses.ToList().Count();
                }
                else
                {
                    Symposium found_symposium = db.Symposiums.Find(symposium_id);
                    Project[] projects = found_symposium.Projects.Distinct().ToArray();
                    int array_length = projects.Count();
                    int[] course_ids = new int[array_length];
                    for (int i = 0; i < projects.Count(); i++)
                    {
                        course_ids[i] = projects[i].courseID;
                    }

                    Course[] found_courses = new Course[projects.Count()];

                    for (int i = 0; i < projects.Count(); i++)
                    {

                        found_courses[i] = db.Courses.Find(projects[i].courseID);
                    }
                    found_courses = found_courses.Distinct().ToArray();

                    ViewBag.Course_Count = found_courses.Count();
                    ViewBag.Courses = found_courses;
                }
                return View();
            }
            else
            {
                return RedirectToAction("desktop_vote", "Projects");
            }
        }
Exemplo n.º 14
0
 /// <summary> 
 /// Set Table column width by prescribing percent 
 /// </summary> 
 /// <param name="widthsPercentage">column width % list</param> 
 /// <param name="totalWidth">Total table width. Will be calculated if null sent.</param>
 public void SetWidthsPercentage(float[] widthsPercentage, float? totalWidth)
 {
     if (totalWidth == null) totalWidth = this.Document.PageWidth - this.Document.MarginLeft - this.Document.MarginRight; // calculate total table width
     List<float> widths = new List<float>(widthsPercentage.Length); // empty list, will hold actual width
     widthsPercentage.ToList().ForEach(pWidth => { widths.Add((pWidth * totalWidth.Value / 100) * (96 / 72)); }); // convert percentage to actual width for all values in array
     SetWidths(widths.ToArray()); // set actual column width
 }
Exemplo n.º 15
0
        /// <summary>
        /// Insert a row into this table.
        /// </summary>
        /// <example>
        /// <code>
        /// // Load a document.
        /// using (DocX document = DocX.Load(@"C:\Example\Test.docx"))
        /// {
        ///     // Get the first table in this document.
        ///     Table table = document.Tables[0];
        ///        
        ///     // Insert a new row at index 1 in this table.
        ///     Row row = table.InsertRow(1);
        ///
        ///     // Loop through each cell in this new row.
        ///     foreach (Cell c in row.Cells)
        ///     {
        ///         // Set the text of each new cell to "Hello".
        ///         c.Paragraphs[0].InsertText("Hello", false);
        ///     }
        ///
        ///     // Save the document to a new file.
        ///     document.SaveAs(@"C:\Example\Test2.docx");
        /// }// Release this document from memory.
        /// </code>
        /// </example>
        /// <param name="index">Index to insert row at.</param>
        /// <returns>A new Row</returns>
        public Row InsertRow(int index)
        {
            if (index < 0 || index > RowCount)
                throw new IndexOutOfRangeException();

            List<XElement> content = new List<XElement>();
            for (int i = 0; i < ColumnCount; i++)
            {
                var w = 2310d;
                if (ColumnWidthsValue != null && ColumnWidthsValue.Length > i)
                    w = ColumnWidthsValue[i] * 15;
                XElement cell = HelperFunctions.CreateTableCell(w);
                content.Add(cell);
            }

            return InsertRow(content, index);
        }
Exemplo n.º 16
0
        internal void GetParagraphsRecursive(XElement Xml, ref int index, ref List<Paragraph> paragraphs)
        {
            // sdtContent are for PageNumbers inside Headers or Footers, don't go any deeper.
            //if (Xml.Name.LocalName == "sdtContent")
            //    return;

            if (Xml.Name.LocalName == "p")
            {
                paragraphs.Add(new Paragraph(Document, Xml, index));

                index += HelperFunctions.GetText(Xml).Length;
            }

            else
            {
                if (Xml.HasElements)
                    foreach (XElement e in Xml.Elements())
                        GetParagraphsRecursive(e, ref index, ref paragraphs);
            }
        }
Exemplo n.º 17
0
        //public Picture InsertPicture(Picture picture)
        //{
        //    Picture newPicture = picture;
        //    newPicture.i = new XElement(picture.i);
        //    xml.Add(newPicture.i);
        //    pictures.Add(newPicture);
        //    return newPicture;
        //}
        // <summary>
        // Insert a Picture at the end of this paragraph.
        // </summary>
        // <param name="description">A string to describe this Picture.</param>
        // <param name="imageID">The unique id that identifies the Image this Picture represents.</param>
        // <param name="name">The name of this image.</param>
        // <returns>A Picture.</returns>
        // <example>
        // <code>
        // // Create a document using a relative filename.
        // using (DocX document = DocX.Create(@"Test.docx"))
        // {
        //     // Add a new Paragraph to this document.
        //     Paragraph p = document.InsertParagraph("Here is Picture 1", false);
        //
        //     // Add an Image to this document.
        //     Novacode.Image img = document.AddImage(@"Image.jpg");
        //
        //     // Insert pic at the end of Paragraph p.
        //     Picture pic = p.InsertPicture(img.Id, "Photo 31415", "A pie I baked.");
        //
        //     // Rotate the Picture clockwise by 30 degrees.
        //     pic.Rotation = 30;
        //
        //     // Resize the Picture.
        //     pic.Width = 400;
        //     pic.Height = 300;
        //
        //     // Set the shape of this Picture to be a cube.
        //     pic.SetPictureShape(BasicShapes.cube);
        //
        //     // Flip the Picture Horizontally.
        //     pic.FlipHorizontal = true;
        //
        //     // Save all changes made to this document.
        //     document.Save();
        // }// Release this document from memory.
        // </code>
        // </example>
        // Removed to simplify the API.
        //public Picture InsertPicture(string imageID, string name, string description)
        //{
        //    Picture p = CreatePicture(Document, imageID, name, description);
        //    Xml.Add(p.Xml);
        //    return p;
        //}
        // Removed because it confusses the API.
        //public Picture InsertPicture(string imageID)
        //{
        //    return InsertPicture(imageID, string.Empty, string.Empty);
        //}
        //public Picture InsertPicture(int index, Picture picture)
        //{
        //    Picture p = picture;
        //    p.i = new XElement(picture.i);
        //    Run run = GetFirstRunEffectedByEdit(index);
        //    if (run == null)
        //        xml.Add(p.i);
        //    else
        //    {
        //        // Split this run at the point you want to insert
        //        XElement[] splitRun = Run.SplitRun(run, index);
        //        // Replace the origional run
        //        run.Xml.ReplaceWith
        //        (
        //            splitRun[0],
        //            p.i,
        //            splitRun[1]
        //        );
        //    }
        //    // Rebuild the run lookup for this paragraph
        //    runLookup.Clear();
        //    BuildRunLookup(xml);
        //    DocX.RenumberIDs(document);
        //    return p;
        //}
        // <summary>
        // Insert a Picture into this Paragraph at a specified index.
        // </summary>
        // <param name="description">A string to describe this Picture.</param>
        // <param name="imageID">The unique id that identifies the Image this Picture represents.</param>
        // <param name="name">The name of this image.</param>
        // <param name="index">The index to insert this Picture at.</param>
        // <returns>A Picture.</returns>
        // <example>
        // <code>
        // // Create a document using a relative filename.
        // using (DocX document = DocX.Create(@"Test.docx"))
        // {
        //     // Add a new Paragraph to this document.
        //     Paragraph p = document.InsertParagraph("Here is Picture 1", false);
        //
        //     // Add an Image to this document.
        //     Novacode.Image img = document.AddImage(@"Image.jpg");
        //
        //     // Insert pic at the start of Paragraph p.
        //     Picture pic = p.InsertPicture(0, img.Id, "Photo 31415", "A pie I baked.");
        //
        //     // Rotate the Picture clockwise by 30 degrees.
        //     pic.Rotation = 30;
        //
        //     // Resize the Picture.
        //     pic.Width = 400;
        //     pic.Height = 300;
        //
        //     // Set the shape of this Picture to be a cube.
        //     pic.SetPictureShape(BasicShapes.cube);
        //
        //     // Flip the Picture Horizontally.
        //     pic.FlipHorizontal = true;
        //
        //     // Save all changes made to this document.
        //     document.Save();
        // }// Release this document from memory.
        // </code>
        // </example>
        // Removed to simplify API.
        //public Picture InsertPicture(int index, string imageID, string name, string description)
        //{
        //    Picture picture = CreatePicture(Document, imageID, name, description);
        //    Run run = GetFirstRunEffectedByEdit(index);
        //    if (run == null)
        //        Xml.Add(picture.Xml);
        //    else
        //    {
        //        // Split this run at the point you want to insert
        //        XElement[] splitRun = Run.SplitRun(run, index);
        //        // Replace the origional run
        //        run.Xml.ReplaceWith
        //        (
        //            splitRun[0],
        //            picture.Xml,
        //            splitRun[1]
        //        );
        //    }
        //    HelperFunctions.RenumberIDs(Document);
        //    return picture;
        //}
        /// <summary>
        /// Create a new Picture.
        /// </summary>
        /// <param name="document"></param>
        /// <param name="id">A unique id that identifies an Image embedded in this document.</param>
        /// <param name="name">The name of this Picture.</param>
        /// <param name="descr">The description of this Picture.</param>
        internal static Picture CreatePicture(DocX document, string id, string name, string descr)
        {
            PackagePart part = document.package.GetPart(document.mainPart.GetRelationship(id).TargetUri);

            int newDocPrId = 1;
            List<string> existingIds = new List<string>();
            foreach (var bookmarkId in document.Xml.Descendants(XName.Get("bookmarkStart", DocX.w.NamespaceName)))
            {
                var idAtt = bookmarkId.Attributes().FirstOrDefault(x => x.Name.LocalName == "id");
                if (idAtt != null)
                    existingIds.Add(idAtt.Value);
            }

            while (existingIds.Contains(newDocPrId.ToString()))
                newDocPrId++;

            int cx, cy;

            using (System.Drawing.Image img = System.Drawing.Image.FromStream(part.GetStream()))
            {
                cx = img.Width * 9526;
                cy = img.Height * 9526;
            }

            XElement e = new XElement(DocX.w + "drawing");

            XElement xml = XElement.Parse
                 (string.Format(@"<w:r xmlns:w=""http://schemas.openxmlformats.org/wordprocessingml/2006/main"">
                    <w:drawing xmlns = ""http://schemas.openxmlformats.org/wordprocessingml/2006/main"">
                        <wp:inline distT=""0"" distB=""0"" distL=""0"" distR=""0"" xmlns:wp=""http://schemas.openxmlformats.org/drawingml/2006/wordprocessingDrawing"">
                            <wp:extent cx=""{0}"" cy=""{1}"" />
                            <wp:effectExtent l=""0"" t=""0"" r=""0"" b=""0"" />
                            <wp:docPr id=""{5}"" name=""{3}"" descr=""{4}"" />
                            <wp:cNvGraphicFramePr>
                                <a:graphicFrameLocks xmlns:a=""http://schemas.openxmlformats.org/drawingml/2006/main"" noChangeAspect=""1"" />
                            </wp:cNvGraphicFramePr>
                            <a:graphic xmlns:a=""http://schemas.openxmlformats.org/drawingml/2006/main"">
                                <a:graphicData uri=""http://schemas.openxmlformats.org/drawingml/2006/picture"">
                                    <pic:pic xmlns:pic=""http://schemas.openxmlformats.org/drawingml/2006/picture"">
                                        <pic:nvPicPr>
                                        <pic:cNvPr id=""0"" name=""{3}"" />
                                            <pic:cNvPicPr />
                                        </pic:nvPicPr>
                                        <pic:blipFill>
                                            <a:blip r:embed=""{2}"" xmlns:r=""http://schemas.openxmlformats.org/officeDocument/2006/relationships""/>
                                            <a:stretch>
                                                <a:fillRect />
                                            </a:stretch>
                                        </pic:blipFill>
                                        <pic:spPr>
                                            <a:xfrm>
                                                <a:off x=""0"" y=""0"" />
                                                <a:ext cx=""{0}"" cy=""{1}"" />
                                            </a:xfrm>
                                            <a:prstGeom prst=""rect"">
                                                <a:avLst />
                                            </a:prstGeom>
                                        </pic:spPr>
                                    </pic:pic>
                                </a:graphicData>
                            </a:graphic>
                        </wp:inline>
                    </w:drawing></w:r>
                    ", cx, cy, id, name, descr, newDocPrId.ToString()));

            return new Picture(document, xml, new Image(document, document.mainPart.GetRelationship(id)));
        }
Exemplo n.º 18
0
        public List<Section> GetSections()
        {

            var allParas = Paragraphs;

            var parasInASection = new List<Paragraph>();
            var sections = new List<Section>();

            foreach (var para in allParas)
            {

                var sectionInPara = para.Xml.Descendants().FirstOrDefault(s => s.Name.LocalName == "sectPr");

                if (sectionInPara == null)
                {
                    parasInASection.Add(para);
                }
                else
                {
                    parasInASection.Add(para);
                    var section = new Section(Document, sectionInPara) { SectionParagraphs = parasInASection };
                    sections.Add(section);
                    parasInASection = new List<Paragraph>();
                }

            }

            XElement body = mainDoc.Root.Element(XName.Get("body", DocX.w.NamespaceName));
            XElement baseSectionXml = body.Element(XName.Get("sectPr", DocX.w.NamespaceName));
            var baseSection = new Section(Document, baseSectionXml) { SectionParagraphs = parasInASection };
            sections.Add(baseSection);

            return sections;
        }
Exemplo n.º 19
0
        /// <summary>
        /// Insert a row into this table.
        /// </summary>
        /// <example>
        /// <code>
        /// // Load a document.
        /// using (DocX document = DocX.Load(@"C:\Example\Test.docx"))
        /// {
        ///     // Get the first table in this document.
        ///     Table table = document.Tables[0];
        ///        
        ///     // Insert a new row at index 1 in this table.
        ///     Row row = table.InsertRow(1);
        ///
        ///     // Loop through each cell in this new row.
        ///     foreach (Cell c in row.Cells)
        ///     {
        ///         // Set the text of each new cell to "Hello".
        ///         c.Paragraphs[0].InsertText("Hello", false);
        ///     }
        ///
        ///     // Save the document to a new file.
        ///     document.SaveAs(@"C:\Example\Test2.docx");
        /// }// Release this document from memory.
        /// </code>
        /// </example>
        /// <param name="index">Index to insert row at.</param>
        /// <returns>A new Row</returns>
        public Row InsertRow(int index)
        {
            if (index < 0 || index > RowCount)
                throw new IndexOutOfRangeException();

            List<XElement> content = new List<XElement>();
            for (int i = 0; i < ColumnCount; i++)
            {
                XElement cell = HelperFunctions.CreateTableCell();
                content.Add(cell);
            }

            return InsertRow(content, index);
        }
Exemplo n.º 20
0
        private DocumentationComment ParseRunbook(string content)
        {
            var lines = content.Split('\n');
            var comment = new List<string>();
            bool inComment = false;

            foreach (var line in lines)
            {
                if (line.StartsWith("<#"))
                    inComment = true;

                if (inComment)
                {
                    //comment += line + "\n";
                    comment.Add(line.TrimEnd());
                }

                if (line.EndsWith("#>"))
                    inComment = false;

                if (!inComment)
                    break;
            }

            if (comment.Count > 0)
            {
                var documentation = ParseComment(comment);

                return documentation;
            }

            return null;
        }
Exemplo n.º 21
0
        /// <summary>
        /// Sets the column width for the given index.
        /// </summary>
        /// <param name="index">Column index</param>
        /// <param name="width">Colum width</param>
        public void SetColumnWidth(Int32 index, Double width)
        {
            List<Double> widths = ColumnWidths;
            if (widths == null || index > widths.Count - 1)
            {
                if (Rows.Count == 0) throw new Exception("There is at least one row required to detect the existing columns.");
                // use width of last row cells
                // may not work for merged cell!
                widths = new List<Double>();
                foreach (Cell c in Rows[Rows.Count - 1].Cells)
                {
                    widths.Add(c.Width);
                }
            }

            // check if index is matching table columns
            if (index > widths.Count - 1) throw new Exception("The index is greather than the available table columns.");

            // get the table grid props
            XElement grid = Xml.Element(XName.Get("tblGrid", DocX.w.NamespaceName));
            // if null; append a new grid below tblPr
            if (grid == null)
            {
                XElement tblPr = GetOrCreate_tblPr();
                tblPr.AddAfterSelf(new XElement(XName.Get("tblGrid", DocX.w.NamespaceName)));
                grid = Xml.Element(XName.Get("tblGrid", DocX.w.NamespaceName));
            }

            // remove all existing values
            grid?.RemoveAll();

            // append new column widths
            Int32 i = 0;
            foreach (var w in widths)
            {
                double value = w;
                if (i == index) value = width;
                var gridCol = new XElement(XName.Get("gridCol", DocX.w.NamespaceName),
                    new XAttribute(XName.Get("w", DocX.w.NamespaceName), value));
                grid?.Add(gridCol);
                i += 1;
            }

            // remove cell widths
            foreach (Row r in Rows)
                foreach (Cell c in r.Cells)
                    c.Width = -1;

            // set fitting to fixed; this will add/set additional table properties
            this.AutoFit = AutoFit.Fixed;
        }
Exemplo n.º 22
0
        private void GenerateVisio(string drawingOutputPath)
        {
            var pageWidth = 16.53543307086614;
            var pageHeight = 11.69291338582677;
            var left = 0.1;
            var processWidth = 1.5;
            var processHeight = 1.0;
            var processPaddingHorizontal = 0.4;
            var processPaddingVertical = 1.4;
            var maxProcessCountPerRow = 10;
            var activityPos = 1;
            var activityYPos = 0;
            var addToHorizontal = 1;
            var shapes = new List<VisioShape>();

            // Clean up the template and remove the existing pages
            var templateXml = XDocument.Load("DrawingTemplate.vdx");
            //VisioTemplate.CleanUpTemplate(templateXml);

            var template = new VisioTemplate(templateXml.ToString());
            var document = new VisioDrawing(template);
            document.DocumentProperties.Creator = "Automation Studio";
            document.DocumentProperties.TimeCreated = DateTime.Now;

            // Configure the page
            var runbooks = _backendContext.Runbooks;
            var runbooksList = new List<RunbookModelProxy>();
            foreach (var runbook in runbooks)
                runbooksList.Add((runbook.Tag as RunbookModelProxy));

            var languageContext = new LanguageContext();

            foreach (var runbook in runbooks)
            {
                if (!(runbook.Tag as RunbookModelProxy).PublishedRunbookVersionID.HasValue)
                    continue;

                var runbookProxy = (runbook.Tag as RunbookModelProxy);
                _statusManager.SetText("Generating visio drawing for " + runbookProxy.RunbookName);
                var viewModel = (runbook.Tag as RunbookModelProxy).GetViewModel<RunbookViewModel>();

                var page = ConfigureVisioPage(viewModel.Runbook.RunbookName, pageWidth, pageHeight);
                document.Pages.Add(page);

                var publishedContent = viewModel.GetContent(RunbookType.Published, true);
                languageContext.Parse(publishedContent);

                var references = languageContext.GetReferences(runbooksList);

                if (references.Count == 0)
                    continue;

                var totalRows = (double)(runbooksList.Count / maxProcessCountPerRow);

                if (runbooksList.Count <= maxProcessCountPerRow)
                    totalRows = 2.0;

                var y = (pageHeight / totalRows) + (totalRows * ((processHeight + processPaddingVertical)) / totalRows);
                var x = (pageWidth / (maxProcessCountPerRow - 1)) + ((processWidth + processPaddingHorizontal) * activityPos);
                var ay = y - ((processHeight + processPaddingVertical) * activityYPos);

                // Add the current runbook as the start activity
                var processId = document.GetMasterMetaData("Process").ID;
                var visioActivity = new VisioShape(processId, x, ay, processWidth, processHeight);

                var charFormat = new VisioAutomation.VDX.Sections.Char();
                charFormat.Size.Result = 12;

                visioActivity.CharFormats = new List<VisioAutomation.VDX.Sections.Char>();
                visioActivity.CharFormats.Add(charFormat);
                visioActivity.Text.Add(runbookProxy.RunbookName);

                page.Shapes.Add(visioActivity);
                shapes.Add(visioActivity);

                activityPos += addToHorizontal;

                foreach (var reference in references)
                {
                    x = (pageWidth / (maxProcessCountPerRow - 1)) + ((processWidth + processPaddingHorizontal) * activityPos);
                    ay = y - ((processHeight + processPaddingVertical) * activityYPos);

                    // Add all references
                    processId = document.GetMasterMetaData("Process").ID;
                    visioActivity = new VisioShape(processId, x, ay, processWidth, processHeight);

                    visioActivity.CharFormats = new List<VisioAutomation.VDX.Sections.Char>();
                    visioActivity.CharFormats.Add(charFormat);
                    visioActivity.Text.Add(reference.RunbookName);

                    page.Shapes.Add(visioActivity);
                    shapes.Add(visioActivity);

                    /*//if (!String.IsNullOrEmpty(activity.Description))
                    {
                        int shapeID = visioActivity.ID;

                        var callOut = new VisioShape(26, x + 0.3, ay + 1.0);
                        //callOut.Text.Add(activity.Description);
                        callOut.Geom = new VisioAutomation.VDX.Sections.Geom();

                        page.Shapes.Add(callOut);
                    }*/

                    activityPos++;

                    if (activityPos >= maxProcessCountPerRow)
                    {
                        addToHorizontal = -1;
                        activityPos += addToHorizontal;
                        activityYPos++;
                    }
                    else
                    {
                        addToHorizontal = 1;
                        activityPos += addToHorizontal;
                        activityYPos++;
                    }
                }

                // Add connectors between the activities
                for (int i = 0; i < shapes.Count; i++)
                {
                    // We only add connectors up until the latest process object
                    if ((i + 1) >= shapes.Count)
                        break;

                    VisioShape a1 = shapes[i];
                    VisioShape a2 = shapes[i + 1];

                    var line = VisioShape.CreateDynamicConnector(document);
                    line.XForm1D.EndY.Result = 0;

                    line.Line = new VisioLine();
                    line.Line.EndArrow.Result = 2;

                    page.Shapes.Add(line);
                    page.ConnectShapesViaConnector(line, a1, a2);
                }

                shapes.Clear();
                languageContext.ClearCache();
            }

            document.Save(drawingOutputPath);
        }
Exemplo n.º 23
0
        /// <summary>
        /// Remove this Paragraph from the document.
        /// </summary>
        /// <param name="trackChanges">Should this remove be tracked as a change?</param>
        /// <example>
        /// Remove a Paragraph from a document and track it as a change.
        /// <code>
        /// // Create a document using a relative filename.
        /// using (DocX document = DocX.Load(@"C:\Example\Test.docx"))
        /// {
        ///     // Create and Insert a new Paragraph into this document.
        ///     Paragraph p = document.InsertParagraph("Hello", false);
        ///
        ///     // Remove the Paragraph and track this as a change.
        ///     p.Remove(true);
        ///
        ///     // Save all changes made to this document.
        ///     document.Save();
        /// }// Release this document from memory.
        /// </code>
        /// </example>
        public void Remove(bool trackChanges)
        {
            if (trackChanges)
            {
                DateTime now = DateTime.Now.ToUniversalTime();

                List<XElement> elements = Xml.Elements().ToList();
                List<XElement> temp = new List<XElement>();
                for (int i = 0; i < elements.Count(); i++)
                {
                    XElement e = elements[i];

                    if (e.Name.LocalName != "del")
                    {
                        temp.Add(e);
                        e.Remove();
                    }

                    else
                    {
                        if (temp.Count() > 0)
                        {
                            e.AddBeforeSelf(CreateEdit(EditType.del, now, temp.Elements()));
                            temp.Clear();
                        }
                    }
                }

                if (temp.Count() > 0)
                    Xml.Add(CreateEdit(EditType.del, now, temp));
            }

            else
            {
                // If this is the only Paragraph in the Cell then we cannot remove it.
                if (Xml.Parent.Name.LocalName == "tc" && Xml.Parent.Elements(XName.Get("p", DocX.w.NamespaceName)).Count() == 1)
                    Xml.Value = string.Empty;

                else
                {
                    // Remove this paragraph from the document
                    Xml.Remove();
                    Xml = null;
                }
            }
        }
Exemplo n.º 24
0
        internal static void GetFormattedTextRecursive(XElement Xml, ref List<FormattedText> alist)
        {
            FormattedText ft = ToFormattedText(Xml);
            FormattedText last = null;

            if (ft != null)
            {
                if (alist.Count() > 0)
                    last = alist.Last();

                if (last != null && last.CompareTo(ft) == 0)
                {
                    // Update text of last entry.
                    last.text += ft.text;
                }
                else
                {
                    if (last != null)
                        ft.index = last.index + last.text.Length;

                    alist.Add(ft);
                }
            }

            if (Xml.HasElements)
                foreach (XElement e in Xml.Elements())
                    GetFormattedTextRecursive(e, ref alist);
        }
        public ActionResult projects_scoped_with_courses(int id)
        {
            Symposium symposium = db.Symposiums.Find(id);
            ViewBag.Symposium = symposium;
            var courses = db.Courses.Where(c => c.symposiumID == id);
            ViewBag.Courses = courses;
            List<Project> list = new List<Project>();
            foreach (var item in courses)
            {
             foreach(var project in item.Projects){
                    list.Add(project);
                }

            }
            ViewBag.Course_Projects = list.OrderByDescending(p => p.total_votes);
            return View(symposium);
        }
Exemplo n.º 26
0
        internal static List<XElement> FormatInput(string text, XElement rPr)
        {
            List<XElement> newRuns = new List<XElement>();
            XElement tabRun = new XElement(DocX.w + "tab");
            XElement breakRun = new XElement(DocX.w + "br");

            StringBuilder sb = new StringBuilder();

            if (string.IsNullOrEmpty(text))
            {
                return newRuns; //I dont wanna get an exception if text == null, so just return empy list
            }

            foreach (char c in text)
            {
                switch (c)
                {
                    case '\t':
                        if (sb.Length > 0)
                        {
                            XElement t = new XElement(DocX.w + "t", sb.ToString());
                            Novacode.Text.PreserveSpace(t);
                            newRuns.Add(new XElement(DocX.w + "r", rPr, t));
                            sb = new StringBuilder();
                        }
                        newRuns.Add(new XElement(DocX.w + "r", rPr, tabRun));
                        break;
                    case '\n':
                        if (sb.Length > 0)
                        {
                            XElement t = new XElement(DocX.w + "t", sb.ToString());
                            Novacode.Text.PreserveSpace(t);
                            newRuns.Add(new XElement(DocX.w + "r", rPr, t));
                            sb = new StringBuilder();
                        }
                        newRuns.Add(new XElement(DocX.w + "r", rPr, breakRun));
                        break;

                    default:
                        sb.Append(c);
                        break;
                }
            }

            if (sb.Length > 0)
            {
                XElement t = new XElement(DocX.w + "t", sb.ToString());
                Novacode.Text.PreserveSpace(t);
                newRuns.Add(new XElement(DocX.w + "r", rPr, t));
            }

            return newRuns;
        }
Exemplo n.º 27
0
        public List InsertList(int index, List list)
        {
            Paragraph p = HelperFunctions.GetFirstParagraphEffectedByInsert(Document, index);

            XElement[] split = HelperFunctions.SplitParagraph(p, index - p.startIndex);
            var elements = new List<XElement> { split[0] };
            elements.AddRange(list.Items.Select(i => new XElement(i.Xml)));
            elements.Add(split[1]);
            p.Xml.ReplaceWith(elements.ToArray());

            return list;
        }
Exemplo n.º 28
0
        private void DetailForm_Load(object sender, EventArgs e)
        {
            // Save button will be disable
            bt_Save.Enabled = false;
            // Initialize database connection
            cmd.Connection = connection;
            /*
             * Put Term data to Form
             */
            cmd.CommandText = string.Format(@"SELECT * FROM TermTable WHERE TermID = {0}", m_Term);
            try
            {
                connection.Open();
                reader = cmd.ExecuteReader();
                if (reader.HasRows)
                    while (reader.Read())
                    {
                        num_Term.Text = reader[1].ToString();
                        lb_YearValue.Text = reader[2].ToString();
                    }
                connection.Close();
            }
            catch (Exception ex)
            {
                MessageBox.Show(@"Message6: " + ex.Message.ToString(), @"Error");
                connection.Close();
            }
            // Read Grade table and add grade to cb_ABRSMgrade
            try
            {
                cmd.CommandText = string.Format(@"SELECT * FROM ABRSMGrade WHERE ABRSMID = {0}",
                    m_studentInfo.m_ABRSMGradeID);
                connection.Open();
                reader = cmd.ExecuteReader();
                if (reader.HasRows)
                {
                    while (reader.Read())
                    {
                        var tempt = new ComboBoxItem(reader[0], reader[1].ToString());
                        cb_ABRSMgrade.Items.Add(tempt);
                    }
                    connection.Close();
                    cb_ABRSMgrade.SelectedIndex = 0;
                }
                connection.Close();
            }
            catch (Exception ex)
            {
                MessageBox.Show(@"Message3: " + ex.Message.ToString(), @"Error");
                connection.Close();
            }
            //Add student name to cb_StudentName

            cb_StudentName.Items.Add(new ComboBoxItem(m_studentInfo.m_studentID, m_studentInfo.m_studentName));
            cb_StudentName.SelectedIndex = 0;
            tb_Instrument.Text = m_studentInfo.m_Instrument.ToString();
            tb_TeacherName.Text = m_studentInfo.m_TeacherName.ToString();
            tb_SchoolName.Text = m_studentInfo.m_EnsemblesPartition.ToString();
            // Read Grade table and add to List for using many time
            var lt_Grade = new List<ComboBoxItem>();
            try
            {
                cmd.CommandText = @"SELECT * FROM Grade";
                connection.Open();
                reader = cmd.ExecuteReader();
                if (reader.HasRows)
                {
                    while (reader.Read())
                    {
                        lt_Grade.Add(new ComboBoxItem(reader[0], reader[1].ToString(), reader[2]));
                    }
                }
                connection.Close();
            }
            catch (Exception ex)
            {
                MessageBox.Show("Message: " + ex.Message.ToString(), "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                connection.Close();
            }
            // Add Grade to cb_MusicalLiteracy, cb_Listening, cb_Performing, cb_Musicianship, cb_Technique, cb_Effort
            foreach (var str_grade in lt_Grade)
            {
                cb_MusicalLiteracy.Items.Add(str_grade);
                cb_Performing.Items.Add(str_grade);
                cb_Listening.Items.Add(str_grade);
                cb_Musicianship.Items.Add(str_grade);
                cb_Technique.Items.Add(str_grade);
                cb_Effort.Items.Add(str_grade);
            }
            // Read Grade from database and put cb_MusicalLiteracy, cb_Listening, cb_Performing, cb_Musicianship, cb_Technique, cb_Effort to correct database
            try
            {
                cmd.CommandText =
                    string.Format(
                        @"SELECT GradeTable.ValueID, GradeTable.GradeID, Grade.GradeName, Grade.PercentGrade FROM GradeTable, Grade WHERE GradeTable.StudentID = {0} AND GradeTable.Term = {1} AND GradeTable.GradeID = Grade.GradeID AND GradeTable.ABRSMID = {2}",
                        m_studentInfo.m_studentID, m_Term, m_studentInfo.m_ABRSMGradeID);
                connection.Open();
                reader = cmd.ExecuteReader();
                if (reader.HasRows)
                {
                    while (reader.Read())
                    {
                        /*TODO: Need to enhanced add to commbo box. Do not hard code value ID for cb_Musicalship, etc...*/
                        switch ((int) reader[0])
                        {
                            case 1:
                            {
                                cb_MusicalLiteracy.SelectedIndex =
                                    cb_MusicalLiteracy.FindStringExact(reader[2].ToString());
                                break;
                            }
                            case 2:
                            {
                                cb_Listening.SelectedIndex = cb_Listening.FindStringExact(reader[2].ToString());
                                break;
                            }
                            case 3:
                            {
                                cb_Technique.SelectedIndex = cb_Technique.FindStringExact(reader[2].ToString());
                                break;
                            }
                            case 4:
                            {
                                cb_Musicianship.SelectedIndex = cb_Musicianship.FindStringExact(reader[2].ToString());
                                break;
                            }
                            case 5:
                            {
                                cb_Performing.SelectedIndex = cb_Performing.FindStringExact(reader[2].ToString());
                                break;
                            }
                            case 6:
                            {
                                cb_Effort.SelectedIndex = cb_Effort.FindStringExact(reader[2].ToString());
                                break;
                            }
                            default:
                                break;
                        }
                    }
                }
                connection.Close();
            }
            catch (Exception ex)
            {
                MessageBox.Show(@"Message: " + ex.Message.ToString(), @"Error", MessageBoxButtons.OK,
                    MessageBoxIcon.Error);
                connection.Close();
                throw;
            }
            // Load command of Target and put to tb_Target
            cmd.CommandText =
                string.Format(
                    @"SELECT Target FROM DatabaseTable WHERE StudentID = {0} AND Term = {1} AND ABRSMID = {2}",
                    m_studentInfo.m_studentID, m_Term, m_studentInfo.m_ABRSMGradeID);
            try
            {
                connection.Open();
                reader = cmd.ExecuteReader();
                if (reader.HasRows)
                {
                    while (reader.Read())
                    {
                        tb_TargetComment.Text = reader[0].ToString();
                    }
                }
                connection.Close();
            }
            catch (Exception exception)
            {
                MessageBox.Show(@"Message: " + exception.Message.ToString(), @"Error", MessageBoxButtons.OK,
                    MessageBoxIcon.Error);
                connection.Close();
                throw;
            }
        }
Exemplo n.º 29
0
        internal void GetParagraphsRecursive(XElement Xml, ref int index, ref List<Paragraph> paragraphs, bool deepSearch=false)
        {
            // sdtContent are for PageNumbers inside Headers or Footers, don't go any deeper.
            //if (Xml.Name.LocalName == "sdtContent")
            //    return;
            var keepSearching = true;
            if (Xml.Name.LocalName == "p")
            {
                paragraphs.Add(new Paragraph(Document, Xml, index));

                index += HelperFunctions.GetText(Xml).Length;
                if (!deepSearch)
                    keepSearching = false;
            }
            if (keepSearching && Xml.HasElements)
            {
                foreach (XElement e in Xml.Elements())
                {
                    GetParagraphsRecursive(e, ref index, ref paragraphs, deepSearch);
                }
            }
        }
Exemplo n.º 30
0
        /*
         * - Add source into GradeTable with data (StudentID, ValueID, GradeID, Term, ABRSMID)
         * - Update Database Table base on StudentID, Term, and ABRSMGrade (StudentID, ABRSMID, Term, Target, SummaryGrade)
         * TODO: Need to check Term info before add to database --- PhuongLuong done
         */
        private bool saveSource()
        {
            if (cb_ABRSMgrade.SelectedItem != null && cb_StudentName.SelectedItem != null &&
                cb_Listening.SelectedItem != null && cb_Effort.SelectedItem != null &&
                cb_MusicalLiteracy.SelectedItem != null && cb_Musicianship.SelectedItem != null
                && cb_Performing.SelectedItem != null && cb_Technique.SelectedItem != null &&
                !tb_TargetComment.Text.IsEmpty())
            {
                var listValueGrade = new List<ValueGrade>();
                /*
                 * Read data and put to list ValueGrade
                 */
                /*TODO need to remove hard code Value ID here and check condition for add*/
                listValueGrade.Add(new ValueGrade(1, (int) (cb_MusicalLiteracy.SelectedItem as ComboBoxItem).MValue));
                listValueGrade.Add(new ValueGrade(2, (int) (cb_Listening.SelectedItem as ComboBoxItem).MValue));
                listValueGrade.Add(new ValueGrade(3, (int) (cb_Technique.SelectedItem as ComboBoxItem).MValue));
                listValueGrade.Add(new ValueGrade(4, (int) (cb_Musicianship.SelectedItem as ComboBoxItem).MValue));
                listValueGrade.Add(new ValueGrade(5, (int) (cb_Performing.SelectedItem as ComboBoxItem).MValue));
                listValueGrade.Add(new ValueGrade(6, (int) (cb_Effort.SelectedItem as ComboBoxItem).MValue));
                /*
                 * - Update database to Grade Table
                 * TODO: Need to lookat in database for existing student database and update this, not insert
                */
                foreach (var valueGrade in listValueGrade)
                {
                    //cmd.CommandText =
                    //    string.Format(
                    //        @"INSERT INTO GradeTable (StudentID, ValueID, GradeID, Term, ABRSMID) VALUES ({0}, {1}, {2}, {3}, {4})",
                    //        (cb_StudentName.SelectedItem as ComboBoxItem).m_Value, valueGrade.m_ValueID,
                    //        valueGrade.m_GradeID, num_Term.Text, (cb_ABRSMgrade.SelectedItem as ComboBoxItem).m_Value);
                    cmd.CommandText =
                        string.Format(
                            @"UPDATE GradeTable SET GradeID = {0} WHERE StudentID = {1} AND ValueID = {2} AND Term = {3} AND ABRSMID = {4}",
                            valueGrade.m_GradeID, ((ComboBoxItem) cb_StudentName.SelectedItem).MValue,
                            valueGrade.m_ValueID, m_Term,
                            ((ComboBoxItem) cb_ABRSMgrade.SelectedItem).MValue);
                    try
                    {
                        connection.Open();
                        if (cmd.ExecuteNonQuery() == 0)
                        {
                            connection.Close();
                            return false;
                        }
                        connection.Close();
                    }
                    catch (Exception exception)
                    {
                        connection.Close();
                        MessageBox.Show(@"Cannot add to Grade Table. Message: " + exception.ToString(), @"Error",
                            MessageBoxButtons.OK,
                            MessageBoxIcon.Error);
                        return false;
                        throw;
                    }
                }
                var summaryGrade = calculateSummary();

                /* Update database to DatabaseTable*/
                //cmd.CommandText =
                //    string.Format(
                //        @"INSERT INTO DatabaseTable (StudentID, ABRSMID, Term, Target, SummaryGrade) VALUES ({0}, {1}, {2}, '{3}', {4})",
                //        (cb_StudentName.SelectedItem as ComboBoxItem).m_Value,
                //        (cb_ABRSMgrade.SelectedItem as ComboBoxItem).m_Value, num_Term.Text, tb_TargetComment.Text,
                //        summaryGrade);
                //cmd.CommandText =
                //    string.Format(
                //        @"UPDATE DatabaseTable SET Target = '{0}', SummaryGrade = {1} WHERE StudentID = {2} AND Term = {3} AND ABRSMID = {4}",
                //        tb_TargetComment.Text, summaryGrade, ((ComboBoxItem) cb_StudentName.SelectedItem).MValue, m_Term,
                //        ((ComboBoxItem) cb_ABRSMgrade.SelectedItem).MValue);
                cmd.CommandText = "UPDATE DatabaseTable SET Target = @Target, SummaryGrade = @SummaryGrade WHERE StudentID = @StudentID AND Term = @Term AND ABRSMID = @ABRSMID";
                cmd.Parameters.AddWithValue("@StudentID", ((ComboBoxItem)cb_StudentName.SelectedItem).MValue);
                cmd.Parameters.AddWithValue("@ABRSMID", ((ComboBoxItem)cb_ABRSMgrade.SelectedItem).MValue);
                cmd.Parameters.AddWithValue("@Term", m_Term);
                cmd.Parameters.AddWithValue("@Target", tb_TargetComment.Text);
                cmd.Parameters.AddWithValue("@SummaryGrade", summaryGrade);
                try
                {
                    connection.Open();
                    if (cmd.ExecuteNonQuery() == 0)
                    {
                        connection.Close();
                        return false;
                    }
                    connection.Close();
                }
                catch (Exception exception)
                {
                    connection.Close();
                    MessageBox.Show(@"Cannot add to DatabaseTable. Message:" + exception.ToString(), @"Error",
                        MessageBoxButtons.OK,
                        MessageBoxIcon.Error);
                    return false;
                    throw;
                }
                // Add source info to database
                //cmd.CommandText = string.Format(@"INSERT INTO GradeTable (StudentID, ValueID, GradeID, ABRSMID) VALUES ({0}, {1}, {2}, {3})", (cb_StudentName.SelectedItem as ComboBoxItem).m_Value, )
            }
            else
            {
                MessageBox.Show(@"Please check the input. Some thing is missing.", @"Error", MessageBoxButtons.OK,
                    MessageBoxIcon.Error);
                return false;
            }
            return true;
        }