public ActionResult SystemHistoryTextual()
        {
            // Get the user
            var user = userRepository.GetUserByUsername(User.Identity.Name);
            //var allPolls = new List<Poll>();
            var allPolls = user.ManagedPolls;
            var unique = new List<Poll>();
            foreach (Poll poll in allPolls) { if (!unique.Contains(poll)) unique.Add(poll); }
            allPolls = unique;

            IDictionary<Poll, IList<User>> creatorList = new Dictionary<Poll, IList<User>>();
            IDictionary<Poll, int> attendanceList = new Dictionary<Poll, int>();
            foreach (var poll in allPolls)
            {
                // Get poll creators
                creatorList.Add(poll, userRepository.GetCreatorsOfPoll(poll));

                // Get poll attendance
                int attendance = 0;
                foreach (var participant in poll.participants)
                {
                    if (participant.attended)
                    {
                        attendance += 1;
                    }
                }
                attendanceList.Add(poll, attendance);
            }

            var viewModel = new PollReportViewModel(allPolls, creatorList, attendanceList);
            return View(viewModel);
        }
        private string GetJobFormHTMLForStoreNonVisit(JobFormNew JobFormNew)
        {
            try
            {
                List<string> parentIDList = new List<string>();
                List<string> controlIDList = new List<string>();
                int imagecount = 0;
                List<WorkersInMotion.Model.ViewModel.JobFormValueDetails> FormValues = new List<WorkersInMotion.Model.ViewModel.JobFormValueDetails>();
                StringBuilder sbJobForm = new StringBuilder();
                // sbJobForm.Append("<div style='page-break-before:always'>&nbsp;</div>");
                sbJobForm.Append("<html>");
                sbJobForm.Append("<head><script type='text/javascript' src='http://maps.googleapis.com/maps/api/js?sensor=false'></script></head>");
                sbJobForm.Append("<body>");
                #region Generate JobForm
                if (JobFormNew.JobFormHeading != null)
                {
                    sbJobForm.Append("<div id='" + JobFormNew.JobFormHeading.JobGUID + "' name='" + JobFormNew.JobFormHeading.JobGUID + "'>");
                    sbJobForm.Append("<div align='center'>");
                    sbJobForm.Append("<table style='width:100%' align='center' cellpadding='0'>");
                    sbJobForm.Append("<tr>");
                    sbJobForm.Append("<td colspan='2' style='font-size:18px;font-family:verdana;font-weight:bold;text-align:center;'>" + JobFormNew.JobFormHeading.JobName + "&nbsp;Report</td>");
                    sbJobForm.Append("</tr>");
                    sbJobForm.Append("<tr>");
                    sbJobForm.Append("<td colspan='2' style='font-size:18px;font-family:verdana;font-weight:bold;text-align:center;'>&nbsp;</td>");
                    sbJobForm.Append("</tr>");
                    sbJobForm.Append("<tr>");
                    sbJobForm.Append("<td style='font-size:12px;font-family:verdana;font-weight:bold;text-align:left;width: 65%;' align='left'>Client Name :<span style='font-weight:normal;'>" + JobFormNew.JobFormHeading.PlaceName + "</span> </td>");
                    sbJobForm.Append("<td style='font-size:12px;font-family:verdana;font-weight:bold;text-align:left;width: 35%;' align='left'>Client ID :<span style='font-weight:normal;'>" + JobFormNew.JobFormHeading.PlaceID + "</span> </td>");
                    sbJobForm.Append("</tr>");
                    sbJobForm.Append("<tr>");
                    sbJobForm.Append("<td style='font-size:12px;font-family:verdana;font-weight:bold;text-align:left;width: 65%;' align='left'>Store ID :<span style='font-weight:normal;'>" + JobFormNew.JobFormHeading.MarketID + "</span> </td>");
                    sbJobForm.Append("<td style='font-size:12px;font-family:verdana;font-weight:bold;text-align:left;width: 35%;' align='left'>Check-In :<span style='font-weight:normal;'>" + JobFormNew.JobFormHeading.CheckInTime + "</span> </td>");
                    sbJobForm.Append("</tr>");
                    sbJobForm.Append("<tr>");
                    sbJobForm.Append("<td style='font-size:12px;font-family:verdana;font-weight:bold;text-align:left;width: 65%;' align='left'>Store Name : <span style='font-weight:normal;'>" + JobFormNew.JobFormHeading.MarketName + "</span></td>");
                    sbJobForm.Append("<td style='font-size:12px;font-family:verdana;font-weight:bold;text-align:left;width: 35%;' align='left'>Check-Out : <span style='font-weight:normal;'>" + JobFormNew.JobFormHeading.CheckOutTime + "</span></td>");
                    sbJobForm.Append("</tr>");
                    sbJobForm.Append("<tr>");
                    sbJobForm.Append("<td style='font-size:12px;font-family:verdana;font-weight:bold;text-align:left;' align='left'>Address :<span style='font-weight:normal;'>" + JobFormNew.JobFormHeading.MarketAddress + "</span> </td>");
                    sbJobForm.Append("</tr>");
                    sbJobForm.Append("</table>");
                    sbJobForm.Append("</div>");
                    sbJobForm.Append("<a name='" + JobFormNew.JobFormHeading.JobGUID + "' style='text-decoration: none;'>&nbsp;</a>");
                    sbJobForm.Append("<hr style='boder:1px solid black;width:100%'/>");
                }
                else
                {
                    sbJobForm.Append("<div>");
                }

                if (JobFormNew != null && JobFormNew.FormValues != null)
                {
                    foreach (var item1 in JobFormNew.FormValues)
                    {
                        if ((item1.ControlType == WorkersInMotion.Model.ViewModel.ControlType.CONTROL_TYPE_EDIT && item1.parentID == -100) || (item1.ControlType == WorkersInMotion.Model.ViewModel.ControlType.CONTROL_TYPE_EDIT && item1.controlParentLabel == "Email") || (item1.ControlType == WorkersInMotion.Model.ViewModel.ControlType.CONTROL_TYPE_EDIT && item1.controlParentLabel == "Phone"))
                        {
                            if (!controlIDList.Contains(item1.ControlID.ToString()))
                            {
                                //if (!parentIDList.Contains(item1.parentID.ToString()))
                                //{
                                //    parentIDList.Add(item1.parentID.ToString());
                                sbJobForm.Append("<div style='padding-top:5px;padding-bottom:5px'>");
                                sbJobForm.Append("<p style='color:black;font-weight:bold;font-size:12px;margin-left:1px;'>" + item1.controlParentLabel + "</p>");
                                sbJobForm.Append("<table style='width:100%' align='left' cellpadding='0'>");
                                sbJobForm.Append("<tr>");
                                foreach (var items in JobFormNew.FormValues.Where(one => (one.parentID == item1.parentID && one.ControlType == WorkersInMotion.Model.ViewModel.ControlType.CONTROL_TYPE_EDIT) || ((one.ControlLabel == "Email" || one.ControlLabel == "Phone") && one.ControlType == WorkersInMotion.Model.ViewModel.ControlType.CONTROL_TYPE_EDIT)))
                                {
                                    if (!controlIDList.Contains(items.ControlID.ToString()))
                                    {

                                        controlIDList.Add(items.ControlID.ToString());

                                        sbJobForm.Append("<td align='left' style='width:25%'>");
                                        sbJobForm.Append("<span style='padding-left:0px;line-height:20px;font-size:10px;'>" + items.Value + "</span>");
                                        // sbJobForm.Append("<p>&nbsp;</p>");
                                        sbJobForm.Append("</td>");

                                    }
                                }
                                sbJobForm.Append("</tr>");
                                sbJobForm.Append("</table>");
                                sbJobForm.Append("</div>");

                            }
                        }
                        //}
                        //else if ((item1.ControlType == WorkersInMotion.Model.ViewModel.ControlType.CONTROL_TYPE_EDIT && item1.parentID == -101) || (item1.ControlType == WorkersInMotion.Model.ViewModel.ControlType.CONTROL_TYPE_EDIT && item1.controlParentLabel == "Date"))
                        //{
                        //    if (!parentIDList.Contains(item1.parentID.ToString()))
                        //    {
                        //        parentIDList.Add(item1.parentID.ToString());
                        //        sbJobForm.Append("<div style='padding-top:5px;padding-bottom:5px'>");
                        //        sbJobForm.Append("<p style='color:black;font-weight:bold;font-size:12px;margin-left:1px;'>" + item1.controlParentLabel + "</p>");
                        //        sbJobForm.Append("<table style='width:100%' align='left' cellpadding='0'>");
                        //        sbJobForm.Append("<tr>");
                        //        sbJobForm.Append("<td align='left'>");
                        //        foreach (var items in JobFormNew.FormValues.Where(one => (one.parentID == item1.parentID && ((one.ControlType == WorkersInMotion.Model.ViewModel.ControlType.CONTROL_TYPE_EDIT && item1.parentID == -101) || (one.ControlType == WorkersInMotion.Model.ViewModel.ControlType.CONTROL_TYPE_EDIT && one.ControlLabel == "Date")))))
                        //        {
                        //            if (!controlIDList.Contains(items.ControlID.ToString()))
                        //            {

                        //                controlIDList.Add(items.ControlID.ToString());
                        //                if (items.ControlLabel == "Year" || items.ControlLabel == "Day")
                        //                {
                        //                    sbJobForm.Append(" <span style='padding-left:0px;line-height:20px;font-size:10px;'>-" + items.Value + "</span>");
                        //                }
                        //                else
                        //                {
                        //                    sbJobForm.Append(" <span style='padding-left:10px;line-height:20px;font-size:10px;'>" + items.Value + "</span>");
                        //                }


                        //            }
                        //        }
                        //        sbJobForm.Append("</td>");
                        //        sbJobForm.Append("</tr>");
                        //        sbJobForm.Append("</table>");
                        //        sbJobForm.Append("</div>");

                        //    }
                        //}

                        else if ((item1.ControlType == WorkersInMotion.Model.ViewModel.ControlType.CONTROL_TYPE_EDIT) && (item1.ControlLabel == "Region"))
                        {
                            if (!controlIDList.Contains(item1.ControlID.ToString()))
                            {
                                sbJobForm.Append("<div style='padding-top:5px;padding-bottom:5px'>");
                                sbJobForm.Append("<table style='width:100%' align='left' cellpadding='0'>");
                                sbJobForm.Append("<tr>");
                                foreach (var items in JobFormNew.FormValues.Where(one => ((one.ControlLabel == "Region" || one.ControlLabel == "Market") && one.ControlType == WorkersInMotion.Model.ViewModel.ControlType.CONTROL_TYPE_EDIT)))
                                {
                                    if (!controlIDList.Contains(items.ControlID.ToString()))
                                    {

                                        controlIDList.Add(items.ControlID.ToString());

                                        sbJobForm.Append("<td align='left' style='width:25%'>");
                                        sbJobForm.Append("<label style='color:black;font-weight:bold;font-size:12px;'>" + items.ControlLabel + "</label><br></br>");
                                        sbJobForm.Append("<span style='padding-left:0px;line-height:20px;font-size:10px;'>" + items.Value + "</span>");
                                        // sbJobForm.Append("<p style='padding:0px 10px 0px 10px; border-bottom: 1px solid gray; border-left: 1px solid gray; border-right: 1px solid gray; line-height: 2px;'>&nbsp;</p>");
                                        sbJobForm.Append("</td>");

                                    }
                                }
                                sbJobForm.Append("</tr>");
                                sbJobForm.Append("</table>");
                                sbJobForm.Append("</div>");
                            }

                        }
                        else if ((item1.ControlType == WorkersInMotion.Model.ViewModel.ControlType.CONTROL_TYPE_EDIT) && (item1.ControlLabel == "Store Number # *" || item1.ControlLabel == "Store Address"))
                        {
                            if (!controlIDList.Contains(item1.ControlID.ToString()))
                            {
                                sbJobForm.Append("<div style='padding-top:5px;padding-bottom:5px'>");
                                sbJobForm.Append("<table style='width:100%' align='left' cellpadding='0'>");
                                sbJobForm.Append("<tr>");
                                foreach (var items in JobFormNew.FormValues.Where(one => ((one.ControlLabel == "Store Number # *" || one.ControlLabel == "Store Address") && one.ControlType == WorkersInMotion.Model.ViewModel.ControlType.CONTROL_TYPE_EDIT)))
                                {
                                    if (!controlIDList.Contains(items.ControlID.ToString()))
                                    {

                                        controlIDList.Add(items.ControlID.ToString());

                                        sbJobForm.Append("<td align='left' style='width:25%'>");
                                        sbJobForm.Append("<label style='color:black;font-weight:bold;font-size:12px;'>" + items.ControlLabel + "</label><br></br>");
                                        sbJobForm.Append("<span style='padding-left:0px;line-height:20px;font-size:10px;'>" + items.Value + "</span>");
                                        //sbJobForm.Append("<p>&nbsp;</p>");
                                        sbJobForm.Append("</td>");

                                    }
                                }
                                sbJobForm.Append("</tr>");
                                sbJobForm.Append("</table>");
                                sbJobForm.Append("</div>");
                            }

                        }
                        else if ((item1.ControlType == WorkersInMotion.Model.ViewModel.ControlType.CONTROL_TYPE_EDIT && item1.parentID < 0))
                        {
                            if (!controlIDList.Contains(item1.ControlID.ToString()))
                            {
                                sbJobForm.Append("<div style='padding-top:5px;padding-bottom:5px'>");
                                sbJobForm.Append("<p style='color:black;font-weight:bold;font-size:12px;margin-left:1px;'>" + item1.controlParentLabel + "</p>");
                                sbJobForm.Append("<table style='width:100%' align='left' cellpadding='0'>");
                                sbJobForm.Append("<tr>");
                                //sbJobForm.Append("<td align='left'>");
                                //sbJobForm.Append("</td>");
                                foreach (var items in JobFormNew.FormValues.Where(one => (one.parentID == item1.parentID && one.ControlType == WorkersInMotion.Model.ViewModel.ControlType.CONTROL_TYPE_EDIT)))
                                {
                                    if (!controlIDList.Contains(items.ControlID.ToString()))
                                    {

                                        if (!controlIDList.Contains(items.ControlID.ToString()))
                                        {

                                            controlIDList.Add(items.ControlID.ToString());
                                            sbJobForm.Append("<td align='left' style='width:25%'>");
                                            sbJobForm.Append("<span style='padding-left:0px;line-height:20px;font-size:10px;'>" + items.Value + "</span>");
                                            sbJobForm.Append("</td>");

                                        }

                                    }
                                }

                                sbJobForm.Append("</tr>");
                                sbJobForm.Append("</table>");
                                sbJobForm.Append("</div>");

                            }
                        }
                        else if ((item1.ControlType == WorkersInMotion.Model.ViewModel.ControlType.CONTROL_TYPE_EDIT || item1.ControlType == WorkersInMotion.Model.ViewModel.ControlType.CONTROL_TYPE_DROP_DOWN) && item1.controlParentLabel != "Email" && item1.controlParentLabel != "Phone")
                        {
                            if (!controlIDList.Contains(item1.ControlID.ToString()))
                            {
                                controlIDList.Add(item1.ControlID.ToString());
                                if (!string.IsNullOrEmpty(item1.ControlLabel) && !string.IsNullOrEmpty(item1.Value))
                                {
                                    sbJobForm.Append("<div style='padding-top:5px;padding-bottom:5px'>");
                                    sbJobForm.Append("<label style='color:black;font-weight:bold;font-size:12px;'>&nbsp;" + item1.ControlLabel + "</label>");
                                    sbJobForm.Append("<table style='width:100%' align='left'>");
                                    sbJobForm.Append("<tr>");
                                    sbJobForm.Append("<td align='left' style='width:40%'>");
                                    sbJobForm.Append("<span style='padding-left:0px;line-height:20px;font-size:10px;'>" + item1.Value + "</span>");
                                    // sbJobForm.Append("<p style='padding:0px 10px 0px 10px; border-bottom: 1px solid gray; border-left: 1px solid gray; border-right: 1px solid gray; line-height: 2px;'>&nbsp;</p>");
                                    sbJobForm.Append("</td>");
                                    sbJobForm.Append("</tr>");
                                    sbJobForm.Append("</table>");
                                    sbJobForm.Append("</div>");
                                }
                            }
                        }

                        else if (item1.ControlType == WorkersInMotion.Model.ViewModel.ControlType.CONTROL_TYPE_CHECKBOX)
                        {
                            if (!controlIDList.Contains(item1.ControlID.ToString()))
                            {
                                sbJobForm.Append("<div style='padding-top:5px;padding-bottom:5px'>");
                                sbJobForm.Append("<label style='color:black;font-weight:bold;font-size:12px;'>" + item1.controlParentLabel + "</label>");

                                FormValues = JobFormNew.FormValues.Where(one => one.parentID == item1.parentID && one.ControlType == WorkersInMotion.Model.ViewModel.ControlType.CONTROL_TYPE_CHECKBOX).ToList();

                                if (FormValues.Count() > 0)
                                {
                                    sbJobForm.Append("<table style='width:100%' align='left'>");
                                    for (int i = 0; i < FormValues.Count; i = i + 3)
                                    {

                                        sbJobForm.Append("<tr>");
                                        for (int j = i; j < i + 3 && j < FormValues.Count; j++)
                                        {
                                            WorkersInMotion.Model.ViewModel.JobFormValueDetails items = (WorkersInMotion.Model.ViewModel.JobFormValueDetails)FormValues[j];
                                            if (!controlIDList.Contains(items.ControlID.ToString()))
                                            {
                                                controlIDList.Add(items.ControlID.ToString());


                                                sbJobForm.Append("<td align='left' style='width:25%'>");
                                                if (items.Value == "true")
                                                {

                                                    sbJobForm.Append("<img src='" + Server.MapPath("~/assets/img/checkbox_yes.png") + "' alt='logo'  width='20px' height='20px' />");
                                                    //sbJobForm.Append("<input type='checkbox' name='checked' id='mychk' value='on'/>");
                                                }
                                                else
                                                {
                                                    //sbJobForm.Append("<img src='http://localhost:4100/assets/img/1403875956_ui-check-box.png' alt='logo'  width='20px' height='20px' />");
                                                    sbJobForm.Append("<img src='" + Server.MapPath("~/assets/img/checkbox_no.png") + "' alt='logo'  width='20px' height='20px' />");
                                                    //sbJobForm.Append("<input type='checkbox' name='checked' id='mychk' value='on'/>");
                                                }
                                                sbJobForm.Append("<span style='color:black;font-size:10px;vertical-align:top'>" + items.ControlLabel + "</span>&nbsp;");
                                                sbJobForm.Append("</td>");

                                            }
                                        }
                                        sbJobForm.Append("</tr>");
                                    }
                                    sbJobForm.Append("</table>");
                                }
                                sbJobForm.Append("</div>");
                            }

                        }
                        else if (item1.ControlType == WorkersInMotion.Model.ViewModel.ControlType.CONTROL_TYPE_MULTITEXT)
                        {
                            if (!controlIDList.Contains(item1.ControlID.ToString()))
                            {
                                controlIDList.Add(item1.ControlID.ToString());
                                sbJobForm.Append("<div style='padding-top:5px;padding-bottom:5px'>");
                                sbJobForm.Append("<table style='width:100%' align='left'>");
                                sbJobForm.Append("<tr>");
                                sbJobForm.Append("<td align='left'>");
                                sbJobForm.Append("<label style='font-size:12px;'>" + item1.ControlLabel + "</label>");

                                sbJobForm.Append("<label>:</label>");

                                sbJobForm.Append("<textarea cols='20' rows='2' style='background-color:#FFFFFD;font-size:10px;'>" + item1.Value + "</textarea>");
                                sbJobForm.Append("</td>");
                                sbJobForm.Append("</tr>");
                                sbJobForm.Append("</table>");
                                sbJobForm.Append("</div>");
                            }
                        }
                        else if (item1.ControlType == WorkersInMotion.Model.ViewModel.ControlType.CONTROL_TYPE_LABEL)
                        {
                            if (!controlIDList.Contains(item1.ControlID.ToString()))
                            {
                                sbJobForm.Append("<div style='padding-top:5px;padding-bottom:5px'>");
                                sbJobForm.Append("<table style='width:100%' align='left'>");
                                sbJobForm.Append("<tr>");
                                sbJobForm.Append("<td align='left'>");
                                sbJobForm.Append("<label style='font-size:12px;'>" + item1.ControlLabel + "</label>");

                                sbJobForm.Append("<label>:</label>");

                                sbJobForm.Append("<label style='font-size:10px;'>&nbsp;&nbsp;" + item1.Value + "</label>&nbsp;");
                                sbJobForm.Append("</td>");
                                sbJobForm.Append("</tr>");
                                sbJobForm.Append("</table>");


                                sbJobForm.Append("</div>");
                            }
                        }
                        else if (item1.ControlType == WorkersInMotion.Model.ViewModel.ControlType.CONTROL_TYPE_RADIO_GROUP)
                        {
                            if (!controlIDList.Contains(item1.ControlID.ToString()))
                            {
                                controlIDList.Add(item1.ControlID.ToString());
                                sbJobForm.Append("<div id='Div' class='leftbar-heading'>");
                                sbJobForm.Append("<label style='color:black;font-weight:bold;border-bottom:10px;'>" + item1.ControlLabel + "</label>");
                                sbJobForm.Append("<table style='width:100%' align='left' cellpadding='5'>");
                                sbJobForm.Append("<tr>");
                                foreach (var items in JobFormNew.FormValues.Where(one => (one.parentID == item1.ControlID && one.ControlType == WorkersInMotion.Model.ViewModel.ControlType.CONTROL_TYPE_RADIO_BUTTON)))
                                {
                                    if (!controlIDList.Contains(items.ControlID.ToString()))
                                    {

                                        controlIDList.Add(items.ControlID.ToString());

                                        sbJobForm.Append("<td align='left' style='width:25%'>");
                                        if (items.Value == "true")
                                        {
                                            sbJobForm.Append("<img src='" + Server.MapPath("~/assets/img/1403876293_radiobutton_yes.png") + "' alt='logo'  width='20px' height='20px' />");
                                            //sbJobForm.Append("<input type='radio' disabled='disabled' checked />");
                                        }
                                        else
                                        {
                                            // sbJobForm.Append("<input type='radio' disabled='disabled' />");
                                            sbJobForm.Append("<img src='" + Server.MapPath("~/assets/img/1403876299_radiobutton_no.png") + "' alt='logo'  width='20px' height='20px' />");
                                        }
                                        sbJobForm.Append("<span style='color:black;border-bottom:10px;;font-size:10px;vertical-align:top;'>" + items.ControlLabel + "</span>&nbsp;");
                                        sbJobForm.Append("</td>");

                                    }
                                }
                                sbJobForm.Append("</tr>");
                                sbJobForm.Append("</table>");
                                sbJobForm.Append("</div>");
                            }
                        }


                        else if (item1.ControlType == WorkersInMotion.Model.ViewModel.ControlType.CONTROL_TYPE_SWITCH)
                        {
                            if (!controlIDList.Contains(item1.ControlID.ToString()))
                            {
                                controlIDList.Add(item1.ControlID.ToString());
                                sbJobForm.Append("<div style='padding-top:5px;padding-bottom:5px'>");
                                sbJobForm.Append("<label style='color:black;font-weight:bold;font-size:12px;'>" + item1.ControlLabel + "</label>");

                                FormValues = JobFormNew.FormValues.Where(one => one.parentID == item1.ControlID && one.ControlType == WorkersInMotion.Model.ViewModel.ControlType.CONTROL_TYPE_RADIO_BUTTON).ToList();

                                if (FormValues.Count() > 0)
                                {
                                    sbJobForm.Append("<table style='width:100%' align='left'>");
                                    for (int i = 0; i < FormValues.Count; i = i + 3)
                                    {

                                        sbJobForm.Append("<tr>");
                                        for (int j = i; j < i + 3 && j < FormValues.Count; j++)
                                        {
                                            WorkersInMotion.Model.ViewModel.JobFormValueDetails items = (WorkersInMotion.Model.ViewModel.JobFormValueDetails)FormValues[j];

                                            if (!controlIDList.Contains(items.ControlID.ToString()))
                                            {
                                                controlIDList.Add(items.ControlID.ToString());

                                                sbJobForm.Append("<td align='left' style='width:25%'>");
                                                if (items.Value == "true")
                                                {
                                                    sbJobForm.Append("<img src='" + Server.MapPath("~/assets/img/1403876293_radiobutton_yes.png") + "' alt='logo'  width='20px' height='20px' />");
                                                    //sbJobForm.Append("<img src='http://localhost:4100/assets/img/1403876293_radiobutton_yes.png' alt='logo'  width='20px' height='20px' />");
                                                    //sbJobForm.Append("<input type='radio' disabled='disabled' checked></input>");
                                                }
                                                else
                                                {
                                                    sbJobForm.Append("<img src='" + Server.MapPath("~/assets/img/1403876299_radiobutton_no.png") + "' alt='logo'  width='20px' height='20px' />");
                                                    //sbJobForm.Append("<img src='http://localhost:4100/assets/img/1403876299_radiobutton_no.png' alt='logo'  width='20px' height='20px' />");
                                                    //sbJobForm.Append("<input type='radio' disabled='disabled'></input>");
                                                }
                                                sbJobForm.Append("<span style='color:black;font-size:10px;vertical-align:top;'>" + items.ControlLabel + "</span>&nbsp;");
                                                sbJobForm.Append("</td>");
                                            }

                                        }
                                        sbJobForm.Append("</tr>");
                                    }
                                    sbJobForm.Append("</table>");
                                }

                                sbJobForm.Append("<div id='Div'>");
                                sbJobForm.Append("<label style='color:black;font-weight:bold;font-size:12px;'>" + item1.controlParentLabel + "</label>");

                                FormValues = JobFormNew.FormValues.Where(one => one.parentID == item1.ControlID && one.ControlType == WorkersInMotion.Model.ViewModel.ControlType.CONTROL_TYPE_IMAGE).ToList();

                                if (FormValues.Count() > 0)
                                {
                                    if (!parentIDList.Contains(item1.ControlID.ToString()))
                                    {
                                        parentIDList.Add(item1.ControlID.ToString());
                                        sbJobForm.Append("<table style='width:100%' align='left'>");
                                        for (int i = 0; i < FormValues.Count; i = i + 3)
                                        {
                                            sbJobForm.Append("<tr>");
                                            for (int j = i; j < i + 3 && j < FormValues.Count; j++)
                                            {
                                                WorkersInMotion.Model.ViewModel.JobFormValueDetails items = (WorkersInMotion.Model.ViewModel.JobFormValueDetails)FormValues[j];
                                                if (!controlIDList.Contains(items.ControlID.ToString()))
                                                {
                                                    controlIDList.Add(items.ControlID.ToString());


                                                    sbJobForm.Append("<td align='left'>");
                                                    if (!string.IsNullOrEmpty(items.ImagePath) && !string.IsNullOrEmpty(items.Value))
                                                    {
                                                        sbJobForm.Append("<div>");
                                                        sbJobForm.Append("<img src='" + items.ImagePath + '/' + items.Value + "' alt='logo'  width='120px' height='120px' />");
                                                        Logger.Debug(items.ImagePath + '/' + items.Value);
                                                        //sbJobForm.Append("<img src='" + items.ImagePath + '/' + items.Value + "' style='width:120px;height:120px;' />");
                                                        sbJobForm.Append("</div>");
                                                    }
                                                    sbJobForm.Append("<span style='color:black;font-size:10px;'>" + items.ControlLabel + "</span>&nbsp;");
                                                    sbJobForm.Append("</td>");

                                                }
                                            }
                                            sbJobForm.Append("</tr>");
                                        }
                                        sbJobForm.Append("</table>");
                                    }
                                }
                                sbJobForm.Append("</div>");

                                sbJobForm.Append("</div>");
                            }
                        }
                        else if (item1.ControlType == WorkersInMotion.Model.ViewModel.ControlType.CONTROL_TYPE_IMAGE)
                        {
                            if (!controlIDList.Contains(item1.ControlID.ToString()))
                            {
                                sbJobForm.Append("<div style='padding-top:5px;padding-bottom:5px'>");
                                sbJobForm.Append("<label style='color:black;font-weight:bold;font-size:12px;'>" + item1.controlParentLabel + "</label>");

                                FormValues = JobFormNew.FormValues.Where(one => one.parentID == item1.parentID && one.ControlType == WorkersInMotion.Model.ViewModel.ControlType.CONTROL_TYPE_IMAGE).ToList();

                                if (FormValues.Count() > 0)
                                {
                                    sbJobForm.Append("<table style='width:100%' align='left'>");
                                    for (int i = 0; i < FormValues.Count; i = i + 3)
                                    {
                                        sbJobForm.Append("<tr>");
                                        for (int j = i; j < i + 3 && j < FormValues.Count; j++)
                                        {
                                            WorkersInMotion.Model.ViewModel.JobFormValueDetails items = (WorkersInMotion.Model.ViewModel.JobFormValueDetails)FormValues[j];
                                            if (!controlIDList.Contains(items.ControlID.ToString()))
                                            {
                                                controlIDList.Add(items.ControlID.ToString());


                                                sbJobForm.Append("<td align='left'>");
                                                if (!string.IsNullOrEmpty(items.ImagePath) && !string.IsNullOrEmpty(items.Value))
                                                {
                                                    sbJobForm.Append("<div>");
                                                    sbJobForm.Append("<img src='" + items.ImagePath + '/' + items.Value + "' alt='logo'  width='120px' height='120px' />");
                                                    Logger.Debug(items.ImagePath + '/' + items.Value);
                                                    //sbJobForm.Append("<img src='" + items.ImagePath + '/' + items.Value + " style='width:120px;height:120px;'/>");
                                                    sbJobForm.Append("</div>");
                                                }
                                                sbJobForm.Append("<span style='color:black;font-size:10px;'>" + items.ControlLabel + "</span>&nbsp;");
                                                sbJobForm.Append("</td>");
                                            }
                                        }
                                        sbJobForm.Append("</tr>");
                                    }
                                    sbJobForm.Append("</table>");
                                }
                                sbJobForm.Append("</div>");
                            }

                        }
                        else if (item1.ControlType == WorkersInMotion.Model.ViewModel.ControlType.CONTROL_TYPE_IMAGE_DESC)
                        {
                            if (!controlIDList.Contains(item1.ControlID.ToString()))
                            {
                                sbJobForm.Append("<div style='padding-top:5px;padding-bottom:5px'>");
                                sbJobForm.Append("<label style='color:black;font-weight:bold;font-size:12px;'>" + item1.controlParentLabel + "</label>");

                                FormValues = JobFormNew.FormValues.Where(one => one.parentID == item1.parentID && one.ControlType == WorkersInMotion.Model.ViewModel.ControlType.CONTROL_TYPE_IMAGE_DESC).ToList();

                                if (FormValues.Count() > 0)
                                {
                                    sbJobForm.Append("<table style='width:100%' align='left'>");
                                    for (int i = 0; i < FormValues.Count; i = i + 3)
                                    {
                                        sbJobForm.Append("<tr>");
                                        for (int j = i; j < i + 3 && j < FormValues.Count; j++)
                                        {
                                            WorkersInMotion.Model.ViewModel.JobFormValueDetails items = (WorkersInMotion.Model.ViewModel.JobFormValueDetails)FormValues[j];
                                            if (!controlIDList.Contains(items.ControlID.ToString()))
                                            {
                                                controlIDList.Add(items.ControlID.ToString());


                                                sbJobForm.Append("<td align='left'>");
                                                if (!string.IsNullOrEmpty(items.ImagePath) && !string.IsNullOrEmpty(items.Value))
                                                {
                                                    sbJobForm.Append("<div>");

                                                    //string base64String = string.Empty;
                                                    //using (var webClient = new WebClient())
                                                    //{
                                                    //    byte[] imageAsByteArray = webClient.DownloadData(items.ImagePath + '/' + items.Value);
                                                    //    base64String = Convert.ToBase64String(imageAsByteArray, 0, imageAsByteArray.Length);
                                                    //}

                                                    //sbJobForm.Append("<img src='data:image/jpeg;base64," + base64String + "' alt='logo'  width='120' height='120' />");


                                                    sbJobForm.Append("<img src='" + items.ImagePath + '/' + items.Value + "' alt='logo'  width='120px' height='120px' />");
                                                    Logger.Debug(items.ImagePath + '/' + items.Value);
                                                    sbJobForm.Append("</div>");
                                                }
                                                foreach (var item in JobFormNew.FormValues.Where(one => one.parentID == items.ControlID && one.ControlType == WorkersInMotion.Model.ViewModel.ControlType.CONTROL_TYPE_EDIT))
                                                {
                                                    if (!controlIDList.Contains(item.ControlID.ToString()))
                                                    {

                                                        controlIDList.Add(item.ControlID.ToString());
                                                        sbJobForm.Append("<span style='color:black;font-size:10px;'>" + item.ControlLabel + "</span>");
                                                    }
                                                }
                                                sbJobForm.Append("&nbsp;");
                                                sbJobForm.Append("</td>");
                                            }
                                        }
                                        sbJobForm.Append("</tr>");
                                    }
                                    sbJobForm.Append("</table>");
                                }
                                sbJobForm.Append("</div>");
                            }

                        }
                        else if (item1.ControlType == WorkersInMotion.Model.ViewModel.ControlType.CONTROL_TYPE_ISSUES_TO_REPORT || item1.ControlType == WorkersInMotion.Model.ViewModel.ControlType.CONTROL_TYPE_OPEN_CHARGEBACKS || item1.ControlType == WorkersInMotion.Model.ViewModel.ControlType.CONTROL_TYPE_UNSOLD_QUOTES)
                        {
                            if (!controlIDList.Contains(item1.ControlID.ToString()))
                            {
                                sbJobForm.Append("<div style='padding-top:5px;padding-bottom:5px'>");
                                sbJobForm.Append("<label style='color:black;font-weight:bold;font-size:12px;'>" + item1.ControlLabel + "</label>");


                                sbJobForm.Append("<div id='div_" + item1.ControlID + "'>");
                                if (JobFormNew.FormValues.Where(one => one.parentID == item1.ControlID).ToList().Count > 0)
                                {
                                    foreach (var items in JobFormNew.FormValues.Where(one => one.parentID == item1.ControlID))
                                    {
                                        if (!controlIDList.Contains(items.ControlID.ToString()))
                                        {
                                            controlIDList.Add(items.ControlID.ToString());
                                            sbJobForm.Append("<table style='width:100%' align='left'>");
                                            sbJobForm.Append("<tr>");
                                            sbJobForm.Append("<td align='left' style='width:100px'>");
                                            if (items.currentValueID > 0)
                                            {
                                                sbJobForm.Append("<span style='color:black;font-weight:bold;font-size:10px;'>" + items.Value + "</span>");
                                            }
                                            else
                                            {
                                                sbJobForm.Append("<span style='color:black;font-size:10px;'>" + items.Value + "</span>");
                                            }
                                            sbJobForm.Append("&nbsp;");
                                            sbJobForm.Append("</td>");
                                            sbJobForm.Append("</tr>");
                                            sbJobForm.Append("</table>");
                                        }
                                    }
                                }
                                else
                                {
                                    //sbJobForm.Append("<table style='width:100%' align='left'>");
                                    //sbJobForm.Append("<tr>");
                                    sbJobForm.Append("<div align='left' style='width:100px;font-size:10px;'>None</div>");
                                    //sbJobForm.Append("<tr>");
                                    //sbJobForm.Append("</table>");
                                }
                                sbJobForm.Append("</div>");
                                sbJobForm.Append("</div>");
                            }
                        }

                    }
                }
                sbJobForm.Append("</div>");

                #endregion
                string marker = string.Empty;
                if (JobFormNew != null && JobFormNew.CoordinateList != null && JobFormNew.CoordinateList.Count > 0)
                {

                    int i = 0;
                    string address = string.Empty;
                    foreach (CoOrdinates items in JobFormNew.CoordinateList)
                    {
                        i++;
                        if (i == JobFormNew.CoordinateList.Count)
                        {
                            if (!string.IsNullOrEmpty(items.EndTime))
                                marker = marker + "markers=size:small%7Ccolor:0xcc0000%7C" + items.Latitude + "," + items.Longitude;
                            else if (!string.IsNullOrEmpty(items.StartTime))
                                marker = marker + "markers=size:mid%7Ccolor:0x33d100%7C" + items.Latitude + "," + items.Longitude;
                            else if (!string.IsNullOrEmpty(items.StoreName))
                                marker = marker + "markers=color:0xff6600%7C" + items.Latitude + "," + items.Longitude;
                        }
                        else
                        {

                            if (!string.IsNullOrEmpty(items.EndTime))
                                marker = marker + "markers=size:small%7Ccolor:0xcc0000%7C" + items.Latitude + "," + items.Longitude + "&";
                            else if (!string.IsNullOrEmpty(items.StartTime))
                                marker = marker + "markers=size:mid%7Ccolor:0x33d100%7C" + items.Latitude + "," + items.Longitude + "&";
                            else if (!string.IsNullOrEmpty(items.StoreName))
                                marker = marker + "markers=color:0xff6600%7C" + items.Latitude + "," + items.Longitude + "&";


                        }
                        if (!string.IsNullOrEmpty(items.City))
                        {
                            address = address + "+" + items.City;
                        }
                        if (!string.IsNullOrEmpty(items.State))
                        {
                            address = address + "+" + items.State;
                        }
                        if (!string.IsNullOrEmpty(items.Country))
                        {
                            address = address + "+" + items.Country;
                        }
                        //markers=color:blue%7Clabel:S%7C40.702147,-74.015794&markers=color:green%7Clabel:G%7C40.711614,-74.012318&markers=color:red%7Clabel:C%7C40.718217,-73.998284

                    }
                    sbJobForm.Append("<div style='page-break-before:always'>");
                    sbJobForm.Append("<img src='http://maps.googleapis.com/maps/api/staticmap?center=" + address + "&zoom=10&size=1000x1000&maptype=roadmap&" + marker + "'></img>");
                    sbJobForm.Append("</div>");
                }

                sbJobForm.Append("</body>");
                sbJobForm.Append("</html>");
                return sbJobForm.ToString();
            }
            catch (Exception ex)
            {
                Logger.Error(ex.Message);
                return "";
            }
        }
        public ActionResult GeneratePDF(string pdfcontent)
        {
            Logger.Debug("Inside Store Visit Controller- GeneratePDF");
            try
            {
                if (Session["OrganizationGUID"] != null)
                {
                    if (!string.IsNullOrEmpty(pdfcontent.ToString()))
                    {
                        Response.ContentType = "application/pdf";

                        Response.Cache.SetCacheability(HttpCacheability.NoCache);

                        StringBuilder pVisit = new StringBuilder();
                        // pVisit.Append("<header>Prabhu</header>");
                        //pVisit.Append("<html>");
                        //pVisit.Append("<head>");
                        //pVisit.Append("<title></title>");
                        //pVisit.Append("</head>");
                        //pVisit.Append("<body>");
                        pVisit.Append("<div>");

                        pVisit.Append("<table style='clear:both;width:100%;border-spacing: 0px;border-color:black;color: black;border-collapse: collapse;font-family: verdana;font-size: 10px;border:1px solid black;' border='1' cellpadding='8'>");
                        pVisit.Append("<thead>");
                        if (pdfcontent == "StoreVisit" && Session["StoreVisit"] != null)
                        {
                            Session["VisitType"] = "Store Visit Report";
                            Response.AddHeader("content-disposition", "attachment;filename=Visits.pdf");
                            pVisit.Append("<tr>");
                            pVisit.Append("<td style='font-weight:bold;font-size:10px;border-color:black;font-family:verdana'>Region</td>");
                            pVisit.Append("<td style='font-weight:bold;font-size:10px;border-color:black;font-family:verdana'>Store ID</td>");
                            pVisit.Append("<td style='font-weight:bold;font-size:10px;border-color:black;font-family:verdana'>Store Name</td>");
                            pVisit.Append("<td style='font-weight:bold;font-size:10px;border-color:black;font-family:verdana'>Visit Date</td>");
                            pVisit.Append("<td style='font-weight:bold;font-size:10px;border-color:black;font-family:verdana'>Status</td>");
                            pVisit.Append("<td style='font-weight:bold;font-size:10px;border-color:black;font-family:verdana'>Field Manager</td>");
                            pVisit.Append("<td style='font-weight:bold;font-size:10px;border-color:black;font-family:verdana'>Details</td>");
                            pVisit.Append("</tr>");
                            pVisit.Append("</thead>");
                            pVisit.Append("<tbody>");
                            List<StoreVisit> visit = new List<StoreVisit>();
                            visit = (List<StoreVisit>)Session["StoreVisit"];
                            if (visit.Count > 0)
                            {
                                foreach (StoreVisit item in visit)
                                {
                                    pVisit.Append("<tr>");
                                    pVisit.Append("<td style='font-size:8px;border-color:black;font-family:verdana'>" + item.RegionName + "</td>");
                                    pVisit.Append("<td style='font-size:8px;border-color:black;font-family:verdana'>" + item.MarketID + "</td>");
                                    pVisit.Append("<td style='font-size:8px;border-color:black;font-family:verdana'>" + item.CustomerStopName + "</td>");
                                    pVisit.Append("<td style='font-size:8px;border-color:black;font-family:verdana'>" + item.Date + "</td>");
                                    pVisit.Append("<td style='font-size:8px;border-color:black;font-family:verdana'>" + item.Status + "</td>");
                                    pVisit.Append("<td style='font-size:8px;border-color:black;font-family:verdana'>" + item.FMName + "</td>");
                                    pVisit.Append("<td style='font-size:8px;border-color:black;font-family:verdana'><a href='#" + item.JobGUID.ToString() + "'>Detail</a></td>");
                                    //pVisit.Append("<a href='#'>Detail</a>");
                                    pVisit.Append("</tr>");
                                }
                            }
                            else
                            {
                                TempData["msg"] = "<script>ModalPopupsAlert('Workers-In-Motion','No data to generate PDF');</script>";
                                return RedirectToAction("Index", "StoreVisit", new { id = "Visits" });
                            }
                        }
                        else if (pdfcontent == "StoreNonVisit" && Session["StoreNonVisit"] != null)
                        {
                            Session["VisitType"] = "Store Non-Visit Report";
                            Response.AddHeader("content-disposition", "attachment;filename=NonVisits.pdf");
                            pVisit.Append("<tr>");
                            pVisit.Append("<td style='font-weight:bold;font-size:10px;border-color:black;font-family:verdana'>Region</td>");
                            pVisit.Append("<td style='font-weight:bold;font-size:10px;border-color:black;font-family:verdana'>Store ID</td>");
                            pVisit.Append("<td style='font-weight:bold;font-size:10px;border-color:black;font-family:verdana'>Store Name</td>");
                            pVisit.Append("<td style='font-weight:bold;font-size:10px;border-color:black;font-family:verdana'>Last Visit Date</td>");
                            //pVisit.Append("<td style='font-weight:bold;font-size:10px;font-family:verdana'>Status</td>");
                            pVisit.Append("<td style='font-weight:bold;font-size:10px;border-color:black;font-family:verdana'>Field Manager</td>");
                            pVisit.Append("<td style='font-weight:bold;font-size:10px;border-color:black;font-family:verdana'>Details</td>");
                            pVisit.Append("</tr>");
                            pVisit.Append("</thead>");
                            pVisit.Append("<tbody>");
                            List<MarketModel> nonvisit = new List<MarketModel>();
                            nonvisit = (List<MarketModel>)Session["StoreNonVisit"];
                            if (nonvisit.Count > 0)
                            {
                                foreach (MarketModel item in nonvisit)
                                {
                                    pVisit.Append("<tr>");
                                    pVisit.Append("<td style='font-size:8px;border-color:black;font-family:verdana'>" + item.RegionName + "</td>");
                                    pVisit.Append("<td style='font-size:8px;border-color:black;font-family:verdana'>" + item.MarketID + "</td>");
                                    pVisit.Append("<td style='font-size:8px;border-color:black;font-family:verdana'>" + item.MarketName + "</td>");
                                    pVisit.Append("<td style='font-size:8px;border-color:black;font-family:verdana'>" + item.LastStoreVisitedDate + "</td>");
                                    //pVisit.Append("<td style='font-size:8px;font-family:verdana'></td>");
                                    pVisit.Append("<td style='font-size:8px;border-color:black;font-family:verdana'>" + item.FirstName + " " + item.LastName + "</td>");
                                    Job _jobnew = _IJobRepository.GetJobByCustomerStopGUID(new Guid(item.MarketGUID));
                                    if (_jobnew != null)
                                    {
                                        pVisit.Append("<td style='font-size:8px;border-color:black;font-family:verdana'><a href='#" + item.MarketGUID.ToString() + "'>Detail</a></td>");
                                    }
                                    else
                                    {
                                        pVisit.Append("<td style='font-size:8px;border-color:black;font-family:verdana'></td>");
                                    }
                                    pVisit.Append("</tr>");
                                }
                            }
                            else
                            {
                                TempData["msg"] = "<script>ModalPopupsAlert('Workers-In-Motion','No data to generate PDF');</script>";
                                return RedirectToAction("Index", "StoreVisit", new { id = "Non-Visits" });
                            }
                        }
                        else
                        {
                            pVisit.Append("<tr>");
                            pVisit.Append("<td style='font-weight:bold;border-color:black;font-size:10px;font-family:verdana'>Region</td>");
                            pVisit.Append("<td style='font-weight:bold;border-color:black;font-size:10px;font-family:verdana'>Store ID</td>");
                            pVisit.Append("<td style='font-weight:bold;border-color:black;font-size:10px;font-family:verdana'>Store Name</td>");
                            pVisit.Append("<td style='font-weight:bold;border-color:black;font-size:10px;font-family:verdana'>Visit Date</td>");
                            pVisit.Append("<td style='font-weight:bold;border-color:black;font-size:10px;font-family:verdana'>Status</td>");
                            pVisit.Append("<td style='font-weight:bold;border-color:black;font-size:10px;font-family:verdana'>Field Manager</td>");
                            pVisit.Append("<td style='font-weight:bold;border-color:black;font-size:10px;font-family:verdana'>Details</td>");
                            pVisit.Append("</tr>");
                            pVisit.Append("</thead>");
                            pVisit.Append("<tbody>");
                        }


                        pVisit.Append("</tbody>");
                        pVisit.Append("</table>");
                        pVisit.Append("</div>");
                        if (pdfcontent == "StoreVisit" && Session["StoreVisit"] != null)
                        {
                            List<StoreVisit> visit = new List<StoreVisit>();
                            visit = (List<StoreVisit>)Session["StoreVisit"];
                            if (visit.Count > 0)
                            {
                                List<string> jobNameList = new List<string>();
                                foreach (StoreVisit item in visit)
                                {
                                    JobFormNew pJobFormView = new JobFormNew();
                                    Job _job = new Job();
                                    _job = _IJobRepository.GetJobByID(item.JobGUID);
                                    if (_job != null)
                                    {
                                        ViewBag.JobName = _job.JobName;
                                        if (!jobNameList.Contains(_job.JobGUID.ToString()))
                                        {
                                            jobNameList.Add(_job.JobGUID.ToString());
                                            if (!string.IsNullOrEmpty(_job.JobForm))
                                            {
                                                pJobFormView = JobFormJsonConvert(_job.JobForm, "PDFImageURL", _job.JobGUID.ToString());
                                            }
                                            if (pJobFormView != null && pJobFormView.FormValues != null && pJobFormView.FormValues.Count > 0)
                                            {
                                                pJobFormView.FormValues.OrderBy(x => x.ControlID);
                                                //  pVisit.Append(GetJobFormHTMLForStoreVisit(pJobFormView, _job.JobName, _job.JobGUID.ToString(), _job.CustomerStopGUID.ToString(), _job.JobGUID.ToString(), _job.StatusCode != null ? Convert.ToInt32(_job.StatusCode) : 6));
                                            }
                                        }
                                    }

                                }
                            }
                        }
                        else if (pdfcontent == "StoreNonVisit" && Session["StoreNonVisit"] != null)
                        {
                            List<MarketModel> nonvisit = new List<MarketModel>();
                            nonvisit = (List<MarketModel>)Session["StoreNonVisit"];
                            if (nonvisit.Count > 0)
                            {
                                List<string> jobNameList = new List<string>();
                                foreach (MarketModel item in nonvisit)
                                {
                                    JobFormNew pJobFormView = new JobFormNew();
                                    Job _job = new Job();
                                    Market _market = _IMarketRepository.GetMarketByID(new Guid(item.MarketGUID));
                                    if (_market != null)
                                    {
                                        _job = _IJobRepository.GetJobByCustomerStopGUID(new Guid(item.MarketGUID));
                                        if (_job != null)
                                        {
                                            ViewBag.JobName = _job.JobName;
                                            if (!jobNameList.Contains(_job.CustomerStopGUID.ToString()))
                                            {
                                                jobNameList.Add(_job.CustomerStopGUID.ToString());
                                                if (!string.IsNullOrEmpty(_job.JobForm))
                                                {
                                                    pJobFormView = JobFormJsonConvert(_job.JobForm, "PDFImageURL", _job.JobGUID.ToString());
                                                }
                                                if (pJobFormView != null && pJobFormView.FormValues != null && pJobFormView.FormValues.Count > 0)
                                                {
                                                    pJobFormView.FormValues.OrderBy(x => x.ControlID);
                                                    // pVisit.Append(GetJobFormHTMLForStoreNonVisit(pJobFormView, _job.JobName, _job.CustomerStopGUID.ToString(), _job.CustomerGUID.ToString(), _job.StatusCode != null ? Convert.ToInt32(_job.StatusCode) : 6));
                                                }
                                            }
                                        }
                                    }
                                }
                            }
                        }
                        //pVisit.Append("</body>");
                        //pVisit.Append("</html>");



                        //byte[] byteArray = Encoding.UTF8.GetBytes(pVisit.ToString());
                        //MemoryStream ms = new MemoryStream(byteArray);

                        //Stream stream = ms;
                        //StreamReader sr = new StreamReader(stream);

                        ////Document document = new Document(new Rectangle(288f, 144f), 10f, 10f, 30f, 30f);
                        //Document document = new Document();

                        //FileStream fs = new FileStream(Request.PhysicalApplicationPath + "\\StoreVisit.pdf", FileMode.Create);
                        //PdfWriter writer = PdfWriter.GetInstance(document, fs);

                        Document document = new Document(PageSize.A4, 70, 55, 40, 25);
                        PdfWriter writer = PdfWriter.GetInstance(document, System.Web.HttpContext.Current.Response.OutputStream);

                        writer.PageEvent = new PDFFooter();
                        document.Open();

                        TextReader txtReader = new StringReader(pVisit.ToString());
                        var xmlWorkerHelper = XMLWorkerHelper.GetInstance();
                        xmlWorkerHelper.ParseXHtml(writer, document, txtReader);

                        //iTextSharp.text.html.simpleparser.HTMLWorker hw = new iTextSharp.text.html.simpleparser.HTMLWorker(document);
                        //hw.Parse(sr);
                        document.Close();

                        //Response.ContentType = "application/pdf";

                        ////Set default file Name as current datetime
                        //Response.AddHeader("content-disposition", "attachment; filename=" + DateTime.Now.ToString("yyyyMMdd") + ".pdf");
                        System.Web.HttpContext.Current.Response.Write(document);

                        Response.Flush();
                        Response.End();
                        //WebClient client = new WebClient();
                        //Byte[] buffer = client.DownloadData(Request.PhysicalApplicationPath + "\\StoreVisit.pdf");
                        //return File(buffer, "application/pdf");
                    }
                }
                else
                {
                    return RedirectToAction("SessionTimeOut", "User");
                }
            }
            catch (Exception ex)
            {
                Logger.Error(ex.Message);
            }
            return null;
        }
        /// <summary>
        /// Adds conflicts to the database depending upon the current state of the election.
        /// </summary>
        /// <param name="session">A valid session.</param>
        protected virtual void ConflictLogic(ISession session)
        {
            List<ElectionConflict> conflicts = ElectionConflict.FindElectionConflicts(session, ID);
            foreach (ElectionConflict conflict in conflicts)
                NHibernateHelper.Delete(session, conflict);

            ITransaction transaction = session.BeginTransaction();
            // Get the current committee
            Committee committee = Committee.FindCommittee(session, PertinentCommittee);

            // Get the users who won the election.
            Dictionary<string, int> winners = GetResults(session);
            List<User> winningUsers = new List<User>();
            foreach (string email in winners.Keys)
            {
                winningUsers.Add(User.FindUser(session, email));
            }

            // Get the users on the committee.
            List<User> members = User.FindUsers(session, committee.Name);

            // List all of the departments currently present on the committee.
            // and use a parallel list to store the ID of the other department
            // member so we can add it to the conflict later.
            List<DepartmentType> departments = new List<DepartmentType>();
            List<int> secID = new List<int>();
            foreach (User i in members)
            {
                departments.Add(i.Department);
                secID.Add(i.ID);
            }

            // For each user who won, add a new conflict if their department
            // is already present on the list. Adding, departments as we go.
            // Also raise conflicts if the winning users hold officer positions,
            // or if they already serve on a committee.
            foreach (User i in winningUsers)
            {
                // check if they have a prior committment
                if (i.OfficerPosition != OfficerPositionType.None ||
                    i.CurrentCommittee != User.NoCommittee)
                {
                    ElectionConflict conflict = new ElectionConflict();
                    conflict.Election = ID;
                    conflict.FirstUser = i.ID;
                    conflict.SecUser = ElectionConflict.SecondUserNotApplicable;
                    conflict.Type = ConflictType.ElectedToMultipleCommittees;
                    session.SaveOrUpdate(conflict);
                }

                // check for department-based conflicts
                if(departments.Contains(i.Department))
                {
                    ElectionConflict conflict = new ElectionConflict();
                    conflict.Election = ID;
                    conflict.FirstUser = i.ID;
                    conflict.SecUser = secID[departments.IndexOf(i.Department)];
                    conflict.Type = ConflictType.TooManyDeptMembers;
                    session.SaveOrUpdate(conflict);
                }
            }
            session.Flush();
            NHibernateHelper.Finished(transaction);
        }
        public ActionResult FiltersPartial(int? param)
        {
            List<AllOptionsModel> readyList = new List<AllOptionsModel>();
            AllOptionsModel readyModel = new AllOptionsModel();

            List<string> list = new List<string>();
            var producers = from x in db.ProdutcsToCategories
                            where x.CatId == param
                            select x.Product.Producer;
            foreach (var producer in producers)
            {
                if (producer != null)
                {
                    if (!list.Contains(producer))
                        list.Add(producer);
                }
            }

            readyModel.listString = list.ToList();

            var option = from x in db.Options
                         where x.categoryId == param
                         select x;
            List<OptionModel> om = new List<OptionModel>();
            foreach (var opt in option)
            {
                OptionModel model = new OptionModel();
                model.option = opt;
                var option2 = from x in db.OptionValues
                              where x.ValueId == opt.ValuesId
                              select x;
                List<OptionValue> ovl = new List<OptionValue>();
                foreach (var optionValue in option2)
                {
                    if (optionValue != null)
                    {
                        //model.optionValueList.Add(optionValue);
                        ovl.Add(optionValue);
                    }
                }
                model.optionValueList = ovl;

                om.Add(model);
                //readyModel.optionList.Add(model);

            }
            readyModel.optionList = om;
            readyList.Add(readyModel);
            return View("FiltersPartial", readyModel);
        }
Exemple #6
0
        /// <summary>
        /// Displays form fiels for chosed identifiers.
        /// </summary>
        /// <param name="formCollection">object that encapsulates chosed identifiers for reporting</param>
        public ActionResult Fill(FormCollection formCollection)
        {
            if (Session["OrganisationID"] == null)
            {
                TempData["accessError"] = "Vaše session vypršela, nebo nejste přihlášen.";
                return RedirectToAction("LogOn", "Organisation");
            }

            bool standardSubsectors = true;
            bool specialisedSubsectorsCorrect = true;

            this.TempData.Clear();

            foreach (var key in formCollection.AllKeys)
            {

                if (!key.StartsWith("S"))
                {
                    int subsectorID = Convert.ToInt32(key);
                    var subsector = db.SubsectorsESG.Where(s => s.ID == subsectorID).SingleOrDefault();

                    char[] delimiter2 = { ',' };
                    string[] identifiers2 = formCollection[key].Split(delimiter2);
                    IList<int> intIdentifiers1 = new List<int>();

                    foreach (var item in identifiers2)
                    {
                        intIdentifiers1.Add(Convert.ToInt32(item));
                        TempData[key + "-" + item] = "checked";
                    }

                    int countScope1 = subsector.KeyPerformanceIdentifiers.Where(kpi => kpi.Scope == 1).Count();

                    int countScope1Check = subsector.KeyPerformanceIdentifiers
                                                    .Where(kpi => kpi.Scope == 1)
                                                    .Where(kpi => intIdentifiers1.Contains(kpi.ID))
                                                    .Count();

                    if (countScope1 != countScope1Check)
                    {
                        standardSubsectors = false;
                    }
                }

                if (key.StartsWith("S"))
                {
                    char[] delimiter = { '-' };
                    string[] parts = key.Split(delimiter);

                    int subsectorID = Convert.ToInt32(parts[1]);
                    var subsector = db.SpecialisedSubsectorsESG.Where(s => s.ID == subsectorID).SingleOrDefault();

                    char[] delimiter2 = { ',' };
                    string[] identifiers2 = formCollection[key].Split(delimiter2);
                    IList<int> intIdentifiers = new List<int>();

                    foreach (var item in identifiers2)
                    {
                        intIdentifiers.Add(Convert.ToInt32(item));
                        TempData["S-" + subsectorID + "-" + item] = "checked";
                    }

                    int countScope1 = subsector.SpecialisedIdentifiers.Where(kpi => kpi.Scope == 1 && kpi.Activated).Count();
                    int countScope1Check = subsector.SpecialisedIdentifiers
                                                    .Where(si => si.Scope == 1 && si.Activated)
                                                    .Where(si => intIdentifiers.Contains(si.ID))
                                                    .Count();

                    if (countScope1 != countScope1Check)
                    {
                        specialisedSubsectorsCorrect = false;
                    }
                }
            }

            if (formCollection.AllKeys.Where(s => !s.StartsWith("S")).Count() == 0)
            {
                TempData["errorFound"] = "errorFound";
                TempData["notChosedStandardSubsector"] = "Musi být zvolen alespoň 1 standardní podsektor a všechny jeho identifikátory rozsahu 1.";
                return RedirectToAction("Choose");
            }

            if (!standardSubsectors || !specialisedSubsectorsCorrect)
            {
                TempData["errorFound"] = "errorFound";
                TempData["notChosedStandardSubsector"] = "Musi být zvolen alespoň 1 standardní podsektor a všechny jeho identifikátory rozsahu 1.";
                return RedirectToAction("Choose");
            }

            ChosedIdentifiers chosedIdentifiers = null;

            chosedIdentifiers = new ChosedIdentifiers();

            foreach (var key in formCollection.AllKeys)
            {
                if (key.StartsWith("S"))
                {
                    char[] delimiter1 = { '-' };
                    string[] identifiers1 = key.Split(delimiter1);

                    int specialisedSubsectorID = Convert.ToInt32(identifiers1[1]);
                    SpecialisedSubsector specialisedSubsector = db.SpecialisedSubsectorsESG.Where(ss => ss.ID == specialisedSubsectorID).SingleOrDefault();

                    chosedIdentifiers.AddSpecialisedSubsector(specialisedSubsector);

                    char[] delimiter2 = { ',' };
                    string[] identifiers2 = formCollection[key].Split(delimiter2);
                    IList<int> intIdentifiers1 = new List<int>();

                    foreach (var item in identifiers2)
                    {
                        intIdentifiers1.Add(Convert.ToInt32(item));
                    }

                    var specialisedSubsectorIdentifiers = db.SpecialisedIdentifiersESG.Where(si => intIdentifiers1.Contains(si.ID));

                    foreach (SpecialisedIdentifier item in specialisedSubsectorIdentifiers)
                    {
                        chosedIdentifiers.SpecialisedSubsectorsIdentifiers[specialisedSubsector].Add(item);
                    }

                    continue;
                }

                int subsectorID = Convert.ToInt32(key);
                Subsector subsector = db.SubsectorsESG.Where(s => s.ID == subsectorID).SingleOrDefault();

                chosedIdentifiers.AddSubsector(subsector);

                char[] delimiter = { ',' };
                string[] identifiers = formCollection[key].Split(delimiter);
                IList<int> intIdentifiers = new List<int>();

                foreach (var item in identifiers)
                {
                    intIdentifiers.Add(Convert.ToInt32(item));
                }

                var subsectorIdentifiers = db.KeyPerformanceIdentifiersESG.Where(kpi => intIdentifiers.Contains(kpi.ID));

                foreach (KeyPerformanceIdentifier item in subsectorIdentifiers)
                {
                    chosedIdentifiers.SubsectorsIdentifiers[subsector].Add(item);
                }
            }

            return View(chosedIdentifiers);
        }
        protected void UpdateExplanationValidationField()
        {
            HealthStatements collection = (HealthStatements)(Session["HealthStatements"]);
            List<String> QuestionsToAnswer = new List<String>();

            foreach (System.Web.UI.WebControls.ListItem li in cmbQuestion.Items)
            {
                if (!QuestionsToAnswer.Contains(li.Value))
                {
                    QuestionsToAnswer.Add(li.Value);
                }
            }

            foreach (HealthStatement hs in collection.MyHealthStatements)
            {
                if (QuestionsToAnswer.Contains(hs.QuestionNum))
                {
                    QuestionsToAnswer.Remove(hs.QuestionNum);
                }
            }

            //Update field used for validation.
            NumExplanationsRequired.Value = QuestionsToAnswer.Count.ToString();
        }
        public ActionResult RegisterProfesor(Profesor profesor)
        {
            if (ModelState.IsValid)
            {
                if (profesor.Password == profesor.ConfirmPassword)
                {
                    IRepositorio<Profesor> repositorioProfesor = new ProfesorRepositorio();
                    var miProfesor = repositorioProfesor.GetByUniqueAtribute(profesor.Username);

                    IRepositorio<Alumno> repositorioAlumno = new AlumnoRepositorio();
                    var miAlumno = repositorioAlumno.GetByUniqueAtribute(profesor.Username);

                    if (miProfesor == null && miAlumno == null)
                    {
                        MembershipCreateStatus createStatus = MembershipService.CreateUser(profesor.Username,
                                                                                           profesor.Password,
                                                                                           profesor.Nombre.Substring(0, 1) + profesor.Apellido + "@ucab.edu.ve");
                        if (createStatus == MembershipCreateStatus.Success)
                        {
                            if (Roles.RoleExists("Profesor"))
                            {
                                Roles.AddUserToRole(profesor.Username, "Profesor");
                            }
                            else
                            {
                                Roles.CreateRole("Profesor");
                                Roles.AddUserToRole(profesor.Username, "Profesor");
                            }
                            profesor.CreationDate = DateTime.Today;
                            var prof = repositorioProfesor.GetById(profesor.Cedula);
                            var flag = prof == null ? repositorioProfesor.Save(profesor) : repositorioProfesor.Update(profesor);

                            if (flag.CompareTo("true") == 0)
                            {
                                Session["cedula"] = profesor.Cedula;
                                IRepositorio<Actividad> repositorioActividad = new ActividadRepositorio();
                                var listActividades =
                                    repositorioActividad.GetAll().Where(a => a.Profesor == profesor.Cedula &&
                                                                             a.Periodo.CompareTo(_periodoActual) == 0 &&
                                                                             a.Tipo.CompareTo("Clase") == 0).ToList();
                                var misMaterias = new List<Materium>();
                                IRepositorio<Materium> repositorioMateria = new MateriumRepositorio();
                                foreach (var actividad in listActividades)
                                {
                                    var materia = repositorioMateria.GetById(actividad.IdMateria);
                                    materia.Seccion = actividad.Seccion;
                                    if (!misMaterias.Contains(materia))
                                    {
                                        misMaterias.Add(materia);
                                    }
                                }
                                profesor.Materiums = misMaterias;
                                FormsService.SignIn(profesor.Username, false /* createPersistentCookie */);
                                return View("ConfigurationProfesor", profesor);
                            }
                            else
                            {
                                ModelState.AddModelError("saveAlumno", "Oops! Ha ocurrido un error inesperado, vuelva a intentarlo.");
                            }
                        }
                        else
                        {
                            ModelState.AddModelError("passOrUsername", AccountValidation.ErrorCodeToString(createStatus));
                        }
                    }
                    else
                    {
                        ModelState.AddModelError("passOrUsername", "Oops!! El nombre de usuario ya existe, por favor intente con otro.");
                    }
                }
                else
                {
                    ModelState.AddModelError("contrasenia", "Las contraseñas no coinciden.");
                }
            }
            return View(profesor);
        }
 public static bool IsValidFileExtension(string extension)
 {
     extension = extension.Replace(".", "");
     IEnumerable<string> extensions = new List<string> { "pdf", "doc", "docx", "odt", "txt", "xls", "xlsx", "ods", "ppt", "pptx", "odp" };
     return extensions.Contains(extension);
 }
        private void printRingForUser(UserShows userShow, int UserID, Document doc, ref List<int> defaultUsers, ref int pageCount)
        {
            String html = "";
            float[] ringColumns = new float[] { 300, 300, 300, 300};

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

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

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

            Dogs d = new Dogs();

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

                PrevShowDetailsID = ShowDetailsID;
            }

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

                }
            }

            if (currentUser.UserID == UserID)
            {
                doc.Add(getHandlerDetails(userShow, currentUser, PrevShowDetailsID, dogsRunningToday));
            }
            else
            {
                User defaultHandler = new User(UserID);
                doc.Add(getHandlerDetails(userShow, defaultHandler, PrevShowDetailsID, dogsRunningToday));
            }
            doc.NewPage();
        }
        private void saveResultsToPDFToolStripMenuItem_Click(object sender, EventArgs e)
        {
            BaseFont bfTimes = BaseFont.CreateFont(BaseFont.TIMES_ROMAN, BaseFont.CP1252, false);
            iTextSharp.text.Font times = new iTextSharp.text.Font(bfTimes, 12, iTextSharp.text.Font.ITALIC, BaseColor.DARK_GRAY);
            Document doc = new Document(iTextSharp.text.PageSize.LETTER, 10, 10, 42, 42);
            PdfWriter pdw = PdfWriter.GetInstance(doc, new FileStream("TextsStats"+DateTime.Now.GetHashCode().ToString() + ".pdf", FileMode.Create));
            doc.Open();
            Paragraph p = new Paragraph("Text Stats for : " + DateTime.Now, times);
            doc.Add(p);
            p.Alignment = 1;
            PdfPTable pdt = new PdfPTable(4);
            pdt.HorizontalAlignment = 1;
            pdt.SpacingBefore = 20f;
            pdt.SpacingAfter = 20f;
            pdt.AddCell("Name of Text");
            pdt.AddCell("MSE (Naivna)");
            pdt.AddCell("MSE (Gramatika)");
            pdt.AddCell("PCT");
            c_tekst.SelectedIndex = 0;
            c_analiza.SelectedIndex = 0;
            foreach (Tekst t in lista_teksta)
            {
                c_analiza.SelectedIndex = 0;
                calculateStats("Pojedinačan tekst", 1);
                c_analiza.SelectedIndex = 1;
                calculateStats("Pojedinačan tekst", 2);
                if(c_tekst.SelectedIndex+1 < c_tekst.Items.Count)
                    c_tekst.SelectedIndex++;
            }
            List<StatistikaTekst> cista_lista_PDF = new List<StatistikaTekst>();
            List<String> help = new List<String>();
            StatistikaTekst ukupno = new StatistikaTekst();
            foreach(StatistikaTekst st in lista_PDF)
            {
                if (!help.Contains(st.Ime_teksta))
                {
                    help.Add(st.Ime_teksta);
                    ukupno.RMSE_G1 += st.RMSE_G1;
                    ukupno.RMSE_N1 += st.RMSE_N1;
                    cista_lista_PDF.Add(st);
                }
            }
            ukupno.Ime_teksta = "TOTAL";
            ukupno.RMSE_G1 /= cista_lista_PDF.Count();
            ukupno.RMSE_N1 /= cista_lista_PDF.Count();
            ukupno.RMSE_G1 = Math.Round(ukupno.RMSE_G1, 5);
            ukupno.RMSE_N1 = Math.Round(ukupno.RMSE_N1, 5);
            ukupno.Pct_diff = Math.Round(ukupno.RMSE_G1 / ukupno.RMSE_N1, 5);
            cista_lista_PDF.Add(ukupno);
            foreach (StatistikaTekst st in cista_lista_PDF)
            {
                pdt.AddCell(st.Ime_teksta);
                pdt.AddCell(Convert.ToString(st.RMSE_N1));
                pdt.AddCell(Convert.ToString(st.RMSE_G1));
                pdt.AddCell(Convert.ToString(st.Pct_diff*100)+'%');
            }
            /*using (MemoryStream stream = new MemoryStream())
            {
                chart1.SaveImage(stream, ChartImageFormat.Png);
                iTextSharp.text.Image chartImage = iTextSharp.text.Image.GetInstance(stream.GetBuffer());
                chartImage.ScalePercent(75f);
                chartImage.Alignment = 1;
                doc.Add(chartImage);
            }*/
            doc.Add(pdt);
            doc.Close();
            using (ExcelPackage ep = new ExcelPackage())
            {
                //Here setting some document properties
                ep.Workbook.Properties.Author = "MasterWordCounter";
                ep.Workbook.Properties.Title = "Text Data";

                //Create a sheet
                ep.Workbook.Worksheets.Add("Text Data");
                ExcelWorksheet ws = ep.Workbook.Worksheets[1];
                ws.Name = "Text Data"; //Setting Sheet's name
                ws.Cells.Style.Font.Size = 11; //Default font size for whole sheet
                ws.Cells.Style.Font.Name = "Calibri"; //Default Font name for whole sheet

                DataTable dt = new DataTable("TextsStats" + DateTime.Now.GetHashCode().ToString()); //My Function which generates DataTable
                dt.Columns.Add("Ime Djela");
                dt.Columns.Add("MSE (Naivna)");
                dt.Columns.Add("MSE (Gramatika)");
                dt.Columns.Add("Procenat (%)");
                foreach (StatistikaTekst st in cista_lista_PDF)
                {
                    DataRow dr = dt.NewRow();
                    dr["Ime Djela"] = (st.Ime_teksta);
                    dr["MSE (Naivna)"] = st.RMSE_N1;
                    dr["MSE (Gramatika)"] = st.RMSE_G1;
                    dr["Procenat (%)"] = st.Pct_diff * 100;
                    dt.Rows.Add(dr);
                }
                //Merging cells and create a center heading for out table
                ws.Cells[1, 1].Value = "Ime Djela";
                ws.Cells[1, 2].Value = "MSE (Naivna)";
                ws.Cells[1, 3].Value = "MSE (Gramatika)";
                ws.Cells[1, 4].Value = "Procenat (%)";

                int colIndex = 1;
                int rowIndex = 2;

                foreach (DataColumn dc in dt.Columns) //Creating Headings
                {
                    var cell = ws.Cells[rowIndex, colIndex];

                    //Setting the background color of header cells to Gray
                    var fill = cell.Style.Fill;
                    fill.PatternType = ExcelFillStyle.Solid;
                    fill.BackgroundColor.SetColor(Color.Gray);

                    //Setting Top/left,right/bottom borders.
                    var border = cell.Style.Border;
                    border.Bottom.Style =
                        border.Top.Style =
                        border.Left.Style =
                        border.Right.Style = ExcelBorderStyle.Thin;

                    //Setting Value in cell
                    cell.Value = "Heading " + dc.ColumnName;

                    colIndex++;
                }

                foreach (DataRow dr in dt.Rows) // Adding Data into rows
                {
                    colIndex = 1;
                    rowIndex++;
                    foreach (DataColumn dc in dt.Columns)
                    {
                        var cell = ws.Cells[rowIndex, colIndex];
                        //Setting Value in cell
                        cell.Value = dr[dc.ColumnName];

                        //Setting borders of cell
                        var border = cell.Style.Border;
                        border.Left.Style =
                            border.Right.Style = ExcelBorderStyle.Thin;
                        colIndex++;
                    }
                }

                colIndex = 0;
                foreach (DataColumn dc in dt.Columns) //Creating Headings
                {
                    colIndex++;
                    var cell = ws.Cells[rowIndex, colIndex];

                    //Setting Sum Formula
                    cell.Formula = "Sum(" +
                                    ws.Cells[3, colIndex].Address +
                                    ":" +
                                    ws.Cells[rowIndex - 1, colIndex].Address +
                                    ")";

                    //Setting Background fill color to Gray
                    cell.Style.Fill.PatternType = ExcelFillStyle.Solid;
                    cell.Style.Fill.BackgroundColor.SetColor(Color.Gray);
                }

                //Generate A File with Random name
                Byte[] bin = ep.GetAsByteArray();
                string file = Guid.NewGuid().ToString() + ".xlsx";
                File.WriteAllBytes(file, bin);
            }
            MessageBox.Show("PDF created!");
        }
Exemple #12
0
        /// <summary>
        /// GetLIstOfUserNames Method Definition
        /// </summary>
        /// <param name="projectName"></param>
        /// <returns></returns>
        public Boolean GetListOfUserNames(string projectName)
        {
            dtView.DataSource = null;
            dtView.Rows.Clear();
            _glUsers.Clear();

            if (projectName == "ALL")
            {
                lstProjects.Items.Clear();
                lstProjects.Items.Add("All TFS Projects");
                lstProjects.Items.Add("");
                teamProjects = _versionControl.GetAllTeamProjects(false);
                foreach (TeamProject tp in teamProjects)
                {
                    lstProjects.Items.Add(tp.Name);
                    Identity[] appGroups = _securityService.ListApplicationGroups(tp.ArtifactUri.AbsoluteUri);
                    foreach (Identity group in appGroups)
                    {
                        Identity[] groupMembers = _securityService.ReadIdentities(SearchFactor.Sid, new string[] { group.Sid }, QueryMembership.Expanded);
                        if (groupMembers.Length == 0) break;
                        foreach (Identity member in groupMembers)
                        {
                            if (member.Members.Length == 0) break;
                            if (member.Members != null)
                            {
                                foreach (string memberSid in member.Members)
                                {
                                    Identity memberInfo = _securityService.ReadIdentity(SearchFactor.Sid, memberSid, QueryMembership.None);
                                    if (memberInfo.Type != IdentityType.WindowsUser) continue;

                                    if (_glUsers.Contains(memberInfo.Sid))
                                        _userDetail = (UserDetails)_glUsers[memberInfo.Sid];
                                    else
                                        _userDetail = new UserDetails(memberInfo);

                                    //update the project and permission
                                    _userDetail.TeamProject = tp.Name;
                                    _userDetail.Permission = group.DisplayName;
                                    _userDetail.UpdateProjectAndPermission(tp.Name, group.DisplayName);
                                    if (_glUsers.ContainsKey(memberInfo.Sid))
                                        _glUsers.Remove(memberInfo.Sid);

                                    _glUsers.Add(memberInfo.Sid, _userDetail);

                                }
                            }
                        }
                    }

                }
            }
            else if (projectName == "")
            {

            }
            else
            {
                TeamProject teamproject = _versionControl.GetTeamProject(projectName);
                Identity[] appGroups = _securityService.ListApplicationGroups(teamproject.ArtifactUri.AbsoluteUri);
                List<Identity> usernames = new List<Identity>();

                foreach (Identity group in appGroups)
                {
                    Identity[] groupMembers = _securityService.ReadIdentities(SearchFactor.Sid, new string[] { group.Sid }, QueryMembership.Expanded);

                    foreach (Identity member in groupMembers)
                    {
                        if (member.Members != null)
                        {

                            foreach (string memberSid in member.Members)
                            {
                                Identity memberInfo = _securityService.ReadIdentity(SearchFactor.Sid, memberSid, QueryMembership.None);
                                if (memberInfo.Type != IdentityType.WindowsUser) continue;

                                if (usernames.Contains(memberInfo))
                                    _userDetail = (UserDetails)_glUsers[memberInfo.Sid];
                                else
                                    _userDetail = new UserDetails(memberInfo);

                                //update the project and permission
                                _userDetail.TeamProject = teamproject.Name;
                                _userDetail.Permission = group.DisplayName;
                                _userDetail.UpdateProjectAndPermission(teamproject.Name, group.DisplayName);
                                if (_glUsers.ContainsKey(memberInfo.Sid))
                                    _glUsers.Remove(memberInfo.Sid);

                                _glUsers.Add(memberInfo.Sid, _userDetail);

                            }
                        }
                    }
                }
            }

            int sn = 0;
            dtView.Rows.Add(_glUsers.Count + 1);
            foreach (UserDetails userIdentity in _glUsers.Values)
            {
                dtView.Rows[sn].Cells[0].Value = userIdentity.UserName;
                dtView.Rows[sn].Cells[1].Value = userIdentity.ADId;
                dtView.Rows[sn].Cells[2].Value = userIdentity.EmailAdd;
                dtView.Rows[sn].Cells[3].Value = userIdentity.Domain;
                string v = string.Empty;
                Hashtable ht = userIdentity.PaR;
                foreach (string str in userIdentity.PaR.Values)
                {
                    v = string.Format("{0}{1}", v, str);
                }
                dtView.Rows[sn].Cells[4].Value = v;
                dtView.Rows[sn].Cells[5].Value = userIdentity.Status;
                sn++;
            }
            return true;
        }
        public ActionResult ICS109(Guid id)
        {
            var mission = this.db.Missions.Include("Log").Single(f => f.Id == id);

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

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

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

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

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

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

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

              var fields = stamper.AcroFields;

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

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

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

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

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

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

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

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

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

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

            resultDoc.Close();
            return File(result.ToArray(), "application/pdf", mission.StateNumber + "_ICS109_CommLog.pdf");
              }
        }
        public ActionResult ConfigurationProfesor()
        {
            IRepositorio<Profesor> repositorioProfesor = new ProfesorRepositorio();
            var miCedula = (int)Session["cedula"];
            var profesor = repositorioProfesor.GetById(miCedula);
            IRepositorio<Actividad> repositorioActividad = new ActividadRepositorio();
            var listActividades =
                repositorioActividad.GetAll().Where(a => a.Profesor == profesor.Cedula &&
                                                         a.Periodo.CompareTo(_periodoActual) == 0 &&
                                                         a.Tipo.CompareTo("Clase") == 0);

            var misMaterias = new List<Materium>();
            IRepositorio<Materium> repositorioMateria = new MateriumRepositorio();
            foreach (var actividad in listActividades)
            {
                var materia = repositorioMateria.GetById(actividad.IdMateria);
                materia.Seccion = actividad.Seccion;
                if (!misMaterias.Contains(materia))
                {
                    var listActividadEval = repositorioActividad.GetAll().Where(a => a.Tipo.CompareTo("Evaluacion") == 0 &&
                                                                             a.Periodo.CompareTo(_periodoActual) == 0 &&
                                                                             a.Profesor == miCedula &&
                                                                             a.Seccion == materia.Seccion &&
                                                                             a.IdMateria == materia.IdMateria).ToList();
                    if (listActividadEval.Count == 0)
                    {
                        misMaterias.Add(materia);
                    }
                }
            }
            profesor.Materiums = misMaterias;

            return View(profesor);
        }
Exemple #15
0
        private void button5_Click(object sender, EventArgs e)
        {
            List<string> employeeIdToRemove = new List<string>();
            if (EmployeesDataGrid.SelectedRows.Count > 0)
            {
                foreach (DataGridViewRow row in EmployeesDataGrid.SelectedRows)
                {
                    //MessageBox.Show( row.Cells["EmployeeID"].Value.ToString());
                    if (!employeeIdToRemove.Contains(row.Cells["EmployeeID"].Value.ToString()))
                    {
                        employeeIdToRemove.Add(row.Cells["EmployeeID"].Value.ToString());
                    }
                }

            }
            else if (EmployeesDataGrid.SelectedCells.Count > 0)
            {
                foreach (DataGridViewCell cell in EmployeesDataGrid.SelectedCells)
                {
                    DataGridViewRow row = EmployeesDataGrid.Rows[cell.RowIndex];
                    //MessageBox.Show(row.Cells["EmployeeID"].Value.ToString());
                    if (!employeeIdToRemove.Contains(row.Cells["EmployeeID"].Value.ToString()))
                    {
                        employeeIdToRemove.Add(row.Cells["EmployeeID"].Value.ToString());
                    }
                }
            }

            foreach (string ID in employeeIdToRemove)
            {
                DialogResult confirm = MessageBox.Show("Are you sure you want to Delete employee ID# " + ID,
                    "Confirm Delete",
                    MessageBoxButtons.YesNo,
                    MessageBoxIcon.Exclamation,
                    MessageBoxDefaultButton.Button2);

                if (confirm == DialogResult.Yes)
                {
                    Controller controller = new Controller(database);
                    controller.RemoveEmployee(ID);

                    EmployeesDataGrid.DataSource = null;
                    EmployeesDataGrid.Update();
                    EmployeesDataGrid.Refresh();

                    List<Employee> data;
                    data = this.database.SelectAllEmployee();
                    EmployeesDataGrid.DataSource = data;
                    EmployeesDataGrid.Update();
                    EmployeesDataGrid.Refresh();

                }

            }
        }
 // **************************************
 // URL: /Account/GetCountryList
 // **************************************
 public IEnumerable<string> GetCountryList()
 {
     List<string> list = new List<string>();
     CultureInfo[] cultures =
                 CultureInfo.GetCultures(CultureTypes.InstalledWin32Cultures |
                 CultureTypes.SpecificCultures);
     foreach (CultureInfo info in cultures)
     {
         //RegionInfo info2 = new RegionInfo(info.LCID);
         if (!list.Contains(info.EnglishName))
         {
             list.Add(info.DisplayName);
         }
     }
     return list;
 }
        public ActionResult viewPRExcel(Int16 fiscalYear, Int16? coeID)
        {
            ModelState.Clear();
            var viewModel = new PRViewModel
            {
                //allCoEs = db.CoEs.ToList(),
                allCoEs = db.CoEs.ToList(),
                allMaps = db.Indicator_CoE_Maps.ToList(),
                allFootnoteMaps = db.Indicator_Footnote_Maps.ToList()
            };

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

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

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

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

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

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

            var prFootnoteCharsNewLine = 125;
            var prObjectivesCharsNewLine = 226;

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

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

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

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

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

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

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

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

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

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

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

                    currentRow += 2;

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

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

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

                        currentRow++;

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

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

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

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

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

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

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

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

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

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

                                double maxLines = 1;
                                double lines;

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

            httpResponse.End();

            return View(viewModel);
        }
        private void printRingForUser(UserShows userShow, int UserID, Document doc, ref List<int> defaultUsers, ref int pageCount)
        {
            float[] ringColumns = new float[] { 300, 300, 300, 300 };

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

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

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

            Dogs d = new Dogs();

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

                        int countDogs = 0;
                        int DefaultHandler;

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

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

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

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

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

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

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

                            classDetailsTable.AddCell(cell);

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

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

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

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

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

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

                    }

                    PrevShowDetailsID = ShowDetailsID;
                }

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

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

                        if (UserID > -1)
                        {
                            if (currentUser.UserID != UserID)
                            {
                                User defaultHandler = new User(UserID);
                            }
                        }
                        doc.NewPage();
                        pageCount++;
                    }
                }
            }
            catch (Exception e)
            {
                AppException.LogError($"Error Running Plan:{e.Message},{e.StackTrace}");
            }
        }
        private void MonteDocumentoDoRelatorio()
        {
            var corBackgroudHeader = Color.GRAY;
            var tabela = new PdfPTable(1);
            var dicionarioDeManutencoes = new Dictionary<long, InformacoesRelatorioDeManutencoes>();
            var dicionarioDePatentes = new Dictionary<long, IList<IProcessoDePatente>>();
            var dicionarioDeMarcas = new Dictionary<long, IList<IProcessoDeMarca>>();
            var listaDeIdsDosClientes = new List<long>();

            tabela.WidthPercentage = 100;
            tabela.DefaultCell.Border = Rectangle.NO_BORDER;

            _processosDePatentes = _processosDePatentes.OrderBy(processo => processo.Patente.Clientes[0].Pessoa.Nome).ToList();
            _processosDeMarcas = _processosDeMarcas.OrderBy(processo => processo.Marca.Cliente.Pessoa.Nome).ToList();

            foreach (IProcessoDePatente processo in _processosDePatentes)
            {
                var cliente = processo.Patente.Clientes[0];

                if (cliente.Pessoa != null && cliente.Pessoa.ID.HasValue && !dicionarioDePatentes.ContainsKey(cliente.Pessoa.ID.Value))
                {
                    dicionarioDePatentes.Add(cliente.Pessoa.ID.Value, new List<IProcessoDePatente>());

                    if(!listaDeIdsDosClientes.Contains(cliente.Pessoa.ID.Value))
                        listaDeIdsDosClientes.Add(cliente.Pessoa.ID.Value);
                }

                if (cliente.Pessoa != null && cliente.Pessoa.ID.HasValue)
                    dicionarioDePatentes[cliente.Pessoa.ID.Value].Add(processo);
            }

            foreach (IProcessoDeMarca processo in _processosDeMarcas)
            {
                var cliente = processo.Marca.Cliente;

                if (cliente.Pessoa != null && cliente.Pessoa.ID.HasValue && !dicionarioDeMarcas.ContainsKey(cliente.Pessoa.ID.Value))
                {
                    dicionarioDeMarcas.Add(cliente.Pessoa.ID.Value, new List<IProcessoDeMarca>());

                    if (!listaDeIdsDosClientes.Contains(cliente.Pessoa.ID.Value))
                        listaDeIdsDosClientes.Add(cliente.Pessoa.ID.Value);
                }

                if (cliente.Pessoa != null && cliente.Pessoa.ID.HasValue)
                    dicionarioDeMarcas[cliente.Pessoa.ID.Value].Add(processo);
            }

            foreach (long identificador in listaDeIdsDosClientes)
            {
                if(!dicionarioDeManutencoes.ContainsKey(identificador))
                {
                    var informacoes = new InformacoesRelatorioDeManutencoes();

                    if(dicionarioDePatentes.ContainsKey(identificador))
                        informacoes.ProcessoDePatentes = dicionarioDePatentes[identificador];

                    if(dicionarioDeMarcas.ContainsKey(identificador))
                        informacoes.ProcessoDeMarcas = dicionarioDeMarcas[identificador];

                    dicionarioDeManutencoes.Add(identificador, informacoes);
                }
            }

            tabela.AddCell(ObtenhaTabelaTitulo());

            foreach (long chave in dicionarioDeManutencoes.Keys)
            {
                string nomeDoCliente = string.Empty;

                if (dicionarioDeManutencoes[chave].ProcessoDeMarcas != null && dicionarioDeManutencoes[chave].ProcessoDeMarcas.Count > 0)
                    nomeDoCliente = dicionarioDeManutencoes[chave].ProcessoDeMarcas[0].Marca.Cliente.Pessoa.Nome;
                else if (dicionarioDeManutencoes[chave].ProcessoDePatentes != null && dicionarioDeManutencoes[chave].ProcessoDePatentes.Count > 0)
                    nomeDoCliente = dicionarioDeManutencoes[chave].ProcessoDePatentes[0].Patente.Clientes[0].Pessoa.Nome;

                if (dicionarioDeManutencoes[chave].ProcessoDePatentes != null)
                    foreach (IProcessoDePatente processoDePatente in dicionarioDeManutencoes[chave].ProcessoDePatentes)
                        tabela.AddCell(ObtenhaTabelaDadosDaPatente(processoDePatente, nomeDoCliente));

                if (dicionarioDeManutencoes[chave].ProcessoDeMarcas != null)
                    foreach (IProcessoDeMarca processoDeMarca in dicionarioDeManutencoes[chave].ProcessoDeMarcas)
                        tabela.AddCell(ObtenhaTabelaDadosDaMarca(processoDeMarca, nomeDoCliente));
            }

            _documento.Add(tabela);
        }