void LoadEmployees()
 {
     EmployeeService employeeService = new EmployeeService();
     employees = employeeService.GetEmployees();
     Employee e = new Employee
     {
         Id = 0,
         FullName = "Tất cả"
     };
     employees.Add(e);
     employees = employees.OrderBy(el => el.Id).ToList();
     if (employees != null)
     {
         cbmEmployees.DataSource = employees;
         cbmEmployees.DisplayMember = "FullName";
         cbmEmployees.ValueMember = "Id";
     }
 }
 void LoadDataCombobox()
 {
     ProductTypeService productTypeService = new ProductTypeService();
     ProductType pt = new ProductType
     {
         Id = 0,
         TypeName = "Tất cả"
     };
     productTypes = productTypeService.GetProductTypes();
     productTypes.Add(pt);
     productTypes = productTypes.OrderBy(pts => pts.Id).ToList();
     if (productTypes != null)
     {
         cbmProductTypes.DataSource = productTypes;
         cbmProductTypes.DisplayMember = "TypeName";
         cbmProductTypes.ValueMember = "Id";
     }
     LoadProducts(0);
 }
Пример #3
0
        public static MemoryStream GeneratePDF(Teacher teacher, SchoolClass schoolClass, List<Pupil> pupils, string schoolYear)
        {
            Document document = new Document();
            MemoryStream stream = new MemoryStream();
            PdfWriter writer = PdfWriter.GetInstance(document, stream);

            writer.CloseStream = false;
            document.Open();
            document.AddCreationDate();
            document.AddAuthor("VaKEGrade");
            document.AddTitle("Certificate");

            pupils = pupils.OrderBy(x => x.LastName).ToList();
            foreach (Pupil pupil in pupils)
            {
                CertificateGenerator.GenerateCertificate(pupil, schoolClass, schoolYear, ref document);
            }
            document.Close();
            stream.Seek(0, SeekOrigin.Begin);
            return stream;
        }
Пример #4
0
        public IPdfReportData CreatePdfReport()
        {
            return new PdfReport().DocumentPreferences(doc =>
            {
                doc.RunDirection(PdfRunDirection.LeftToRight);
                doc.Orientation(PageOrientation.Portrait);
                doc.PageSize(PdfPageSize.A4);
                doc.DocumentMetadata(new DocumentMetadata { Author = "Vahid", Application = "PdfRpt", Keywords = "Test", Subject = "Test Rpt", Title = "Test" });
                doc.Compression(new CompressionSettings
                {
                    EnableCompression = true,
                    EnableFullCompression = true
                });
            })
             .DefaultFonts(fonts =>
             {
                 fonts.Path(System.IO.Path.Combine(Environment.GetEnvironmentVariable("SystemRoot"), "fonts\\arial.ttf"),
                            System.IO.Path.Combine(Environment.GetEnvironmentVariable("SystemRoot"), "fonts\\verdana.ttf"));
                 fonts.Size(9);
                 fonts.Color(System.Drawing.Color.Black);
             })
             .PagesFooter(footer =>
             {
                 footer.DefaultFooter(DateTime.Now.ToString("MM/dd/yyyy"));
             })
             .PagesHeader(header =>
             {
                 header.CacheHeader(cache: true); // It's a default setting to improve the performance.
                 header.CustomHeader(new GroupingHeaders { PdfRptFont = header.PdfFont });
             })
             .MainTableTemplate(template =>
             {
                 template.BasicTemplate(BasicTemplate.SilverTemplate);
             })
             .MainTablePreferences(table =>
             {
                 table.ColumnsWidthsType(TableColumnWidthType.Relative);
                 table.GroupsPreferences(new GroupsPreferences
                 {
                     GroupType = GroupType.HideGroupingColumns,
                     RepeatHeaderRowPerGroup = true,
                     ShowOneGroupPerPage = false,
                     SpacingBeforeAllGroupsSummary = 5f,
                     NewGroupAvailableSpacingThreshold = 150,
                     SpacingAfterAllGroupsSummary = 5f
                 });
                 table.SpacingAfter(4f);
             })
             .MainTableDataSource(dataSource =>
             {
                 var listOfRows = new List<Employee>();
                 var rnd = new Random();
                 for (int i = 0; i < 170; i++)
                 {
                     listOfRows.Add(
                         new Employee
                         {
                             Age = rnd.Next(25, 35),
                             Id = i + 1000,
                             Salary = rnd.Next(1000, 4000),
                             Name = "Employee " + i,
                             Department = "Department " + rnd.Next(1, 3)
                         });
                 }

                 listOfRows = listOfRows.OrderBy(x => x.Department).ThenBy(x => x.Age).ToList();
                 dataSource.StronglyTypedList(listOfRows);
             })
             .MainTableSummarySettings(summarySettings =>
             {
                 summarySettings.PreviousPageSummarySettings("Cont.");
                 summarySettings.OverallSummarySettings("Sum");
                 summarySettings.AllGroupsSummarySettings("Groups Sum");
             })
             .MainTableColumns(columns =>
             {
                 columns.AddColumn(column =>
                 {
                     column.PropertyName("rowNo");
                     column.IsRowNumber(true);
                     column.CellsHorizontalAlignment(HorizontalAlignment.Center);
                     column.IsVisible(true);
                     column.Order(0);
                     column.Width(20);
                     column.HeaderCell("#");
                 });

                 columns.AddColumn(column =>
                 {
                     column.PropertyName<Employee>(x => x.Department);
                     column.CellsHorizontalAlignment(HorizontalAlignment.Center);
                     column.Order(1);
                     column.Width(20);
                     column.HeaderCell("Department");
                     column.Group(
                     (val1, val2) =>
                     {
                         return val1.ToString() == val2.ToString();
                     });
                 });

                 columns.AddColumn(column =>
                 {
                     column.PropertyName<Employee>(x => x.Age);
                     column.CellsHorizontalAlignment(HorizontalAlignment.Center);
                     column.Order(2);
                     column.Width(20);
                     column.HeaderCell("Age");
                     column.Group(
                     (val1, val2) =>
                     {
                         return (int)val1 == (int)val2;
                     });
                 });

                 columns.AddColumn(column =>
                 {
                     column.PropertyName<Employee>(x => x.Id);
                     column.CellsHorizontalAlignment(HorizontalAlignment.Center);
                     column.IsVisible(true);
                     column.Order(3);
                     column.Width(20);
                     column.HeaderCell("Id");
                 });

                 columns.AddColumn(column =>
                 {
                     column.PropertyName<Employee>(x => x.Name);
                     column.CellsHorizontalAlignment(HorizontalAlignment.Center);
                     column.IsVisible(true);
                     column.Order(4);
                     column.Width(20);
                     column.HeaderCell("Name");
                 });

                 columns.AddColumn(column =>
                 {
                     column.PropertyName<Employee>(x => x.Salary);
                     column.CellsHorizontalAlignment(HorizontalAlignment.Center);
                     column.IsVisible(true);
                     column.Order(5);
                     column.Width(20);
                     column.HeaderCell("Salary");
                     column.ColumnItemsTemplate(template =>
                     {
                         template.TextBlock();
                         template.DisplayFormatFormula(obj => obj == null || string.IsNullOrEmpty(obj.ToString())
                                                            ? string.Empty : string.Format("{0:n0}", obj));
                     });
                     column.AggregateFunction(aggregateFunction =>
                     {
                         aggregateFunction.NumericAggregateFunction(AggregateFunction.Sum);
                         aggregateFunction.DisplayFormatFormula(obj => obj == null || string.IsNullOrEmpty(obj.ToString())
                                                            ? string.Empty : string.Format("{0:n0}", obj));
                     });
                 });
             })
             .MainTableEvents(events =>
             {
                 events.DataSourceIsEmpty(message: "There is no data available to display.");
                 events.GroupAdded(args =>
                     {
                         //args.PdfDoc.Add(new Phrase("\nGroup added event."));

                         /*var data = args.ColumnCellsSummaryData
                             .Where(data => data.CellData.PropertyName.Equals("propertyName")
                                    && data.GroupNumber == 1);*/

                         var salary = args.LastOverallAggregateValueOf<Employee>(x => x.Salary);
                         var table = new PdfGrid(1)
                         {
                             RunDirection = (int)PdfRunDirection.LeftToRight,
                             WidthPercentage = args.PageSetup.MainTablePreferences.WidthPercentage
                         };
                         var htmlCell = new XmlWorkerHelper
                         {
                             // the registered fonts (DefaultFonts section) should be specified here
                             Html = string.Format(@"<br/><span style='font-size:9pt;font-family:verdana;'>
                                                    <b>Group <i>added</i> event.</b>
                                                    Total Salary: {0}</span>", salary),
                             RunDirection = PdfRunDirection.LeftToRight,
                             CssFilesPath = null, // optional
                             ImagesPath = null, // optional
                             InlineCss = null, // optional
                             DefaultFont = args.PdfFont.Fonts[1] // verdana
                         }.RenderHtml();
                         htmlCell.Border = 0;
                         table.AddCell(htmlCell);
                         table.SpacingBefore = args.PageSetup.MainTablePreferences.SpacingBefore;

                         args.PdfDoc.Add(table);
                     });
             })
             .Export(export =>
             {
                 export.ToExcel();
             })
             .Generate(data => data.AsPdfFile(string.Format("{0}\\Pdf\\RptGroupingSample-{1}.pdf", AppPath.ApplicationPath, Guid.NewGuid().ToString("N"))));
        }
Пример #5
0
        // GET: Tablero
        public ActionResult Tablero(string lvl, int? areaId)
        {
            ApplicationUser usuario = (ApplicationUser)db.Users.FirstOrDefault(item => item.UserName == User.Identity.Name);
            int periodId = (int)Session["SelectedPeriod"];
            Periodo period = db.Periodos.Find(periodId);
            int nivel;
            Area area;

            if (lvl == null)
            {
                nivel = usuario.UsuarioArea.Nivel.ID;
            }
            else
            {
                nivel = int.Parse(lvl);
            }
            // Area
            if (areaId == null)
            {
                if (usuario.TienePermiso(1)) // Administrador
                {
                    area = db.Areas.First();
                }
                else
                {
                    area = usuario.UsuarioArea;
                }
                areaId = area.ID;
            }
            else
            {
                area = db.Areas.FirstOrDefault(item => item.ID == areaId);
            }
            ViewBag.CurrentArea = area;
            // Areas
            if (usuario.TieneNivel(1) || usuario.TienePermiso(1))
            {
                ViewBag.Areas = db.Areas.Where(item => item.Nivel.ID == nivel).ToList();
            }
            else if (usuario.TieneNivel(2))
            {
                if (nivel == 2)
                {
                    ViewBag.Areas = db.Areas.Where(item => item.ID == usuario.UsuarioArea.ID).ToList();
                }
                else if (nivel == 3)
                {
                    List<Area> Areas = new List<Area>();
                    List<int> areasId = new List<int>();

                    Areas = db.Areas.Where(item => item.Nivel.ID == nivel && item.AreaPadre.ID == usuario.UsuarioArea.ID).ToList();
                    areasId = (from a in Areas
                               select a.ID).ToList();
                    Areas.AddRange(db.Areas.Where(item => item.Nivel.ID == nivel && areasId.Any(p => item.AreaPadre.ID == p)).ToList());
                    areasId = (from a in Areas
                               select a.ID).ToList();
                    Areas.AddRange(db.Areas.Where(item => item.Nivel.ID == nivel && areasId.Any(p => item.AreaPadre.ID == p)).ToList());
                    ViewBag.Areas = Areas.Distinct().OrderBy(item => item.ID);
                }
            }
            else if (usuario.TienePermiso(6))
            {
                List<Area> Areas = new List<Area>();

                Areas.Add(usuario.UsuarioArea);
                Areas.AddRange(usuario.UsuarioArea.AreasHijas.ToList());
                ViewBag.Areas = Areas.OrderBy(item => item.AreaPadre.ID);
            }
            lvl = nivel.ToString();
            ViewBag.usuario = usuario;
            ViewBag.Nivel = lvl;
            ViewBag.PeriodoSeleccionado = period;

               /* int _nivel = 3;

            if (usuario.TieneNivel(1))
            {
                _nivel = 1;
            }

            if (usuario.TieneNivel(2))
            {
                _nivel = 2;
            }

            if (usuario.TieneNivel(3))
            {
                _nivel = 3;
            }*/

            List<NivelOrganizacional> Niveles = new List<NivelOrganizacional>();

            NivelOrganizacional Nivel_01 = db.NivelesOrganizacionales.Find(1);
            Niveles.Add(Nivel_01);
            NivelOrganizacional Nivel_02 = db.NivelesOrganizacionales.Find(2);
            Niveles.Add(Nivel_02);
            NivelOrganizacional Nivel_03 = db.NivelesOrganizacionales.Find(3);
            Niveles.Add(Nivel_03);
            ViewBag.Niveles = Niveles;

            //if (usuario.TieneNivel(1) || usuario.TienePermiso(1))
            //{
            //    return View(db.Indicadores.Where(item => item.Tipo.Nivel.ID == nivel && item.Periodos.Any(p => p.ID == periodId)).ToList());
            //}
            //if ((usuario.TieneNivel(2) && nivel == 2) || (usuario.TieneNivel(3) && nivel == 3))
            //{
            //    return View(db.Indicadores.Where(item => item.Tipo.Nivel.ID == nivel && item.Area.ID == usuario.UsuarioArea.ID && item.Periodos.Any(p => p.ID == periodId)).ToList());
            //}
            //if ((usuario.TieneNivel(3) && usuario.TienePermiso(8) && nivel == 2) || (usuario.TieneNivel(2) && usuario.TienePermiso(5) && nivel == 1))
            //{
            //    return View(db.Indicadores.Where(item => item.Tipo.Nivel.ID == nivel && item.Area.ID == usuario.UsuarioArea.AreaPadre.ID && item.Periodos.Any(p => p.ID == periodId)).ToList());
            //}
            return View(db.Indicadores.Where(item => item.Area.ID == areaId && item.Periodos.Any(p => p.ID == periodId)).ToList());
        }
Пример #6
0
        // GET: Proyectos
        public ActionResult Proyectos(int? areaId, int? tipoId)
        {
            ApplicationUser usuario = (ApplicationUser)db.Users.FirstOrDefault(item => item.UserName == User.Identity.Name);
            int periodId = (int)Session["SelectedPeriod"];
            Periodo period = db.Periodos.Find(periodId);
            Area area;
            TipoProyecto tipo;

            if (areaId == null)
            {
                if (usuario.TienePermiso(26) && usuario.TieneNivel(2))
                {
                    area = db.Areas.Where(item => item.Nivel.ID == 3 && item.AreaPadre.ID == usuario.UsuarioArea.ID).First();
                }
                if (usuario.TienePermiso(1) || (usuario.TienePermiso(26) && (usuario.TieneNivel(1)))) // Administrador y Presidente
                {
                    area = db.Areas.Where(item => item.Nivel.ID == 3).First();
                }
                else if (usuario.TieneNivel(3) && usuario.TienePermiso(6))
                {
                    area = usuario.UsuarioArea;
                }
                else
                {
                    area = usuario.UsuarioArea;
                }
                areaId = area.ID;
            }
            else
            {
                area = db.Areas.Where(item => item.Nivel.ID == 3).FirstOrDefault(item => item.ID == areaId);
            }
            if (tipoId == null)
            {
                tipo = db.TipoProyecto.FirstOrDefault();
                tipoId = tipo.ID;
            }
            else
            {
                tipo = db.TipoProyecto.Find(tipoId);
            }
            ViewBag.CurrentTipo = tipo;
            ViewBag.CurrentArea = area;
            if (usuario.TienePermiso(26) && usuario.TieneNivel(2))
            {
                List<Area> Areas = new List<Area>();
                List<int> areasId = new List<int>();

                Areas = db.Areas.Where(item => item.Nivel.ID == 3 && item.AreaPadre.ID == usuario.UsuarioArea.ID).ToList();
                areasId = (from a in Areas
                           select a.ID).ToList();
                Areas.AddRange(db.Areas.Where(item => item.Nivel.ID == 3 && areasId.Any(p => item.AreaPadre.ID == p)).ToList());
                areasId = (from a in Areas
                           select a.ID).ToList();
                Areas.AddRange(db.Areas.Where(item => item.Nivel.ID == 3 && areasId.Any(p => item.AreaPadre.ID == p)).ToList());
                ViewBag.Areas = Areas.Distinct().OrderBy(item => item.ID);
            }
            if (usuario.TienePermiso(1) || (usuario.TienePermiso(26) && (usuario.TieneNivel(1)))) // Administrador y Presidente
            {
                ViewBag.Areas = db.Areas.Where(item => item.Nivel.ID == 3).ToList();
            }
            if (usuario.TienePermiso(6) && usuario.TieneNivel(3))
            {
                List<Area> Areas = new List<Area>();

                Areas.Add(usuario.UsuarioArea);
                Areas.AddRange(usuario.UsuarioArea.AreasHijas.ToList());
                ViewBag.Areas = Areas.OrderBy(item => item.AreaPadre.ID);
            }
            ViewBag.Tipos = db.TipoProyecto.ToList();
            ViewBag.usuario = usuario;
            ViewBag.PeriodoSeleccionado = period;
            return View(db.Proyectos.Where(item => item.Tipo.ID == tipoId && item.Area.ID == areaId && item.Periodos.Any(p => p.ID == periodId)).ToList());
        }
Пример #7
0
        public void FillViewBagProyecto(Proyecto proyecto, int? areaId, int? tipoId)
        {
            ApplicationUser usuario = (ApplicationUser)db.Users.FirstOrDefault(item => item.UserName == User.Identity.Name);
            int periodId = (int)Session["SelectedPeriod"];
            Periodo period = db.Periodos.Find(periodId);
            JavaScriptSerializer serializer = new JavaScriptSerializer();
            TipoProyecto tipo;

            ViewBag.usuario = usuario;
            ViewBag.PeriodoSeleccionado = period;
            ViewBag.TipoProyecto = db.TipoProyecto.ToList();
            ViewBag.Fases = db.FasesProyecto.ToList();
            ViewBag.areaId = areaId;
            // Areas
            if (areaId != null)
            {
                ViewBag.Areas = db.Areas.Where(item => item.ID == areaId).ToList();
            }
            else if (usuario.TienePermiso(1)) // Administrador
            {
                ViewBag.Areas = db.Areas.Where(item => item.Nivel.ID == 3).OrderBy(item => item.AreaPadre.ID).ToList();
            }
            else if (usuario.TienePermiso(6) && usuario.TieneNivel(3)) // Lider Unidad Operativa y Nivel Unidad Operativa
            {
                List<Area> Areas = new List<Area>();

                Areas.Add(usuario.UsuarioArea);
                Areas.AddRange(usuario.UsuarioArea.AreasHijas.ToList());
                ViewBag.Areas = Areas.OrderBy(item => item.AreaPadre.ID);
            }
            else
            {
                List<Area> Areas = new List<Area>();

                Areas.Add(usuario.UsuarioArea);
                ViewBag.Areas = Areas;
            }
            // Tipos
            if (tipoId == null)
            {
                tipo = db.TipoProyecto.FirstOrDefault();
                tipoId = tipo.ID;
            }
            else
            {
                tipo = db.TipoProyecto.Find(tipoId);
            }
            ViewBag.CurrentTipo = tipo;
            // Proyecto
            List<ResumenEjecutivo> resumen = new List<ResumenEjecutivo>();

            for (var i = 1; i <= 12; i++)
            {
                resumen.Add(new ResumenEjecutivo()
                {
                    Mes = i,
                    Resumen = "",
                    Cerrado = DateTime.Now.Month == i ? false : true
                });
            }
            var resumen_json = from a in resumen
                               select new
                               {
                                   id = a.ID,
                                   mesId = a.Mes,
                                   mes = getMonthName(a.Mes),
                                   resumen = a.Resumen,
                                   mesCerrado = a.Cerrado,
                                   mesActual = DateTime.Now.Month
                               };
            ViewBag.Equipo = serializer.Serialize(new object[] { });
            ViewBag.Hitos = serializer.Serialize(new object[] { });
            ViewBag.Presupuesto = serializer.Serialize(new object[] { });
            ViewBag.Resumen = serializer.Serialize(resumen_json);
            if (proyecto != null)
            {
                if (proyecto.Equipo != null)
                {
                    var json_equipo = from a in proyecto.Equipo
                                      select new
                                      {
                                          id = a.ID,
                                          nombre = a.Nombre,
                                          rol = a.Rol,
                                          Eliminar = "<a href=\"javascript: $.noop();\" style=\"color:red\" class=\"fa fa-minus\"></a>"
                                      };
                    ViewBag.Equipo = serializer.Serialize(json_equipo);
                }
                if (proyecto.Hitos != null)
                {
                    var json_hitos = from a in proyecto.Hitos
                                     select new
                                     {
                                         id = a.ID,
                                         nombre = a.Nombre,
                                         faseId = a.Fase.ID.ToString(),
                                         fase = a.Fase.Nombre,
                                         fechacompromiso = a.FechaCompromiso.ToString("dd/MM/yyyy"),
                                         fechareal = a.FechaReal != null ? ((DateTime)a.FechaReal).ToString("dd/MM/yyyy") : "",
                                         ponderacion = a.Ponderacion,
                                         acumulado = a.Acumulado,
                                         status = "",
                                         Editar = "<a href=\"javascript: $.noop();\" style=\"color:green\" class=\"fa fa-edit\" data-toggle=\"modal\" data-target=\"#EditarHito\"></a>",
                                         Eliminar = "<a href=\"javascript: $.noop();\" style=\"color:red\" class=\"fa fa-minus\"></a>"
                                     };
                    ViewBag.Hitos = serializer.Serialize(json_hitos);
                }
                if (proyecto.Presupuesto != null)
                {
                    var json_prespuesto = from a in proyecto.Presupuesto
                                          select new
                                          {
                                              id = a.ID,
                                              mesId = a.Mes,
                                              mes = getMonthName(a.Mes),
                                              planeado = a.Planeado,
                                              asignado = a.Asignado,
                                              ejercido = a.Ejercido,
                                              Editar = "<a href=\"javascript: $.noop();\" style=\"color:green\" class=\"fa fa-edit\" data-toggle=\"modal\" data-target=\"#EditarPresupuesto\"></a>",
                                              Eliminar = "<a href=\"javascript: $.noop();\" style=\"color:red\" class=\"fa fa-minus\"></a>",
                                              presupuestoAsignadoCerrado = a.PresupuestoAsignadoCerrado,
                                              presupuestoEjercidoCerrado = a.PresupuestoEjercidoCerrado
                                          };
                    ViewBag.Presupuesto = serializer.Serialize(json_prespuesto);
                }
                if (proyecto.ResumenEjecutivo != null)
                {
                    var json_resumen = from a in proyecto.ResumenEjecutivo
                                       select new
                                       {
                                           id = a.ID,
                                           mesId = a.Mes,
                                           mes = getMonthName(a.Mes),
                                           resumen = a.Resumen,
                                           mesCerrado = a.Cerrado,
                                           mesActual = DateTime.Now.Month
                                       };
                    ViewBag.Resumen = serializer.Serialize(json_resumen);
                }
            }
        }
Пример #8
0
        public bool WritePdf(string fpath, ParametersViewModel parametersViewModel, CUSTOMER_INFO customerInfo, 
            List<GLNODES> glnodess, List<FACILITIES> facilitiess, List<MM_CONTRACT_RETRIEVAL> mmContractRetrievals,
            List<GUARANTOR> guarantors, string[] accounts, List<LD_KEN> ldKens, List<SECURITIES> securitiess, string loggedUser, string addres,string charge)
        {
            //var imageDir = fpath + "/Images/bg-marketing-banner.jpg";
             Regex r = new Regex("(?:[^a-z0-9 ]|(?<=['\"])s)", RegexOptions.IgnoreCase | RegexOptions.CultureInvariant | RegexOptions.Compiled);
             var filename = r.Replace(customerInfo.CUSTOMER_NAME, String.Empty);
             var directory = fpath + "/PDFs/" + filename;
             var appRootDir = fpath + "/PDFs/" + filename + "/" + filename + "_" + parametersViewModel.ReportDate.ToString("dd_MMM_yyyy") + ".pdf";
            try
            {

                if (!Directory.Exists(directory))
                {
                    Directory.CreateDirectory(directory);
                }
                if (File.Exists(appRootDir))
                    File.Delete(appRootDir);
                //Font Definition
                var normalFont = FontFactory.GetFont(FontFactory.TIMES_ROMAN, 8);
                var boldFont = FontFactory.GetFont(FontFactory.HELVETICA_BOLD, 9);
                var underLine = FontFactory.GetFont(FontFactory.HELVETICA_BOLD, 9, Font.UNDERLINE);
                //Fetching Needed Data
                //var acc = _repository.Fetch<GLNODES>().Any(p => p.ACCOUNT_N0 == accounts.ToString());

                var addressDetails = _repository.Find<AUDITORADDRESS>(parametersViewModel.AddressId);
                var auditorDetails = _repository.Find<AUDITOR>(addressDetails.AuditorId);
                var salutaion = _repository.Fetch<SALUTATION>().FirstOrDefault(p=> p.DefaultActive)  ??
                    _repository.Fetch<SALUTATION>().FirstOrDefault() ;
                var signature = _repository.Fetch<SIGNATURES>().FirstOrDefault(p => p.DefaultActive) ??
                    _repository.Fetch<SIGNATURES>().FirstOrDefault();

                Image signatureImage = default(iTextSharp.text.Image);
                signatureImage = iTextSharp.text.Image.GetInstance(signature.Signimage);
                signatureImage.ScaleAbsolute(60f, 40f);

                var defaultParameters = _repository.Fetch<Parameter>();
                // Creating System.IO.FileStream object
                using (var fs = new FileStream(appRootDir, FileMode.Create, FileAccess.Write, FileShare.None))
                    // Creating iTextSharp.text.Document object
                using (var doc = new Document())
                {
                    doc.SetMargins(doc.LeftMargin, doc.RightMargin, doc.TopMargin + 80, doc.BottomMargin + 60);
                    // Creating iTextSharp.text.pdf.PdfWriter object
                    // It helps to write the Document to the Specified FileStream
                    using (var writer = PdfWriter.GetInstance(doc, fs))
                    {
                        //Set Header & Footer Using Page Events with the above class
                        writer.PageEvent = new PdfHeaderFooter();
                        writer.AddViewerPreference(PdfName.HIDEMENUBAR, new PdfBoolean(true));
                        writer.ViewerPreferences = PdfWriter.HideMenubar;
                        // Openning the Document
                        doc.Open();
                        // Adding a paragraph
                        // NOTE: When we want to insert text, then we've to do it through creating paragraph
                        doc.NewPage();
                        var prSpace = new Paragraph("\n");
                        var pr1 = new Paragraph(String.Format("{0:MMMM d, yyyy}", DateTime.Now), normalFont);
                        var pr2 = new Paragraph(auditorDetails.AuditorName, normalFont);
                        var pr3 = new Paragraph(addressDetails.Address1, normalFont);
                        var pr4 = new Paragraph(addressDetails.Address2, normalFont);
                        var pr5 = new Paragraph(addressDetails.Address3, normalFont);
                        var pr6 = new Paragraph(addressDetails.Address4, normalFont);

                        var pr7 = new Paragraph(salutaion.SalutationDescription, normalFont);
                        var pr8 = new Paragraph("RE: " + customerInfo.CUSTOMER_NAME, underLine);
                        var pr9 = new Paragraph(Parameters("LETTERINTRO").Paramvalue + " " + parametersViewModel.ReportDate.ToString("dd MMM, yyyy") + ".", normalFont);

                        //Account Balances Section
                        var pr10 = new Paragraph(Parameters("GLNODES").Paramvalue, underLine);
                        var glnodesTable = new PdfPTable(4) { WidthPercentage = 100 };
                        var widths = new float[] { 20f, 8f, 70f, 19f };
                        glnodesTable.SetWidths(widths);

                        var cell1 = new PdfPCell(new Phrase("Account Number", boldFont))
                        {
                            BackgroundColor = BaseColor.LIGHT_GRAY,
                            Colspan = 1
                        };
                        glnodesTable.AddCell(cell1);

                        var cell2 = new PdfPCell(new Phrase("CCY", boldFont))
                        {
                            BackgroundColor = BaseColor.LIGHT_GRAY,
                            Colspan = 1
                        };
                        glnodesTable.AddCell(cell2);

                        var cell3 = new PdfPCell(new Phrase("Account Description", boldFont))
                        {
                            BackgroundColor = BaseColor.LIGHT_GRAY,
                            Colspan = 1
                        };
                        glnodesTable.AddCell(cell3);

                        var cell4 = new PdfPCell(new Phrase("Balance", boldFont))
                        {
                            BackgroundColor = BaseColor.LIGHT_GRAY,
                            Colspan = 1
                        };
                        cell4.HorizontalAlignment = Element.ALIGN_RIGHT;
                        glnodesTable.AddCell(cell4);

                        foreach (var n in glnodess)
                        {
                            var cell5 = new PdfPCell(new Phrase(n.ACCOUNT_N0, normalFont))
                            {
                                Colspan = 1
                            };
                            glnodesTable.AddCell(cell5);

                            var cell6 = new PdfPCell(new Phrase(n.CCY, normalFont))
                            {
                                Colspan = 1
                            };
                            glnodesTable.AddCell(cell6);

                            var cell7 = new PdfPCell(new Phrase(n.AC_DESC, normalFont))
                            {
                                Colspan = 1
                            };
                            glnodesTable.AddCell(cell7);

                            var txnType = n.CURRENT_LCY_BAL.Contains("-") ? " DR" : " CR";
                            var amt = n.CCY.ToUpper().Trim() == "KES" ? n.CURRENT_LCY_BAL : n.FCY_BALANCE;
                            var cell8 = new PdfPCell(new Phrase(amt.Replace("-", "") + txnType, normalFont))
                            {
                                Colspan = 1
                            };
                            cell8.HorizontalAlignment = Element.ALIGN_RIGHT;
                            glnodesTable.AddCell(cell8);

                        }
                        //Facilities Section
                        var pr11 = new Paragraph(Parameters("FACILITIES").Paramvalue, underLine);
                        var facilitiesTable = new PdfPTable(5) { WidthPercentage = 100 };
                        var facilitiesWidths = new float[] { 70f, 50f, 8f, 19f, 18f };
                        facilitiesTable.SetWidths(facilitiesWidths);

                        var fcell1 = new PdfPCell(new Phrase("Facilities Description", boldFont))
                        {
                            BackgroundColor = BaseColor.LIGHT_GRAY,
                            Colspan = 1
                        };
                        facilitiesTable.AddCell(fcell1);

                        var fcell2 = new PdfPCell(new Phrase("Exposure Category", boldFont))
                        {
                            BackgroundColor = BaseColor.LIGHT_GRAY,
                            Colspan = 1
                        };
                        facilitiesTable.AddCell(fcell2);

                        var fcellnew = new PdfPCell(new Phrase("CCY", boldFont))
                        {
                            BackgroundColor = BaseColor.LIGHT_GRAY,
                            Colspan = 1
                        };
                        facilitiesTable.AddCell(fcellnew);

                        var fcell3 = new PdfPCell(new Phrase("Maximum Limit", boldFont))
                        {
                            BackgroundColor = BaseColor.LIGHT_GRAY,
                            Colspan = 1
                        };
                        fcell3.HorizontalAlignment = Element.ALIGN_RIGHT;
                        facilitiesTable.AddCell(fcell3);

                        var fcell4 = new PdfPCell(new Phrase("Tenor", boldFont))
                        {
                            BackgroundColor = BaseColor.LIGHT_GRAY,
                            Colspan = 1
                        };
                        facilitiesTable.AddCell(fcell4);

                        foreach (var k in facilitiess)
                        {
                            var fcell5 = new PdfPCell(new Phrase(k.FACILITY_DESCRIPTION, normalFont))
                            {
                                Colspan = 1
                            };
                            facilitiesTable.AddCell(fcell5);

                            var fcell6 = new PdfPCell(new Phrase(k.EXPOSURE_CATEGORY, normalFont))
                            {
                                Colspan = 1
                            };
                            facilitiesTable.AddCell(fcell6);

                            var fcell9 = new PdfPCell(new Phrase(k.CURRENCY.ToUpper(), normalFont))
                            {
                                Colspan = 1
                            };
                            facilitiesTable.AddCell(fcell9);

                            var formatAmt = decimal.Parse(k.AVAILABLE_CCY_AMOUNT);
                            var fcell7 = new PdfPCell(new Phrase(String.Format("{0:C}", formatAmt).Replace("$", ""), normalFont))
                            {
                                Colspan = 1
                            };
                            fcell7.HorizontalAlignment = Element.ALIGN_RIGHT;
                            facilitiesTable.AddCell(fcell7);

                            string tenor = "";
                            if (k.MAX_TENOR_YEARS != null)
                                tenor = k.MAX_TENOR_YEARS.Trim() == "1" ? k.MAX_TENOR_YEARS.Trim() + " Year " : k.MAX_TENOR_YEARS.Trim() + " Years ";
                            else if (k.MAX_TENOR_MONTHS != null)
                                tenor = k.MAX_TENOR_MONTHS.Trim() == "1" ? tenor + k.MAX_TENOR_MONTHS.Trim() + " Month " : tenor + k.MAX_TENOR_MONTHS.Trim() + " Months ";
                            else if (k.MAX_TENOR_DAYS != null)
                                tenor = k.MAX_TENOR_DAYS.Trim() == "1" ? tenor + k.MAX_TENOR_DAYS.Trim() + " Day" : tenor + k.MAX_TENOR_DAYS.Trim() + " Days";

                            var fcell8 = new PdfPCell(new Phrase(tenor.Trim() == "" ? "Exp. " + k.EXPIRY_DATE_: tenor, normalFont))
                            {
                                Colspan = 1
                            };
                            facilitiesTable.AddCell(fcell8);
                        }

                        //MM Section For Oustanding Deposits
                        var pr12 = new Paragraph(Parameters("MM_CONTRACT_RETRIEVAL").Paramvalue, underLine);
                        var mmTable = new PdfPTable(7) { WidthPercentage = 100 };
                        var mmWidths = new float[] { 20f, 20f, 20f, 8f, 18f, 10f, 19f };
                        mmTable.SetWidths(mmWidths);

                        //Header Cells
                        var mcell1 = new PdfPCell(new Phrase("Reference", boldFont))
                        {
                            BackgroundColor = BaseColor.LIGHT_GRAY,
                            Colspan = 1
                        };
                        mmTable.AddCell(mcell1);

                        var mcell2 = new PdfPCell(new Phrase("Value Date", boldFont))
                        {
                            BackgroundColor = BaseColor.LIGHT_GRAY,
                            Colspan = 1
                        };
                        mmTable.AddCell(mcell2);

                        var mcell3 = new PdfPCell(new Phrase("Maturity Date", boldFont))
                        {
                            BackgroundColor = BaseColor.LIGHT_GRAY,
                            Colspan = 1
                        };
                        mmTable.AddCell(mcell3);

                        var mcell4 = new PdfPCell(new Phrase("CCY", boldFont))
                        {
                            BackgroundColor = BaseColor.LIGHT_GRAY,
                            Colspan = 1
                        };
                        mmTable.AddCell(mcell4);

                        var mcell5 = new PdfPCell(new Phrase("Amount", boldFont))
                        {
                            BackgroundColor = BaseColor.LIGHT_GRAY,
                            Colspan = 1
                        };
                        mcell5.HorizontalAlignment = Element.ALIGN_RIGHT;
                        mmTable.AddCell(mcell5);

                        var mcell6 = new PdfPCell(new Phrase("Rate", boldFont))
                        {
                            BackgroundColor = BaseColor.LIGHT_GRAY,
                            Colspan = 1
                        };
                        mmTable.AddCell(mcell6);

                        var mcell7 = new PdfPCell(new Phrase("Accrued Interest", boldFont))
                        {
                            BackgroundColor = BaseColor.LIGHT_GRAY,
                            Colspan = 1
                        };
                        mcell7.HorizontalAlignment = Element.ALIGN_RIGHT;
                        mmTable.AddCell(mcell7);

                        foreach (var q in mmContractRetrievals)
                        {
                            var mcell8 = new PdfPCell(new Phrase(q.CONTRACT_REF_NO, normalFont))
                            {
                                Colspan = 1
                            };
                            mmTable.AddCell(mcell8);

                            var mcell9 = new PdfPCell(new Phrase(q.VALUE_DATE, normalFont))
                            {
                                Colspan = 1
                            };
                            mmTable.AddCell(mcell9);
                            var mcell10 = new PdfPCell(new Phrase(string.IsNullOrEmpty(q.MATURITY_DATE) ? " ON CALL " : q.MATURITY_DATE, normalFont))
                            {
                                Colspan = 1
                            };
                            mmTable.AddCell(mcell10);

                            var mcell11 = new PdfPCell(new Phrase(q.CURRENCY, normalFont))
                            {
                                Colspan = 1
                            };
                            mmTable.AddCell(mcell11);
                            var amt = decimal.Parse(q.PRINCIPAL_AMOUNT);
                            var mcell12 = new PdfPCell(new Phrase(String.Format("{0:C}", amt).Replace("$", ""), normalFont))
                            {
                                Colspan = 1
                            };
                            mcell12.HorizontalAlignment = Element.ALIGN_RIGHT;
                            mmTable.AddCell(mcell12);

                            var mcell13 = new PdfPCell(new Phrase(q.INT_RATE, normalFont))
                            {
                                Colspan = 1
                            };
                            mmTable.AddCell(mcell13);

                            var dayBasis = q.CURRENCY.ToUpper() == "USD" || q.CURRENCY.ToUpper() == "EUR" ? 360 : 365;
                            var myAccrued = Convert.ToDouble(q.PRINCIPAL_AMOUNT) * Convert.ToDouble(q.INT_RATE) /
                                            100 *
                                            (parametersViewModel.ReportDate - DateTime.ParseExact(q.VALUE_DATE, "dd/MM/yyyy", CultureInfo.InvariantCulture)).TotalDays /
                                            dayBasis;
                            var finAmt = Math.Round(myAccrued, 2);
                            var mcell14 = new PdfPCell(new Phrase(String.Format("{0:C}", finAmt).Replace("$", ""), normalFont))
                            {
                                Colspan = 1
                            };
                            mcell14.HorizontalAlignment = Element.ALIGN_RIGHT;
                            mmTable.AddCell(mcell14);
                        }

                        //Oustanding Loans LD_KEN. I hade made the rest Earlier so there is slight naming change of controls coz am feeling lazy to change wht i had done
                        var pr15 = new Paragraph(Parameters("LDKEN").Paramvalue, underLine);
                        var ldKenTable = new PdfPTable(6) { WidthPercentage = 100 };
                        var ldKenWidths = new float[] { 20f, 20f, 20f, 8f, 18f, 10f };
                        ldKenTable.SetWidths(ldKenWidths);

                        //Header Cells
                        var ldcell1 = new PdfPCell(new Phrase("Reference", boldFont))
                        {
                            BackgroundColor = BaseColor.LIGHT_GRAY,
                            Colspan = 1
                        };
                        ldKenTable.AddCell(ldcell1);

                        var ldcell2 = new PdfPCell(new Phrase("Value Date", boldFont))
                        {
                            BackgroundColor = BaseColor.LIGHT_GRAY,
                            Colspan = 1
                        };
                        ldKenTable.AddCell(ldcell2);

                        var ldcell3 = new PdfPCell(new Phrase("Maturity Date", boldFont))
                        {
                            BackgroundColor = BaseColor.LIGHT_GRAY,
                            Colspan = 1
                        };
                        ldKenTable.AddCell(ldcell3);

                        var ldcell4 = new PdfPCell(new Phrase("CCY", boldFont))
                        {
                            BackgroundColor = BaseColor.LIGHT_GRAY,
                            Colspan = 1
                        };
                        ldKenTable.AddCell(ldcell4);

                        var ldcell5 = new PdfPCell(new Phrase("Amount", boldFont))
                        {
                            BackgroundColor = BaseColor.LIGHT_GRAY,
                            Colspan = 1
                        };
                        ldcell5.HorizontalAlignment = Element.ALIGN_RIGHT;
                        ldKenTable.AddCell(ldcell5);

                        var ldcell6 = new PdfPCell(new Phrase("Rate", boldFont))
                        {
                            BackgroundColor = BaseColor.LIGHT_GRAY,
                            Colspan = 1
                        };
                        ldKenTable.AddCell(ldcell6);

                        foreach (var l in ldKens.OrderBy(p => p.CONTRACT_REF_NO))
                        {
                            var ldcell7 = new PdfPCell(new Phrase(l.CONTRACT_REF_NO, normalFont))
                            {
                                Colspan = 1
                            };
                            ldKenTable.AddCell(ldcell7);

                            var ldcell8 = new PdfPCell(new Phrase(l.VALUE_DATE, normalFont))
                            {
                                Colspan = 1
                            };
                            ldKenTable.AddCell(ldcell8);
                            var ldcell9 = new PdfPCell(new Phrase(string.IsNullOrEmpty(l.MATURITY_DATE) ? " ON CALL " : l.MATURITY_DATE, normalFont))
                            {
                                Colspan = 1
                            };
                            ldKenTable.AddCell(ldcell9);

                            var ldcell10 = new PdfPCell(new Phrase(l.CURRENCY, normalFont))
                            {
                                Colspan = 1
                            };
                            ldKenTable.AddCell(ldcell10);

                            var ldcell11 = new PdfPCell(new Phrase(l.PRINCIPAL_OUTSTANDING, normalFont))
                            {
                                Colspan = 1
                            };
                            ldcell11.HorizontalAlignment = Element.ALIGN_RIGHT;
                            ldKenTable.AddCell(ldcell11);

                            var ldcell12 = new PdfPCell(new Phrase(l.RATE, normalFont))
                            {
                                Colspan = 1
                            };
                            ldKenTable.AddCell(ldcell12);
                        }

                        //Securities Section
                        var pr16 = new Paragraph(Parameters("SECURITIES").Paramvalue, underLine);
                        var scTable = new PdfPTable(6) { WidthPercentage = 100 };
                        var scWidths = new float[] { 45f, 20f, 20f, 60f, 9f, 19f };
                        scTable.SetWidths(scWidths);

                        //Header Cells
                        var sccell1 = new PdfPCell(new Phrase("Doc Description", boldFont))
                        {
                            BackgroundColor = BaseColor.LIGHT_GRAY,
                            Colspan = 1
                        };
                        scTable.AddCell(sccell1);

                        var sccell2 = new PdfPCell(new Phrase("Doc Date", boldFont))
                        {
                            BackgroundColor = BaseColor.LIGHT_GRAY,
                            Colspan = 1
                        };
                        scTable.AddCell(sccell2);

                        var sccell3 = new PdfPCell(new Phrase("Expiry Date", boldFont))
                        {
                            BackgroundColor = BaseColor.LIGHT_GRAY,
                            Colspan = 1
                        };
                        scTable.AddCell(sccell3);

                        var sccell4 = new PdfPCell(new Phrase("Item Details", boldFont))
                        {
                            BackgroundColor = BaseColor.LIGHT_GRAY,
                            Colspan = 1
                        };
                        scTable.AddCell(sccell4);

                        var sccell5 = new PdfPCell(new Phrase("CCY", boldFont))
                        {
                            BackgroundColor = BaseColor.LIGHT_GRAY,
                            Colspan = 1
                        };
                        scTable.AddCell(sccell5);

                        var sccell6 = new PdfPCell(new Phrase("Amount", boldFont))
                        {
                            BackgroundColor = BaseColor.LIGHT_GRAY,
                            Colspan = 1
                        };
                        sccell6.HorizontalAlignment = Element.ALIGN_RIGHT;
                        scTable.AddCell(sccell6);

                        foreach (var s in securitiess)
                        {
                            var sccell7 = new PdfPCell(new Phrase(s.DOC_DESCRIPTION, normalFont))
                            {
                                Colspan = 1
                            };
                            scTable.AddCell(sccell7);

                            var sccell8 = new PdfPCell(new Phrase(Convert.ToDateTime(s.DOC_DATE).ToString("dd/MMM/yyyy"), normalFont))
                            {
                                Colspan = 1
                            };
                            scTable.AddCell(sccell8);

                            var sccell9 = new PdfPCell(new Phrase(s.DOC_EXPIRY_DATE, normalFont))
                            {
                                Colspan = 1
                            };
                            scTable.AddCell(sccell9);

                            var sccell10 = new PdfPCell(new Phrase(s.ITEM_DETAILS.ToUpper(), normalFont))
                            {
                                Colspan = 1
                            };
                            scTable.AddCell(sccell10);

                            var sccell11 = new PdfPCell(new Phrase(s.CCY, normalFont))
                            {
                                Colspan = 1
                            };
                            scTable.AddCell(sccell11);

                            var formatAmt = s.AMOUNT ?? "0";
                            var sccell12 = new PdfPCell(new Phrase(String.Format("{0:C}", decimal.Parse(formatAmt)).Replace("$", ""), normalFont))
                            {
                                Colspan = 1
                            };
                            sccell12.HorizontalAlignment = Element.ALIGN_RIGHT;
                            scTable.AddCell(sccell12);
                        }

                        //Guarantors Section
                        var pr13 = new Paragraph(Parameters("GUARANTOR").Paramvalue, underLine);
                        var gtTable = new PdfPTable(5) { WidthPercentage = 100 };
                        var gtWidths = new float[] { 30f, 8f, 19f, 20f, 50f };
                        gtTable.SetWidths(gtWidths);

                        //Header Cells
                        var gtcell1 = new PdfPCell(new Phrase("Reference", boldFont))
                        {
                            BackgroundColor = BaseColor.LIGHT_GRAY,
                            Colspan = 1
                        };
                        gtTable.AddCell(gtcell1);

                        var gtcell2 = new PdfPCell(new Phrase("CCY", boldFont))
                        {
                            BackgroundColor = BaseColor.LIGHT_GRAY,
                            Colspan = 1
                        };
                        gtTable.AddCell(gtcell2);

                        var gtcell3 = new PdfPCell(new Phrase("Amount", boldFont))
                        {
                            BackgroundColor = BaseColor.LIGHT_GRAY,
                            Colspan = 1
                        };
                        gtcell3.HorizontalAlignment = Element.ALIGN_RIGHT;
                        gtTable.AddCell(gtcell3);

                        var gtcell4 = new PdfPCell(new Phrase("Expiry Date", boldFont))
                        {
                            BackgroundColor = BaseColor.LIGHT_GRAY,
                            Colspan = 1
                        };
                        gtTable.AddCell(gtcell4);

                        var gtcell5 = new PdfPCell(new Phrase("Beneficiary", boldFont))
                        {
                            BackgroundColor = BaseColor.LIGHT_GRAY,
                            Colspan = 1
                        };
                        gtTable.AddCell(gtcell5);

                        foreach (var x in guarantors)
                        {
                            var gtcell6 = new PdfPCell(new Phrase(x.OUR_REF_NUM, normalFont))
                            {
                                Colspan = 1
                            };
                            gtTable.AddCell(gtcell6);

                            var gtcell7 = new PdfPCell(new Phrase(x.TXN_CCY, normalFont))
                            {
                                Colspan = 1
                            };
                            gtTable.AddCell(gtcell7);

                            var formatAmt = x.OST_AMOUNT_ ?? "0";
                            var gtcell8 = new PdfPCell(new Phrase(String.Format("{0:C}", decimal.Parse(formatAmt)).Replace("$", ""), normalFont))
                            {
                                Colspan = 1
                            };
                            gtcell8.HorizontalAlignment = Element.ALIGN_RIGHT;
                            gtTable.AddCell(gtcell8);

                            var gtcell9 = new PdfPCell(new Phrase(Convert.ToDateTime(x.EXPIRY_DATE).ToString("dd/MMM/yyyy"), normalFont))
                            {
                                Colspan = 1
                            };
                            gtTable.AddCell(gtcell9);

                            var gtcell10 = new PdfPCell(new Phrase(x.BENE_NAME, normalFont))
                            {
                                Colspan = 1
                            };
                            gtTable.AddCell(gtcell10);
                        }

                        //Signatories Section
                        var pr14 = new Paragraph(Parameters("SIGNATORIES").Paramvalue, underLine);
                        var sigTable = new PdfPTable(2) { WidthPercentage = 100 };
                        var sigWidths = new float[] { 30f, 50f };
                        sigTable.SetWidths(sigWidths);
                        var sigWritten = false;
                        var sigcell1 = new PdfPCell(new Phrase("Account Number", boldFont))
                        {
                            BackgroundColor = BaseColor.LIGHT_GRAY,
                            Colspan = 1
                        };
                        sigTable.AddCell(sigcell1);

                        var sigcell2 = new PdfPCell(new Phrase("Signatory Name & Title", boldFont))
                        {
                            BackgroundColor = BaseColor.LIGHT_GRAY,
                            Colspan = 1
                        };
                        sigTable.AddCell(sigcell2);

                        foreach (var s in accounts)
                        {
                            if (IfThereIsSignatories(s))
                            {
                                sigWritten = true;
                                var sigcell3 = new PdfPCell(new Phrase(s, normalFont))
                                {
                                    Colspan = 1
                                };
                                sigTable.AddCell(sigcell3);

                                foreach (var y in SignatoriesAcc(s, parametersViewModel.ReportDate))
                                {
                                    var sigcell4 = new PdfPCell(new Phrase(y.CIF_SIG_NAME + " - " + y.CIF_SIG_TITLE, normalFont))
                                    {
                                        Colspan = 1
                                    };
                                    sigTable.AddCell(sigcell4);

                                    var sigcell5 = new PdfPCell(new Phrase(" ", normalFont))
                                    {
                                        Colspan = 1
                                    };
                                    sigTable.AddCell(sigcell5);
                                }
                                var sigcell6 = new PdfPCell(new Phrase(" ", normalFont))
                                {
                                    Colspan = 1
                                };
                                sigTable.AddCell(sigcell6);
                            }
                        }

                        //Letter Head

                        doc.Add(pr1);
                        doc.Add(prSpace);
                        doc.Add(pr2);
                        doc.Add(pr3);
                        doc.Add(pr4);
                        doc.Add(pr5);
                        doc.Add(pr6);
                        doc.Add(prSpace);
                        doc.Add(pr7);
                        doc.Add(prSpace);
                        doc.Add(pr8);
                        doc.Add(prSpace);
                        doc.Add(pr9);
                        doc.Add(prSpace);

                        //         List<GLNODES> glnodess, List<FACILITIES> facilitiess, List<MM_CONTRACT_RETRIEVAL> mmContractRetrievals,
                        //List<GUARANTOR> guarantors, List<SIGNATORIES> signatoriess, List<LD_KEN> ldKens, List<SECURITIES> securitiess

                        //Account Balances
                        if (glnodess.Count > 0)
                        {
                            doc.Add(pr10);
                            doc.Add(prSpace);
                            doc.Add(glnodesTable);
                            doc.Add(prSpace);
                        }
                        //Facilities
                        if (facilitiess.Count > 0)
                        {
                            doc.Add(pr11);
                            doc.Add(prSpace);
                            doc.Add(facilitiesTable);
                            doc.Add(prSpace);
                        }

                        //Deposits
                        if (mmContractRetrievals.Count > 0)
                        {
                            doc.Add(pr12);
                            doc.Add(prSpace);
                            doc.Add(mmTable);
                            doc.Add(prSpace);
                        }

                        //Loans
                        if (ldKens.Count > 0)
                        {
                            doc.Add(pr15);
                            doc.Add(prSpace);
                            doc.Add(ldKenTable);
                            doc.Add(prSpace);
                            if (parametersViewModel.Rate != "")
                                doc.Add(new Paragraph("Loan Rate is " + parametersViewModel.Rate + "%", normalFont));
                            doc.Add(prSpace);
                        }

                        //Securities
                        if (securitiess.Count > 0)
                        {
                            doc.Add(pr16);
                            doc.Add(prSpace);
                            doc.Add(scTable);
                            doc.Add(prSpace);
                        }

                        //Guarantors
                        if (guarantors.Count > 0)
                        {
                            doc.Add(pr13);
                            doc.Add(prSpace);
                            doc.Add(gtTable);
                            doc.Add(prSpace);
                        }

                        //Signatories
                        if (sigWritten)
                        {
                            doc.Add(pr14);
                            doc.Add(prSpace);
                            doc.Add(sigTable);
                            doc.Add(prSpace);
                        }

                        var outroTable = new PdfPTable(1) { WidthPercentage = 100 };
                        PdfPCell cell;
                        cell = new PdfPCell(new Paragraph(Parameters("LETTEROUTRO").Paramvalue, normalFont));
                        cell.HorizontalAlignment = Element.ALIGN_LEFT;
                        cell.Border = PdfPCell.NO_BORDER;
                        outroTable.AddCell(cell);
                        cell = new PdfPCell(new Paragraph(prSpace));
                        cell.HorizontalAlignment = Element.ALIGN_LEFT;
                        cell.Border = PdfPCell.NO_BORDER;
                        outroTable.AddCell(cell);
                        cell = new PdfPCell(signatureImage);
                        cell.HorizontalAlignment = Element.ALIGN_LEFT;
                        cell.Border = PdfPCell.NO_BORDER;
                        outroTable.AddCell(cell);
                        cell = new PdfPCell(new Paragraph(prSpace));
                        cell.HorizontalAlignment = Element.ALIGN_LEFT;
                        cell.Border = PdfPCell.NO_BORDER;
                        outroTable.AddCell(cell);

                        cell = new PdfPCell(new Paragraph(signature.Signname, normalFont));
                        cell.HorizontalAlignment = Element.ALIGN_LEFT;
                        cell.Border = PdfPCell.NO_BORDER;
                        outroTable.AddCell(cell);

                        //cell = new PdfPCell(new Paragraph(prSpace));
                        //cell.HorizontalAlignment = Element.ALIGN_LEFT;
                        //cell.Border = PdfPCell.NO_BORDER;
                        //outroTable.AddCell(cell);

                        cell = new PdfPCell(new Paragraph(signature.Signtitle, normalFont));
                        cell.HorizontalAlignment = Element.ALIGN_LEFT;
                        cell.Border = PdfPCell.NO_BORDER;
                        outroTable.AddCell(cell);

                        cell = new PdfPCell(new Paragraph(prSpace));
                        cell.HorizontalAlignment = Element.ALIGN_LEFT;
                        cell.Border = PdfPCell.NO_BORDER;
                        outroTable.AddCell(cell);

                        cell = new PdfPCell(new Paragraph(prSpace));
                        cell.HorizontalAlignment = Element.ALIGN_LEFT;
                        cell.Border = PdfPCell.NO_BORDER;
                        outroTable.AddCell(cell);
                        cell = new PdfPCell(new Paragraph("CC  " + customerInfo.CUSTOMER_NAME, normalFont));
                        cell.HorizontalAlignment = Element.ALIGN_LEFT;
                        cell.Border = PdfPCell.NO_BORDER;
                        outroTable.AddCell(cell);
                        cell = new PdfPCell(new Paragraph("     " + customerInfo.ADDRESS_LINE_1, normalFont));
                        cell.HorizontalAlignment = Element.ALIGN_LEFT;
                        cell.Border = PdfPCell.NO_BORDER;
                        outroTable.AddCell(cell);
                        cell = new PdfPCell(new Paragraph("     " + customerInfo.ADDRESS_LINE_2, normalFont));
                        cell.HorizontalAlignment = Element.ALIGN_LEFT;
                        cell.Border = PdfPCell.NO_BORDER;
                        outroTable.AddCell(cell);
                        outroTable.KeepTogether = true;

                        doc.Add(outroTable);

                        //Letter Outro ....yes am using album synonames

                        // Closing the Document
                        doc.Close();
                        //After This we Log the Report and hide the Download Location
                        var ccy =
                            _repository.Fetch<GLNODES>()
                                .Where(p => p.ACCOUNT_N0==charge).Select(n=>n.CCY);
               //                     var acc1 =
               //                        _repository.Fetch<GLNODES>()
               //                            .Where(p => accounts.Contains(p.ACCOUNT_N0) && p.CCY == "KES");
               //                     var acc2 =
               //_repository.Fetch<GLNODES>()
               //    .Where(p => accounts.Contains(p.ACCOUNT_N0) && p.CCY == "USD");
               //                     //var ccy = acc.Select(p => p.CCY);
               //                     foreach (var n in acc.ToList())
               //                     {
               //                         if (n.CCY == "KES")
               //                         {
               //                             return SaveGeneratedReport(appRootDir, parametersViewModel.ReportDate, loggedUser,
               //                                 addressDetails.Email, fpath, addres, acc1
               //                                     .Select(m => m.ACCOUNT_N0).FirstOrDefault());
               //                         }
               //                         if (n.CCY == "USD")
               //                         {
               //                             return SaveGeneratedReport(appRootDir, parametersViewModel.ReportDate, loggedUser,
               //                                 addressDetails.Email, fpath, addres, acc2
               //                                     .Select(m => m.ACCOUNT_N0).FirstOrDefault());
               //                         }
               //                     }
                        return SaveGeneratedReport(appRootDir, parametersViewModel.ReportDate, loggedUser,
                                    addressDetails.Email, fpath, addres, charge,ccy.FirstOrDefault());
                    }
                }

            }
                // Catching iTextSharp.text.DocumentException if any
            catch (DocumentException de)
            {
                _logs.LogError(loggedUser, "PDF - DocumentException", "Error: " + de.Message,
               addres, fpath, "AuditLetters");
            }
                // Catching System.IO.IOException if any
            catch (IOException ioe)
            {
                _logs.LogError(loggedUser, "PDF - IOException", "Error: " + ioe.Message,
              addres, fpath, "AuditLetters");
            }
            catch (Exception ex)
            {
                _logs.LogError(loggedUser, "PDF - Exception", "Error: " + ex.Message,
              addres, fpath, "AuditLetters");
            }
            return false;
        }
        private JobFormNew JobFormJsonConvert(string jobfomJson, string urlname, string jobguid)
        {
            try
            {
                JobFormNew pJobFormView = (!string.IsNullOrEmpty(jobfomJson)) ? new JavaScriptSerializer().Deserialize<JobFormNew>(jobfomJson) : null;

                if (pJobFormView != null)
                {

                    if (pJobFormView.Values != null)
                    {
                        pJobFormView.FormValues = new List<JobFormValueDetails>();
                        //for (int i = 0; i < pJobFormView.Values.Count; i++)
                        foreach (JobFormValues pFormValues in pJobFormView.Values)
                        {
                            //JobFormValues pFormValues = pJobFormView.Values[i];
                            JobFormValueDetails pFormDetails = new JobFormValueDetails();
                            string[] Controls = pFormValues.ControlID.Split('_');
                            if (Controls.Length > 2)
                            {
                                int controlid, controltype;
                                pFormDetails.FormID = Controls[0];
                                if (int.TryParse(Controls[1], out controlid))
                                {
                                    pFormDetails.ControlID = controlid;
                                }
                                else
                                {
                                    pFormDetails.ControlID = 0;
                                }
                                if (int.TryParse(Controls[2], out controltype))
                                {
                                    pFormDetails.ControlType = (ControlType)controltype;
                                }
                                else
                                {
                                    pFormDetails.ControlType = 0;
                                }

                            }
                            int parentid;
                            pFormDetails.Value = pFormValues.Value;
                            pFormDetails.ControlLabel = pFormValues.ControlLabel;
                            if (int.TryParse(pFormValues.parentID, out parentid))
                            {
                                pFormDetails.parentID = parentid;
                            }
                            else
                            {
                                pFormDetails.parentID = 0;
                            }
                            pFormDetails.controlParentLabel = pFormValues.controlParentLabel;
                            pFormDetails.ValueID = pFormValues.ValueID;
                            pFormDetails.currentValueID = pFormValues.currentValueID;

                            pFormDetails.ImagePath = System.Configuration.ConfigurationManager.AppSettings.Get(urlname).ToString() + Session["OrganizationGUID"].ToString() + "/Jobs/" + pJobFormView.JobGUID;
                            pFormDetails.OrganizationGUID = Session["OrganizationGUID"].ToString();
                            pFormDetails.JobGUID = pJobFormView.JobGUID;
                            pJobFormView.FormValues.Add(pFormDetails);
                        }
                        pJobFormView.JobGUID = jobguid;
                    }
                }
                if (pJobFormView != null && pJobFormView.FormValues != null && pJobFormView.FormValues.Count > 0)
                {
                    pJobFormView.FormValues.OrderBy(x => x.ControlID);
                }
                if (!string.IsNullOrEmpty(jobguid))
                {
                    Job pjob = _IJobRepository.GetJobByID(new Guid(jobguid));
                    if (pjob != null)
                    {
                        List<JobProgress> jobProgressList = new List<JobProgress>();
                        jobProgressList = _IJobRepository.GetJobProgress(pjob.JobGUID);
                        List<string> coordinate = new List<string>();
                        int i = 0;

                        Market pMarket = pjob.CustomerStopGUID != null ? _IMarketRepository.GetMarketByID(new Guid(pjob.CustomerStopGUID.ToString())) : null;
                        if (pMarket != null)
                        {

                            pJobFormView.CoordinateList = new List<CoOrdinates>();

                            if (pMarket.Latitude != null && pMarket.Longitude != null)
                            {
                                CoOrdinates pCoOrdinates = new CoOrdinates();
                                pCoOrdinates.Latitude = Convert.ToDouble(pMarket.Latitude);
                                pCoOrdinates.Longitude = Convert.ToDouble(pMarket.Longitude);
                                pCoOrdinates.Address = pMarket.AddressLine1 + "<br><br/>" + pMarket.AddressLine2;
                                pCoOrdinates.City = pMarket.City;
                                pCoOrdinates.State = pMarket.State;
                                pCoOrdinates.Country = pMarket.Country;
                                pCoOrdinates.JobName = pjob.JobName;
                                pCoOrdinates.StoreName = pMarket.MarketName.ToString();
                                pCoOrdinates.Count = i;
                                i++;
                                pJobFormView.CoordinateList.Add(pCoOrdinates);

                                coordinate.Add(pMarket.Latitude.ToString() + "~" + pMarket.Longitude.ToString() + "~store~" + pCoOrdinates.StoreName.ToString());
                            }

                        }


                        if (jobProgressList != null && jobProgressList.Count > 0)
                        {
                            jobProgressList = jobProgressList.OrderBy(x => x.JobStatus).ToList();
                            if (pMarket == null)
                            {
                                pJobFormView.CoordinateList = new List<CoOrdinates>();
                            }
                            foreach (JobProgress pJobProgress in jobProgressList)
                            {
                                if (pJobProgress.Latitude != null && pJobProgress.Longitude != null)
                                {
                                    CoOrdinates pCoOrdinates = new CoOrdinates();
                                    pCoOrdinates.Latitude = Convert.ToDouble(pJobProgress.Latitude);
                                    pCoOrdinates.Longitude = Convert.ToDouble(pJobProgress.Longitude);
                                    pCoOrdinates.JobName = pjob.JobName;
                                    pCoOrdinates.Count = i;
                                    if (pJobProgress.JobStatus != null && Convert.ToInt32(pJobProgress.JobStatus) == 1)
                                    {

                                        pCoOrdinates.StartTime = pJobProgress.StartTime != null ? Session["TimeZoneID"] != null ? _IUserRepository.GetLocalDateTime(pJobProgress.StartTime, Session["TimeZoneID"].ToString()) : pJobProgress.StartTime.ToString() : "";
                                        pCoOrdinates.StartTime = !string.IsNullOrEmpty(pCoOrdinates.StartTime) ? _IUserRepository.GetLocalDateTime(pJobProgress.StartTime, Session["TimeZoneID"].ToString()) : "";
                                        pCoOrdinates.StartTime = !string.IsNullOrEmpty(pCoOrdinates.StartTime) ? Convert.ToDateTime(pCoOrdinates.StartTime).ToString("MM/dd/yy hh:mm tt") : "";

                                        coordinate.Add(pCoOrdinates.Latitude.ToString() + "~" + pCoOrdinates.Longitude.ToString() + "~start~" + pCoOrdinates.JobName.ToString() + "~" + pCoOrdinates.StartTime.ToString());
                                    }
                                    else
                                    {
                                        pCoOrdinates.EndTime = pJobProgress.StartTime != null ? Session["TimeZoneID"] != null ? _IUserRepository.GetLocalDateTime(pJobProgress.StartTime, Session["TimeZoneID"].ToString()) : pJobProgress.StartTime.ToString() : "";
                                        pCoOrdinates.EndTime = !string.IsNullOrEmpty(pCoOrdinates.EndTime) ? _IUserRepository.GetLocalDateTime(pJobProgress.StartTime, Session["TimeZoneID"].ToString()) : "";
                                        pCoOrdinates.EndTime = !string.IsNullOrEmpty(pCoOrdinates.EndTime) ? Convert.ToDateTime(pCoOrdinates.EndTime).ToString("MM/dd/yy hh:mm tt") : "";

                                        coordinate.Add(pCoOrdinates.Latitude.ToString() + "~" + pCoOrdinates.Longitude.ToString() + "~stop~" + pCoOrdinates.JobName.ToString() + "~" + pCoOrdinates.EndTime.ToString());
                                    }
                                    pJobFormView.CoordinateList.Add(pCoOrdinates);

                                }
                                i++;
                            }



                        }


                        //for displaying google static map in pdf
                        //first need to display job end coordinates
                        //second need to display job start coordinates
                        //Third need to display store coordinates
                        if (pJobFormView.CoordinateList != null && pJobFormView.CoordinateList.Count > 0)
                        {
                            pJobFormView.CoordinateList = pJobFormView.CoordinateList.OrderByDescending(x => x.Count).ToList();
                        }
                        ViewBag.CoOrdinates = coordinate;
                    }
                }
                return pJobFormView;
            }
            catch (Exception ex)
            {
                Logger.Error(ex.Message);
                return null;
            }
        }
        //
        // GET: /StoreVist/
        public ActionResult Index(string id = "", string customerid = "", string FromDate = "", string ToDate = "", string Date = "", string selection = "", string LastModifiedDate = "", string Visit_RowCount = "", string NonVisit_RowCount = "", int page = 1, string Visit_Search = "", string NonVisit_Search = "", string hdnrecordsize="")
        {
            Logger.Debug("Inside CustomerView Controller- Index");
            try
            {
                ViewBag.CustomerID = customerid;
                ViewBag.FromDate = FromDate;
                ViewBag.ToDate = ToDate;
                ViewBag.Date = Date;
                int visit_TotalPage = 0;
                int visit_TotalRecord = 0;
                int visit_pCount = 0;

                int nonvisit_TotalPage = 0;
                int nonvisit_TotalRecord = 0;
                int nonvisit_pCount = 0;
                if (Session["OrganizationGUID"] != null)
                {
                    if (!string.IsNullOrEmpty(Visit_RowCount))
                    {
                        int.TryParse(Visit_RowCount, out visit_pCount);
                        pageVisitCountList(visit_pCount);
                    }
                    else
                    {
                        pageVisitCountList(visit_pCount);
                    }
                    if (!string.IsNullOrEmpty(NonVisit_RowCount))
                    {
                        int.TryParse(NonVisit_RowCount, out nonvisit_pCount);
                        pageNonVisitCountList(nonvisit_pCount);
                    }
                    else
                    {
                        pageNonVisitCountList(nonvisit_pCount);
                    }

                    if (!string.IsNullOrEmpty(Date))
                    {
                        ViewBag.DateValue = HttpUtility.HtmlDecode(Date);
                        Session["DateValue"] = Date;
                    }
                    else if (!string.IsNullOrEmpty(LastModifiedDate))
                    {
                        Logger.Debug("Inside Last Modfied dislay");
                        if (!string.IsNullOrEmpty(FromDate) && !string.IsNullOrEmpty(ToDate))
                        {
                            DateTime pFrom = new DateTime(), pTo = new DateTime();
                            if (ParseExact(FromDate, "dd-MM-yyyy", out pFrom))
                            {
                                ParseExact(ToDate, "dd-MM-yyyy", out pTo);
                                Logger.Debug("Inside");
                                string datevalue = pFrom.ToString("MMMM d, yyyy") + " - " + pTo.ToString("MMMM d, yyyy");
                                ViewBag.DateValue = datevalue;
                                Session["DateValue"] = datevalue;
                            }
                            else
                            {
                                Logger.Debug("OutSide");
                                string datevalue = DateTime.Now.AddDays(-29).ToString("MMMM d, yyyy") + " - " + DateTime.Now.ToString("MMMM d, yyyy");
                                ViewBag.DateValue = datevalue;
                                Session["DateValue"] = datevalue;
                            }
                            Logger.Debug("From Parst : " + pFrom);
                            Logger.Debug("To Parse : " + pTo);
                        }
                        else
                        {
                            Logger.Debug("OutSide1");
                            string datevalue = DateTime.Now.AddDays(-29).ToString("MMMM d, yyyy") + " - " + DateTime.Now.ToString("MMMM d, yyyy");
                            ViewBag.DateValue = datevalue;
                            Session["DateValue"] = datevalue;
                        }
                    }
                    else
                    {
                        Logger.Error("OutSide2");
                        string datevalue = DateTime.Now.AddDays(-29).ToString("MMMM d, yyyy") + " - " + DateTime.Now.ToString("MMMM d, yyyy");
                        ViewBag.DateValue = datevalue;
                        Session["DateValue"] = datevalue;
                    }
                    StoreVisitReports pStoreVisitReports = new StoreVisitReports();
                    pStoreVisitReports.StoreVisitList = new List<StoreVisit>();
                    pStoreVisitReports.StoreNonVisitList = new List<MarketModel>();

                    Session["CustomerGUID"] = customerid;
                    if (!string.IsNullOrEmpty(id))
                    {
                        TempData["TabName"] = id;
                    }
                    else
                    {
                        TempData["TabName"] = "Visits";
                    }

                    StringBuilder sb = new StringBuilder();
                    StringBuilder sb1 = new StringBuilder();
                    sb.Append("<div class='actions'>");
                    sb.Append("<div class='btn-group'>");
                    sb1.Append("<div class='actions'>");
                    sb1.Append("<div class='btn-group'>");
                    if (!string.IsNullOrEmpty(customerid))
                    {
                        Place pplace = _IPlaceRepository.GetPlaceByID(new Guid(customerid));
                        if (pplace != null)
                        {
                            Session["ClientCompanyName"] = pplace.PlaceName;
                            sb.Append("<a href='#' id='ulaworkergroup' class='btn green' data-toggle='dropdown'><i class='icon-map-marker'></i>" + pplace.PlaceName + " <i class='icon-angle-down'></i></a>");
                            sb1.Append("<a href='#' id='ulaworkergroup' class='btn green' data-toggle='dropdown'><i class='icon-map-marker'></i>" + pplace.PlaceName + " <i class='icon-angle-down'></i></a>");
                        }
                    }
                    else
                    {
                        if (!string.IsNullOrEmpty(selection) && selection == "All")
                        {
                            sb.Append("<a href='#' id='ulaworkergroup' class='btn green' data-toggle='dropdown'><i class='icon-map-marker'></i>All <i class='icon-angle-down'></i></a>");
                            sb1.Append("<a href='#' id='ulaworkergroup' class='btn green' data-toggle='dropdown'><i class='icon-map-marker'></i>All <i class='icon-angle-down'></i></a>");
                        }
                        else
                        {
                            sb.Append("<a href='#' id='ulaworkergroup' class='btn green' data-toggle='dropdown'><i class='icon-map-marker'></i>Select Client <i class='icon-angle-down'></i></a>");
                            sb1.Append("<a href='#' id='ulaworkergroup' class='btn green' data-toggle='dropdown'><i class='icon-map-marker'></i>Select Client <i class='icon-angle-down'></i></a>");
                        }
                    }
                    sb.Append("<ul id='ulworkgroup' style='height:100px;overflow-y:scroll' class='dropdown-menu pull-right'>");
                    sb1.Append("<ul id='ulworkgroup' style='height:100px;overflow-y:scroll' class='dropdown-menu pull-right'>");
                    if (string.IsNullOrEmpty(selection) || selection != "All")
                    {
                        //sb.Append("<li><a href=" + Url.Action("Index", new { id = "Visits", selection = "All" }) + ">All</a></li>");
                        //sb1.Append("<li><a href=" + Url.Action("Index", new { id = "Non-Visits", selection = "All" }) + ">All</a></li>");
                        sb.Append("<li><a onclick=\"RedirectAction('Visits','');\">All</a></li>");
                        sb1.Append("<li><a onclick=\"RedirectAction('NonVisits','');\">All</a></li>");
                    }

                    List<Place> PlaceList = _IPlaceRepository.GetPlaceByOrganizationGUID(new Guid(Session["OrganizationGUID"].ToString())).ToList();
                    foreach (Place item in PlaceList)
                    {
                        //sb.Append("<li><a href=" + Url.Action("Index", new { id = "Visits", customerid = item.PlaceGUID.ToString() }) + " data-groupguid=" + item.PlaceGUID + ">" + item.PlaceName + "</a></li>");
                        //sb1.Append("<li><a href=" + Url.Action("Index", new { id = "Non-Visits", customerid = item.PlaceGUID.ToString() }) + " data-groupguid=" + item.PlaceGUID + ">" + item.PlaceName + "</a></li>");

                        sb.Append("<li><a onclick=\"RedirectAction('Visits','" + item.PlaceGUID.ToString() + "');\" data-groupguid=" + item.PlaceGUID + ">" + item.PlaceName + "</a></li>");
                        sb1.Append("<li><a onclick=\"RedirectAction('NonVisits','" + item.PlaceGUID.ToString() + "');\" data-groupguid=" + item.PlaceGUID + ">" + item.PlaceName + "</a></li>");
                    }
                    sb.Append("</ul>");
                    sb.Append("</div>");
                    sb.Append("</div>");
                    sb1.Append("</ul>");
                    sb1.Append("</div>");
                    sb1.Append("</div>");
                    ViewBag.CustomerListVisit = sb.ToString();
                    ViewBag.CustomerListNonVisit = sb1.ToString();

                    Market _market = new Market();
                    Job ljob = new Job();
                    ljob.OrganizationGUID = new Guid(Session["OrganizationGUID"].ToString());
                    _market.OrganizationGUID = new Guid(Session["OrganizationGUID"].ToString());
                    if (!string.IsNullOrEmpty(customerid))
                    {
                        _market.OwnerGUID = new Guid(customerid);
                        ljob.CustomerGUID = new Guid(customerid);
                    }

                    DateTime From, To, Datecontent, LModifiedDate;

                    //LastModifiedDate = _IUserRepository.DecodeFrom64(LastModifiedDate);
                    if (!string.IsNullOrEmpty(LastModifiedDate) && ParseExact(LastModifiedDate, "dd-MM-yyyy", out LModifiedDate))
                    {
                        ljob.LastModifiedDate = LModifiedDate;
                        _market.LastStoreVisitedDate = LModifiedDate;
                    }
                    else if (!string.IsNullOrEmpty(FromDate) && ParseExact(FromDate, "dd-MM-yyyy", out From))
                        _market.LastStoreVisitedDate = From;
                    else
                        _market.LastStoreVisitedDate = DateTime.Now.AddDays(-29);

                    if (!string.IsNullOrEmpty(FromDate) && ParseExact(FromDate, "dd-MM-yyyy", out From))
                    {
                        ljob.ActualStartTime = From;
                    }
                    else
                    {
                        Logger.Error("From Else");
                        ljob.ActualStartTime = DateTime.Now.AddDays(-29);
                    }
                    if (!string.IsNullOrEmpty(ToDate) && ParseExact(ToDate, "dd-MM-yyyy", out To))
                    {
                        ljob.ActualEndTime = To;
                    }
                    else
                    {
                        Logger.Error("To Else");
                        ljob.ActualEndTime = DateTime.Now;
                    }
                    ljob.JobName = "Store Visit";
                    Logger.Debug("Job Object" + Newtonsoft.Json.JsonConvert.SerializeObject(ljob));

                    //FOr Regional Manager
                    if (Session["UserType"] != null && !string.IsNullOrEmpty(Session["UserType"].ToString()) && Session["UserType"].ToString() == "ENT_U_RM" && Session["UserGUID"] != null)
                    {
                        OrganizationUsersMap OrgUserMap = _IOrganizationRepository.GetOrganizationUserMapByUserGUID(new Guid(Session["UserGUID"].ToString()), ljob.OrganizationGUID);
                        if (OrgUserMap != null)
                        {
                            ljob.RegionGUID = OrgUserMap.RegionGUID;
                            _market.RegionGUID = OrgUserMap.RegionGUID;
                        }
                    }

                    //check the current user is Field Manager or not
                    if (Session["UserType"] != null && !string.IsNullOrEmpty(Session["UserType"].ToString()) && Session["UserType"].ToString() == "ENT_U" && Session["UserGUID"] != null)
                    {
                        GlobalUser globalUser = _IGlobalUserRepository.GetGlobalUserByID(new Guid(Session["UserGUID"].ToString()));
                        if (globalUser != null)
                        {
                            ljob.AssignedUserGUID = globalUser.UserGUID;
                            _market.FMUserID = globalUser.USERID;
                        }
                    }

                    List<Job> lstorevisit = _IJobRepository.GetStoreVisitJobs(ljob);
                    List<Market> lstorenonvisit = new List<Market>();
                    lstorenonvisit = _IMarketRepository.GetStoreNonVisit(_market);
                    if (lstorevisit != null && lstorevisit.Count > 0)
                    {
                        ViewBag.Visit_Search = Visit_Search;
                        if (!string.IsNullOrEmpty(Visit_Search))
                        {
                            Visit_Search = Visit_Search.ToLower();
                            lstorevisit = lstorevisit.Where(
                                p => (!String.IsNullOrEmpty(_IRegionRepository.GetRegionNameByRegionGUID(new Guid(p.RegionGUID.ToString()))) && _IRegionRepository.GetRegionNameByRegionGUID(new Guid(p.RegionGUID.ToString())).ToLower().Contains(Visit_Search))
                            || (!String.IsNullOrEmpty(p.CustomerStopGUID.ToString()) && _IMarketRepository.GetMarketByID(new Guid(p.CustomerStopGUID.ToString())).MarketID.ToLower().Contains(Visit_Search))
                            || (!String.IsNullOrEmpty(p.PONumber) && _IMarketRepository.GetMarketByCustomerID(p.OrganizationGUID, _IPORepository.GetPObyPoNumber(p.PONumber).PlaceID, _IPORepository.GetPObyPoNumber(p.PONumber).MarketID).MarketID.ToLower().Contains(Visit_Search))
                            || (!String.IsNullOrEmpty(p.CustomerStopGUID.ToString()) && _IMarketRepository.GetMarketByID(new Guid(p.CustomerStopGUID.ToString())).MarketName.ToLower().Contains(Visit_Search))
                            || (!String.IsNullOrEmpty(p.PONumber) && _IMarketRepository.GetMarketByCustomerID(p.OrganizationGUID, _IPORepository.GetPObyPoNumber(p.PONumber).PlaceID, _IPORepository.GetPObyPoNumber(p.PONumber).MarketID).MarketName.ToLower().Contains(Visit_Search))
                            || (!String.IsNullOrEmpty(_IJobRepository.GetStatusName((int)p.StatusCode)) && _IJobRepository.GetStatusName((int)p.StatusCode).ToLower().Contains(Visit_Search))
                            || (!String.IsNullOrEmpty(_IUserProfileRepository.GetUserProfileByUserID(_IGlobalUserRepository.GetGlobalUserByID(new Guid(p.ManagerUserGUID.ToString())).UserGUID, p.OrganizationGUID).ToString()) && _IUserProfileRepository.GetUserProfileByUserID(_IGlobalUserRepository.GetGlobalUserByID(new Guid(p.ManagerUserGUID.ToString())).UserGUID, p.OrganizationGUID).ToString().ToLower().Contains(Visit_Search))).ToList();
                        }

                        visit_TotalRecord = lstorevisit.ToList().Count;
                        visit_TotalPage = (visit_TotalRecord / (int)ViewBag.pageVisitCountValue) + ((visit_TotalRecord % (int)ViewBag.pageVisitCountValue) > 0 ? 1 : 0);

                        ViewBag.Visit_TotalRows = visit_TotalRecord;
                        lstorevisit = lstorevisit.OrderBy(a => a.OrganizationGUID).Skip(((page - 1) * (int)ViewBag.pageVisitCountValue)).Take((int)ViewBag.pageVisitCountValue).ToList();

                        foreach (Job job in lstorevisit)
                        {
                            StoreVisit storevisit = ConvertToStoreVisit(job);
                            if (storevisit != null)
                            {
                                pStoreVisitReports.StoreVisitList.Add(storevisit);
                            }
                        }
                    }

                    // Logger.Debug("Store Non Visit Count : " + lstorenonvisit.Count);
                    if (lstorenonvisit != null && lstorenonvisit.Count > 0)
                    {
                        ViewBag.NonVisit_Search = NonVisit_Search;
                        if (!string.IsNullOrEmpty(NonVisit_Search))
                        {
                            NonVisit_Search = NonVisit_Search.ToLower();
                            lstorenonvisit = lstorenonvisit.Where(
                                p => (!String.IsNullOrEmpty(p.RegionName) && p.RegionName.ToLower().Contains(NonVisit_Search))
                            || (!String.IsNullOrEmpty(p.MarketID) && p.MarketID.ToLower().Contains(NonVisit_Search))
                            || (!String.IsNullOrEmpty(p.MarketName) && p.MarketName.ToLower().Contains(NonVisit_Search))).ToList();
                        }

                        nonvisit_TotalRecord = lstorenonvisit.ToList().Count;
                        nonvisit_TotalPage = (nonvisit_TotalRecord / (int)ViewBag.pageNonCountValue) + ((nonvisit_TotalRecord % (int)ViewBag.pageNonCountValue) > 0 ? 1 : 0);

                        ViewBag.NonVisit_TotalRows = nonvisit_TotalRecord;
                        lstorenonvisit = lstorenonvisit.OrderBy(a => a.OrganizationGUID).Skip(((page - 1) * (int)ViewBag.pageNonCountValue)).Take((int)ViewBag.pageNonCountValue).ToList();

                        foreach (Market market in lstorenonvisit)
                        {
                            MarketModel _marketModel = ConvertToStoreNonVisit(market);
                            if (_marketModel != null)
                            {
                                pStoreVisitReports.StoreNonVisitList.Add(_marketModel);
                            }
                        }
                    }
                    Session["StoreVisit"] = pStoreVisitReports.StoreVisitList;
                    Session["StoreNonVisit"] = pStoreVisitReports.StoreNonVisitList;

                    if (!string.IsNullOrEmpty(Visit_RowCount))
                        ViewBag.pageVisitCountValue = int.Parse(Visit_RowCount);
                    else
                        ViewBag.pageVisitCountValue = 5;
                    if (!string.IsNullOrEmpty(NonVisit_RowCount))
                        ViewBag.pageNonCountValue = int.Parse(NonVisit_RowCount);
                    else
                        ViewBag.pageNonCountValue = 5;
                    
                    bool visit = false;
                    bool nonvisit = false;
                    if (null != Request && System.Text.RegularExpressions.Regex.IsMatch(Request.Url.ToString().Replace("-", ""), string.Format(@"\b{0}\b", "Visits")))
                        visit = true;
                    if (null != Request && System.Text.RegularExpressions.Regex.IsMatch(Request.Url.ToString().Replace("-", ""), string.Format(@"\b{0}\b", "NonVisits")))
                        nonvisit = true;

                    if (visit)
                        TempData["TabName"] = "Visits";
                    else if(nonvisit)
                        TempData["TabName"] = "Non-Visits";

                    return View(pStoreVisitReports);
                }
                else
                {
                    return RedirectToAction("SessionTimeOut", "User");
                }
            }
            catch (Exception ex)
            {
                Logger.Error(ex.Message);
                return RedirectToAction("Login", "User");
            }
        }
        public JsonResult Details(Int16 indicatorID, Int16 fiscalYear)
        {
            var viewModelItems = new List<Indicators>();
            viewModelItems = db.Indicators.Where(x => x.Indicator_ID == indicatorID).ToList();

            var viewModel = viewModelItems.OrderBy(x => x.Indicator_ID).Select(x => new GraphViewModel
            {
                Indicator_ID = x.Indicator_ID,
                Area_ID = x.Area_ID,
                //CoE = x.Indicator_CoE_Map.Count != 0 ? x.Indicator_CoE_Map.Where(y => y.Fiscal_Year == fiscalYear).FirstOrDefault().CoE.CoE : "",
                Indicator = x.Indicator,

                FY_3_YTD = (string)x.GetType().GetProperty(FiscalYear.FYStr(fiscalYear, 3) + "_YTD").GetValue(x, null),
                FY_3_YTD_Sup = (string)x.GetType().GetProperty(FiscalYear.FYStr(fiscalYear, 3) + "_YTD_Sup").GetValue(x, null),
                //FY_3_Target = (string)x.GetType().GetProperty(FiscalYear.FYStr(fiscalYear, 3) + "_Target").GetValue(x, null),
                //FY_3_Target_Sup = (string)x.GetType().GetProperty(FiscalYear.FYStr(fiscalYear, 3) + "_Target_Sup").GetValue(x, null),
                //FY_3_Comparator = (string)x.GetType().GetProperty(FiscalYear.FYStr(fiscalYear, 3) + "_Comparator").GetValue(x, null),
                //FY_3_Comparator_Sup = (string)x.GetType().GetProperty(FiscalYear.FYStr(fiscalYear, 3) + "_Comparator_Sup").GetValue(x, null),
                //FY_3_Performance_Threshold = (string)x.GetType().GetProperty(FiscalYear.FYStr(fiscalYear, 3) + "_Performance_Threshold").GetValue(x, null),
                //FY_3_Performance_Threshold_Sup = (string)x.GetType().GetProperty(FiscalYear.FYStr(fiscalYear, 3) + "_Performance_Threshold_Sup").GetValue(x, null),

                FY_2_YTD = (string)x.GetType().GetProperty(FiscalYear.FYStr(fiscalYear, 2) + "_YTD").GetValue(x, null),
                FY_2_YTD_Sup = (string)x.GetType().GetProperty(FiscalYear.FYStr(fiscalYear, 2) + "_YTD_Sup").GetValue(x, null),
                //FY_2_Target = (string)x.GetType().GetProperty(FiscalYear.FYStr(fiscalYear, 2) + "_Target").GetValue(x, null),
                //FY_2_Target_Sup = (string)x.GetType().GetProperty(FiscalYear.FYStr(fiscalYear, 2) + "_Target_Sup").GetValue(x, null),
                //FY_2_Comparator = (string)x.GetType().GetProperty(FiscalYear.FYStr(fiscalYear, 2) + "_Comparator").GetValue(x, null),
                //FY_2_Comparator_Sup = (string)x.GetType().GetProperty(FiscalYear.FYStr(fiscalYear, 2) + "_Comparator_Sup").GetValue(x, null),
                //FY_2_Performance_Threshold = (string)x.GetType().GetProperty(FiscalYear.FYStr(fiscalYear, 2) + "_Performance_Threshold").GetValue(x, null),
                //FY_2_Performance_Threshold_Sup = (string)x.GetType().GetProperty(FiscalYear.FYStr(fiscalYear, 2) + "_Performance_Threshold_Sup").GetValue(x, null),

                FY_1_YTD = (string)x.GetType().GetProperty(FiscalYear.FYStr(fiscalYear, 1) + "_YTD").GetValue(x, null),
                FY_1_YTD_Sup = (string)x.GetType().GetProperty(FiscalYear.FYStr(fiscalYear, 1) + "_YTD_Sup").GetValue(x, null),
                //FY_1_Target = (string)x.GetType().GetProperty(FiscalYear.FYStr(fiscalYear, 1) + "_Target").GetValue(x, null),
                //FY_1_Target_Sup = (string)x.GetType().GetProperty(FiscalYear.FYStr(fiscalYear, 1) + "_Target_Sup").GetValue(x, null),
                //FY_1_Comparator = (string)x.GetType().GetProperty(FiscalYear.FYStr(fiscalYear, 1) + "_Comparator").GetValue(x, null),
                //FY_1_Comparator_Sup = (string)x.GetType().GetProperty(FiscalYear.FYStr(fiscalYear, 1) + "_Comparator_Sup").GetValue(x, null),
                //FY_1_Performance_Threshold = (string)x.GetType().GetProperty(FiscalYear.FYStr(fiscalYear, 1) + "_Performance_Threshold").GetValue(x, null),
                //FY_1_Performance_Threshold_Sup = (string)x.GetType().GetProperty(FiscalYear.FYStr(fiscalYear, 1) + "_Performance_Threshold_Sup").GetValue(x, null),

                FY_Q1 = (string)x.GetType().GetProperty(FiscalYear.FYStr(fiscalYear, 0) + "_Q1").GetValue(x, null),
                FY_Q1_Sup = (string)x.GetType().GetProperty(FiscalYear.FYStr(fiscalYear, 0) + "_Q1_Sup").GetValue(x, null),
                FY_Q2 = (string)x.GetType().GetProperty(FiscalYear.FYStr(fiscalYear, 0) + "_Q2").GetValue(x, null),
                FY_Q2_Sup = (string)x.GetType().GetProperty(FiscalYear.FYStr(fiscalYear, 0) + "_Q2_Sup").GetValue(x, null),
                FY_Q3 = (string)x.GetType().GetProperty(FiscalYear.FYStr(fiscalYear, 0) + "_Q3").GetValue(x, null),
                FY_Q3_Sup = (string)x.GetType().GetProperty(FiscalYear.FYStr(fiscalYear, 0) + "_Q3_Sup").GetValue(x, null),
                FY_Q4 = (string)x.GetType().GetProperty(FiscalYear.FYStr(fiscalYear, 0) + "_Q4").GetValue(x, null),
                FY_Q4_Sup = (string)x.GetType().GetProperty(FiscalYear.FYStr(fiscalYear, 0) + "_Q4_Sup").GetValue(x, null),
                FY_YTD = (string)x.GetType().GetProperty(FiscalYear.FYStr(fiscalYear, 0) + "_YTD").GetValue(x, null),
                FY_YTD_Sup = (string)x.GetType().GetProperty(FiscalYear.FYStr(fiscalYear, 0) + "_YTD_Sup").GetValue(x, null),
                Target = (string)x.GetType().GetProperty(FiscalYear.FYStr(fiscalYear, 0) + "_Target").GetValue(x, null),
                TargetNum = Helpers.Color.getNum((string)x.GetType().GetProperty(FiscalYear.FYStr(fiscalYear, 0) + "_Target").GetValue(x, null)),
                Target_Sup = (string)x.GetType().GetProperty(FiscalYear.FYStr(fiscalYear, 0) + "_Target_Sup").GetValue(x, null),
                Comparator = (string)x.GetType().GetProperty(FiscalYear.FYStr(fiscalYear, 0) + "_Comparator").GetValue(x, null),
                Comparator_Sup = (string)x.GetType().GetProperty(FiscalYear.FYStr(fiscalYear, 0) + "_Comparator_Sup").GetValue(x, null),
                Performance_Threshold = (string)x.GetType().GetProperty(FiscalYear.FYStr(fiscalYear, 0) + "_Performance_Threshold").GetValue(x, null),
                Performance_Threshold_Sup = (string)x.GetType().GetProperty(FiscalYear.FYStr(fiscalYear, 0) + "_Performance_Threshold_Sup").GetValue(x, null),

                Color_ID = (Int16)x.GetType().GetProperty(FiscalYear.FYStr(fiscalYear, 0) + "_Color_ID").GetValue(x, null),
                Custom_YTD = (string)x.GetType().GetProperty(FiscalYear.FYStr(fiscalYear, 0) + "_YTD_Custom_Color").GetValue(x, null),
                Custom_Q1 = (string)x.GetType().GetProperty(FiscalYear.FYStr(fiscalYear, 0) + "_Q1_Custom_Color").GetValue(x, null),
                Custom_Q2 = (string)x.GetType().GetProperty(FiscalYear.FYStr(fiscalYear, 0) + "_Q2_Custom_Color").GetValue(x, null),
                Custom_Q3 = (string)x.GetType().GetProperty(FiscalYear.FYStr(fiscalYear, 0) + "_Q3_Custom_Color").GetValue(x, null),
                Custom_Q4 = (string)x.GetType().GetProperty(FiscalYear.FYStr(fiscalYear, 0) + "_Q4_Custom_Color").GetValue(x, null),

                Definition_Calculation = (string)x.GetType().GetProperty(FiscalYear.FYStr(fiscalYear, 0) + "_Definition_Calculation").GetValue(x, null),
                Target_Rationale = (string)x.GetType().GetProperty(FiscalYear.FYStr(fiscalYear, 0) + "_Target_Rationale").GetValue(x, null),
                Comparator_Source = (string)x.GetType().GetProperty(FiscalYear.FYStr(fiscalYear, 0) + "_Comparator_Source").GetValue(x, null),

                Data_Source_MSH = (string)x.GetType().GetProperty(FiscalYear.FYStr(fiscalYear, 0) + "_Data_Source_MSH").GetValue(x, null),
                Data_Source_Benchmark = (string)x.GetType().GetProperty(FiscalYear.FYStr(fiscalYear, 0) + "_Data_Source_Benchmark").GetValue(x, null),
                OPEO_Lead = (string)x.GetType().GetProperty(FiscalYear.FYStr(fiscalYear, 0) + "_OPEO_Lead").GetValue(x, null),

                Q1_Color = (string)x.GetType().GetProperty(FiscalYear.FYStr(fiscalYear, 0) + "_Q1_Color").GetValue(x, null),
                Q2_Color = (string)x.GetType().GetProperty(FiscalYear.FYStr(fiscalYear, 0) + "_Q2_Color").GetValue(x, null),
                Q3_Color = (string)x.GetType().GetProperty(FiscalYear.FYStr(fiscalYear, 0) + "_Q3_Color").GetValue(x, null),
                Q4_Color = (string)x.GetType().GetProperty(FiscalYear.FYStr(fiscalYear, 0) + "_Q4_Color").GetValue(x, null),
                YTD_Color = (string)x.GetType().GetProperty(FiscalYear.FYStr(fiscalYear, 0) + "_YTD_Color").GetValue(x, null),

                //FY_1_YTD_Color = (string)x.GetType().GetProperty(FiscalYear.FYStr(fiscalYear, 1) + "_YTD_Color").GetValue(x, null),
                //FY_2_YTD_Color = (string)x.GetType().GetProperty(FiscalYear.FYStr(fiscalYear, 2) + "_YTD_Color").GetValue(x, null),
                //FY_3_YTD_Color = (string)x.GetType().GetProperty(FiscalYear.FYStr(fiscalYear, 3) + "_YTD_Color").GetValue(x, null),

                Fiscal_Year = fiscalYear,

            }).FirstOrDefault();
            return Json(viewModel);
        }
        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);
        }
        //
        // GET: /JobStatus/
        public ActionResult Index(string FromDate = "", string ToDate = "", string assigneduserguid = "", string jobindexguid = "", string Date = "", string selection = "", string ponumber = "", string RowCount = "", int page = 1, string search = "")
        {
            Logger.Debug("Inside AssignJob Controller- Index");
            try
            {
                ViewBag.AssignedUserID = assigneduserguid;
                ViewBag.FromDate = FromDate;
                ViewBag.ToDate = ToDate;
                ViewBag.Date = Date;
                int totalPage = 0;
                int totalRecord = 0;
                int pCount = 0;
                if (Session["OrganizationGUID"] != null)
                {
                    if (!string.IsNullOrEmpty(RowCount))
                    {
                        int.TryParse(RowCount, out pCount);
                        pageCountList(pCount);
                    }
                    else
                    {
                        pageCountList(pCount);
                    }

                    if (!string.IsNullOrEmpty(Date))
                    {
                        ViewBag.DateValue = HttpUtility.HtmlDecode(Date);
                    }
                    var jobStatus = new JobStatusViewModel();
                    jobStatus.JobStatusModel = new List<JobStatusModel>();
                    var jobGroup = new List<Job>();
                    //Job ljob = new Job();
                    DateTime pFrom = new DateTime(), pTo = new DateTime();
                    OrganizationUsersMap pOrganizationUsersMap = _IUserRepository.GetUserByID(new Guid(Session["UserGUID"].ToString()));
                    Logger.Debug("UserGUID:" + Session["UserGUID"].ToString());
                    if (pOrganizationUsersMap != null)
                    {
                        StringBuilder sb = new StringBuilder();
                        sb.Append("<div class='actions'>");
                        sb.Append("<div class='btn-group'>");
                        if (!string.IsNullOrEmpty(assigneduserguid))
                        {
                            ViewBag.AssignedUserID = assigneduserguid;
                            Logger.Debug("Inside AssignedUSerGUID" + assigneduserguid.ToString());
                            UserProfile _userprofile = _IUserProfileRepository.GetUserProfileByUserID(new Guid(assigneduserguid), pOrganizationUsersMap.OrganizationGUID);
                            if (_userprofile != null)
                            {
                                sb.Append("<a href='#' id='ulaworkergroup' class='btn green' data-toggle='dropdown'><i class='icon-map-marker'></i> " + _userprofile.FirstName + " " + _userprofile.LastName + " <i class='icon-angle-down'></i></a>");
                            }
                        }
                        else
                        {

                            if (!string.IsNullOrEmpty(selection) && selection == "All")
                            {
                                sb.Append("<a href='#' id='ulaworkergroup' class='btn green' data-toggle='dropdown'><i class='icon-map-marker'></i> All <i class='icon-angle-down'></i></a>");
                            }
                            else
                            {
                                sb.Append("<a href='#' id='ulaworkergroup' class='btn green' data-toggle='dropdown'><i class='icon-map-marker'></i> Select User <i class='icon-angle-down'></i></a>");
                            }
                        }
                        sb.Append("<ul id='ulworkgroup' style='height:200px;overflow-y:scroll' class='dropdown-menu pull-right'>");

                        if (Session["UserType"] != null && Session["UserType"].ToString() != "ENT_U" && pOrganizationUsersMap != null)
                        {
                            if (string.IsNullOrEmpty(selection) || selection != "All")
                            {
                                //sb.Append("<li><a href=" + Url.Action("Index", "UserActivities", new { selection = "All" }) + ">All</a></li>");
                                sb.Append("<li><a onclick=\"RedirectAction('');\">All</a></li>");
                            }
                            List<UserProfile> pUserProfile = _IUserProfileRepository.GetUserProfilesbyOrganizationGUID(new Guid(Session["OrganizationGUID"].ToString())).ToList();

                            if (pUserProfile != null && pUserProfile.Count > 0)
                            {
                                pUserProfile = pUserProfile.OrderBy(x => x.FirstName).ToList();
                                foreach (UserProfile item in pUserProfile)
                                {
                                    //sb.Append("<li><a href=" + Url.Action("Index", "UserActivities", new { assigneduserguid = item.UserGUID.ToString() }) + " data-groupguid=" + item.UserGUID + ">" + item.FirstName + " " + item.LastName + "</a></li>");
                                    sb.Append("<li><a onclick=\"RedirectAction('" + item.UserGUID.ToString() + "');\" data-groupguid=" + item.UserGUID + ">" + item.FirstName + " " + item.LastName + "</a></li>");
                                    Logger.Debug("Inside User foreach");
                                }
                            }
                        }
                        sb.Append("</ul>");
                        sb.Append("</div>");
                        sb.Append("</div>");

                        ViewBag.UserList = sb.ToString();
                        Job mjob = new Job();
                        if (!string.IsNullOrEmpty(ponumber))
                        {
                            mjob.PONumber = ponumber;
                            TempData["PoNumber"] = ponumber;
                        }
                        //FOr Regional Manager
                        if (Session["UserType"] != null && !string.IsNullOrEmpty(Session["UserType"].ToString()) && Session["UserType"].ToString() == "ENT_U_RM" && Session["UserGUID"] != null)
                        {
                            OrganizationUsersMap OrgUserMap = _IOrganizationRepository.GetOrganizationUserMapByUserGUID(new Guid(Session["UserGUID"].ToString()), new Guid(Session["OrganizationGUID"].ToString()));
                            if (OrgUserMap != null)
                            {
                                mjob.RegionGUID = OrgUserMap.RegionGUID;
                            }
                        }
                        if (!string.IsNullOrEmpty(FromDate) && !string.IsNullOrEmpty(ToDate) && !string.IsNullOrEmpty(assigneduserguid))
                        {
                            //ViewBag.FromDate = FromDate;
                            //ViewBag.ToDate = ToDate;
                            Logger.Debug("Inside 1");
                            if (Session["UserType"] != null && Session["UserType"].ToString() == "ENT_U")
                            {
                                mjob.AssignedUserGUID = new Guid(assigneduserguid);
                                if (ParseExact(FromDate, "dd-MM-yyyy", out pFrom))
                                {
                                    mjob.ActualStartTime = pFrom;
                                }
                                else
                                {
                                    Logger.Debug("From else");
                                    mjob.ActualStartTime = DateTime.Now.AddDays(-29);
                                }
                                if (ParseExact(ToDate, "dd-MM-yyyy", out pTo))
                                {
                                    mjob.ActualEndTime = pTo;
                                }
                                else
                                {
                                    Logger.Debug("To else");
                                    mjob.ActualEndTime = DateTime.Now;
                                }
                                mjob.OrganizationGUID = new Guid(Session["OrganizationGUID"].ToString());
                                jobGroup = _IJobRepository.GetJobs(mjob);
                            }
                            else
                            {
                                Logger.Debug("Inside 1 else");
                                mjob.AssignedUserGUID = new Guid(assigneduserguid);
                                if (ParseExact(FromDate, "dd-MM-yyyy", out pFrom))
                                {
                                    mjob.ActualStartTime = pFrom;
                                }
                                else
                                {
                                    Logger.Debug("From else 1");
                                    mjob.ActualStartTime = DateTime.Now.AddDays(-29);
                                }
                                if (ParseExact(ToDate, "dd-MM-yyyy", out pTo))
                                {
                                    mjob.ActualEndTime = pTo;
                                }
                                else
                                {
                                    Logger.Debug("To Else 1");
                                    mjob.ActualEndTime = DateTime.Now;
                                }
                                //    mjob.PreferedEndTime = _IUserRepository.GetLocalDateTime(mjob.PreferedEndTime, Session["TimeZoneID"].ToString());
                                mjob.OrganizationGUID = new Guid(Session["OrganizationGUID"].ToString());
                                jobGroup = _IJobRepository.GetJobs(mjob);
                            }
                        }
                        else if (!string.IsNullOrEmpty(FromDate) && !string.IsNullOrEmpty(ToDate))
                        {
                            Logger.Debug("Inside 2");
                            if (Session["UserType"] != null && Session["UserType"].ToString() == "ENT_U")
                            {
                                if (ParseExact(FromDate, "dd-MM-yyyy", out pFrom))
                                {
                                    mjob.ActualStartTime = pFrom;
                                }
                                else
                                {
                                    Logger.Debug("From else");
                                    mjob.ActualStartTime = DateTime.Now.AddDays(-29);
                                }
                                if (ParseExact(ToDate, "dd-MM-yyyy", out pTo))
                                {
                                    mjob.ActualEndTime = pTo;
                                }
                                else
                                {
                                    Logger.Debug("To else");
                                    mjob.ActualEndTime = DateTime.Now;
                                }
                                mjob.AssignedUserGUID = new Guid(Session["UserGUID"].ToString());
                                mjob.OrganizationGUID = new Guid(Session["OrganizationGUID"].ToString());
                                jobGroup = _IJobRepository.GetJobs(mjob);
                            }
                            else
                            {
                                Logger.Debug("Inside 3");
                                if (ParseExact(FromDate, "dd-MM-yyyy", out pFrom))
                                {
                                    mjob.ActualStartTime = pFrom;
                                }
                                else
                                {
                                    Logger.Debug("From Else");
                                    mjob.ActualStartTime = DateTime.Now.AddDays(-29);
                                }
                                if (ParseExact(ToDate, "dd-MM-yyyy", out pTo))
                                {
                                    mjob.ActualEndTime = pTo;
                                }
                                else
                                {
                                    Logger.Debug("To Else");
                                    mjob.ActualEndTime = DateTime.Now;
                                }
                                mjob.OrganizationGUID = new Guid(Session["OrganizationGUID"].ToString());
                                jobGroup = _IJobRepository.GetJobs(mjob);
                            }
                        }
                        else if (!string.IsNullOrEmpty(assigneduserguid))
                        {
                            mjob.ActualStartTime = DateTime.Now.AddDays(-29);
                            mjob.ActualEndTime = DateTime.Now;
                            mjob.AssignedUserGUID = new Guid(assigneduserguid);
                            mjob.OrganizationGUID = new Guid(Session["OrganizationGUID"].ToString());
                            jobGroup = _IJobRepository.GetJobs(mjob);
                        }
                        else
                        {
                            mjob.ActualStartTime = DateTime.Now.AddDays(-29);
                            mjob.ActualEndTime = DateTime.Now;
                            if (Session["UserType"] != null && Session["UserType"].ToString() == "ENT_U")
                            {
                                mjob.AssignedUserGUID = new Guid(Session["UserGUID"].ToString());
                                mjob.OrganizationGUID = new Guid(Session["OrganizationGUID"].ToString());
                                jobGroup = _IJobRepository.GetJobs(mjob);
                            }
                            else
                            {
                                mjob.OrganizationGUID = new Guid(Session["OrganizationGUID"].ToString());
                                jobGroup = _IJobRepository.GetJobs(mjob);
                            }
                        }

                        if (jobGroup != null && jobGroup.Count > 0)
                        {
                            ViewBag.Search = search;
                            if (!string.IsNullOrEmpty(search))
                            {
                                search = search.ToLower();
                                jobGroup = jobGroup.Where(x => (x.CustomerGUID != null ? GetCompanyName(x.CustomerGUID).ToLower() : GetCompanyNameByPO(x.PONumber).ToLower()).Contains(search)
                                    || (!String.IsNullOrEmpty(x.JobName) && x.JobName.ToLower().Contains(search))
                                    || (!String.IsNullOrEmpty(x.PONumber) && x.PONumber.ToLower().Contains(search))
                                    || (!string.IsNullOrEmpty(x.CustomerGUID.ToString()) ? getStoreID(x.CustomerStopGUID.ToString()) : "").Contains(search)
                                    || (_IJobRepository.GetStatusName(Convert.ToInt32(x.StatusCode)).ToLower().Contains(search))
                                    ).ToList();
                            }

                            totalRecord = jobGroup.ToList().Count;
                            totalPage = (totalRecord / (int)ViewBag.pageCountValue) + ((totalRecord % (int)ViewBag.pageCountValue) > 0 ? 1 : 0);
                            
                            ViewBag.TotalRows = totalRecord;

                            jobGroup = jobGroup.OrderBy(a => a.OrganizationGUID).Skip(((page - 1) * (int)ViewBag.pageCountValue)).Take((int)ViewBag.pageCountValue).ToList();

                            foreach (var job in jobGroup.ToList())
                            {
                                JobStatusModel js = new JobStatusModel();
                                js.JobName = job.JobName;
                                js.JobIndexGUID = job.JobGUID.ToString();
                                //  js.JobLogicalID = job.JobFormGUID.ToString();
                                js.UserGUID = job.AssignedUserGUID.ToString();

                                js.PreferredStartTime = job.PreferedStartTime != null ? Session["TimeZoneID"] != null ? _IUserRepository.GetLocalDateTime(job.PreferedStartTime, Session["TimeZoneID"].ToString()) : job.PreferedStartTime.ToString() : "";
                                js.PreferredStartTime = !string.IsNullOrEmpty(js.PreferredStartTime) ? _IUserRepository.GetLocalDateTime(job.PreferedStartTime, Session["TimeZoneID"].ToString()) : "";
                                js.PreferredStartTime = !string.IsNullOrEmpty(js.PreferredStartTime) ? Convert.ToDateTime(js.PreferredStartTime).ToString("MM/dd/yy HH:mm") : "";

                                js.PreferredEndTime = job.PreferedEndTime != null ? Session["TimeZoneID"] != null ? _IUserRepository.GetLocalDateTime(job.PreferedEndTime, Session["TimeZoneID"].ToString()) : job.PreferedEndTime.ToString() : "";
                                js.PreferredEndTime = !string.IsNullOrEmpty(js.PreferredEndTime) ? _IUserRepository.GetLocalDateTime(job.PreferedEndTime, Session["TimeZoneID"].ToString()) : "";
                                js.PreferredEndTime = !string.IsNullOrEmpty(js.PreferredEndTime) ? Convert.ToDateTime(js.PreferredEndTime).ToString("MM/dd/yy HH:mm") : "";

                                js.ActualStartTime = job.ActualStartTime != null ? Session["TimeZoneID"] != null ? _IUserRepository.GetLocalDateTime(job.ActualStartTime, Session["TimeZoneID"].ToString()) : job.ActualStartTime.ToString() : "";
                                js.ActualStartTime = !string.IsNullOrEmpty(js.ActualStartTime) ? _IUserRepository.GetLocalDateTime(job.ActualStartTime, Session["TimeZoneID"].ToString()) : "";
                                js.ActualStartTime = !string.IsNullOrEmpty(js.ActualStartTime) ? Convert.ToDateTime(js.ActualStartTime).ToString("MM/dd/yy HH:mm") : "";

                                js.ActualEndTime = job.PreferedEndTime != null ? Session["TimeZoneID"] != null ? _IUserRepository.GetLocalDateTime(job.ActualEndTime, Session["TimeZoneID"].ToString()) : job.ActualEndTime.ToString() : "";
                                js.ActualEndTime = !string.IsNullOrEmpty(js.ActualEndTime) ? _IUserRepository.GetLocalDateTime(job.ActualEndTime, Session["TimeZoneID"].ToString()) : "";
                                js.ActualEndTime = !string.IsNullOrEmpty(js.ActualEndTime) ? Convert.ToDateTime(js.ActualEndTime).ToString("MM/dd/yy HH:mm") : "";


                                js.LastModifiedDate = job.PreferedEndTime != null ? Session["TimeZoneID"] != null ? _IUserRepository.GetLocalDateTime(job.LastModifiedDate, Session["TimeZoneID"].ToString()) : job.LastModifiedDate.ToString() : "";
                                js.LastModifiedDate = !string.IsNullOrEmpty(js.LastModifiedDate) ? _IUserRepository.GetLocalDateTime(job.LastModifiedDate, Session["TimeZoneID"].ToString()) : "";
                                js.LastModifiedDate = !string.IsNullOrEmpty(js.LastModifiedDate) ? Convert.ToDateTime(js.LastModifiedDate).ToString("MM/dd/yy HH:mm") : "";



                                //  ActualStartTime = job.ActualStartTime.ToString() != "" ? Convert.ToDateTime(job.ActualStartTime).ToString("yyyy/MM/dd HH:mm") : "",//, Session["TimeZoneID"].ToString()
                                js.EstimatedStartTime = job.ActualStartTime != null ? Session["TimeZoneID"] != null ? _IUserRepository.GetLocalDateTime(job.ActualStartTime, Session["TimeZoneID"].ToString()) : job.ActualStartTime.ToString() : "";

                                js.EstimatedStartTime = !string.IsNullOrEmpty(js.EstimatedStartTime) ? _IUserRepository.GetLocalDateTime(job.ActualStartTime, Session["TimeZoneID"].ToString()) : "";
                                js.EstimatedStartTime = !string.IsNullOrEmpty(js.EstimatedStartTime) ? Convert.ToDateTime(js.EstimatedStartTime).ToString("MM/dd/yy HH:mm") : "";
                                //js.AssignedTo = _IGlobalUserRepository.GetGlobalUserByID(new Guid(job.AssignedUserGUID.ToString())) != null ? _IGlobalUserRepository.GetGlobalUserByID(new Guid(job.AssignedUserGUID.ToString())).UserName : "";
                                js.EstimatedDuration = Convert.ToDouble(job.EstimatedDuration);
                                js.Status = _IJobRepository.GetStatusName(Convert.ToInt32(job.StatusCode));
                                // js.CustomerName = !string.IsNullOrEmpty(job.CustomerGUID.ToString()) ? GetCompanyName(new Guid(job.CustomerGUID.ToString())) : "";
                                js.CustomerName = job.CustomerGUID != null ? GetCompanyName(job.CustomerGUID) : GetCompanyNameByPO(job.PONumber);
                                js.StoreID = !string.IsNullOrEmpty(job.CustomerGUID.ToString()) ? getStoreID(job.CustomerStopGUID.ToString()) : "";
                                js.PONumber = job.PONumber;
                                js.statuscode = job.StatusCode != null ? Convert.ToInt32(job.StatusCode) : 0;
                                js.RegionGUID = job.RegionGUID != null ? job.RegionGUID.ToString() : "";
                                js.TerritoryGUID = job.TerritoryGUID != null ? job.TerritoryGUID.ToString() : "";
                                js.SiteAddress = job.ServiceAddress;
                                JobProgress pJobProgress = _IJobRepository.GetJobProgressMismatch(job.JobGUID, js.statuscode);
                                bool mismatch;
                                if (pJobProgress != null && bool.TryParse(pJobProgress.LocationMismatch.ToString(), out mismatch))
                                {
                                    js.locationmismatch = mismatch;
                                }
                                if (job.StatusCode >= 2 && job.AssignedUserGUID != null)
                                {

                                    js.Email = GetEmails(new Guid(job.AssignedUserGUID.ToString()), pOrganizationUsersMap.OrganizationGUID);
                                    js.AssociateContactNumber = GetContactNumber(new Guid(job.AssignedUserGUID.ToString()), pOrganizationUsersMap.OrganizationGUID);
                                    GlobalUser _globaluser = _IGlobalUserRepository.GetGlobalUserByID(new Guid(job.AssignedUserGUID.ToString()));
                                    if (_globaluser != null)
                                    {
                                        js.AssociateName = _globaluser.UserName;
                                        js.AssignedTo = _globaluser.UserName;
                                    }
                                    else
                                    {
                                        js.AssignedTo = "";
                                        js.AssociateName = "";
                                    }
                                }
                                else
                                {
                                    js.Email = "";
                                    js.AssignedTo = "";
                                    js.AssociateName = "";
                                    js.AssociateContactNumber = "";
                                }

                                if (job.CustomerStopGUID != null && job.CustomerStopGUID != Guid.Empty)
                                {
                                    Market _Market = _IMarketRepository.GetMarketByID(new Guid(job.CustomerStopGUID.ToString()));
                                    if (_Market != null)
                                    {
                                        if (!string.IsNullOrEmpty(_Market.RMUserID))
                                        {
                                            GlobalUser _globalUser = _IGlobalUserRepository.GetGlobalUserByUserID(_Market.RMUserID, Session["OrganizationGUID"].ToString());
                                            if (_globalUser != null)
                                            {
                                                UserProfile _userprofile = _IUserProfileRepository.GetUserProfileByUserID(_globalUser.UserGUID, job.OrganizationGUID);
                                                if (_userprofile != null)
                                                {
                                                    js.RegionalManager = _userprofile.FirstName + " " + _userprofile.LastName;
                                                }
                                                else
                                                {
                                                    js.RegionalManager = "";
                                                }
                                            }
                                        }
                                        else
                                        {
                                            js.RegionalManager = "";
                                        }
                                    }
                                    else
                                    {
                                        js.RegionalManager = "";
                                        // js.FieldManager = "";
                                    }
                                }
                                else if (!string.IsNullOrEmpty(job.PONumber))
                                {
                                    POs _po = _IPORepository.GetPObyPoNumber(job.PONumber);
                                    if (_po != null)
                                    {
                                        Market _Market = _IMarketRepository.GetMarketByCustomerID(job.OrganizationGUID, _po.PlaceID, _po.MarketID);
                                        if (_Market != null)
                                        {
                                            if (!string.IsNullOrEmpty(_Market.RMUserID))
                                            {
                                                GlobalUser _globalUser = _IGlobalUserRepository.GetGlobalUserByUserID(_Market.RMUserID, Session["OrganizationGUID"].ToString());
                                                if (_globalUser != null)
                                                {
                                                    UserProfile _userprofile = _IUserProfileRepository.GetUserProfileByUserID(_globalUser.UserGUID, pOrganizationUsersMap.OrganizationGUID);
                                                    if (_userprofile != null)
                                                    {
                                                        js.RegionalManager = _userprofile.FirstName + " " + _userprofile.LastName;
                                                    }
                                                    else
                                                    {
                                                        js.RegionalManager = "";
                                                    }
                                                }
                                            }
                                            else
                                            {
                                                js.RegionalManager = "";
                                            }
                                        }
                                        else
                                        {
                                            js.RegionalManager = "";
                                            //js.FieldManager = "";
                                        }
                                    }
                                    else
                                    {
                                        js.RegionalManager = "";
                                        //js.FieldManager = "";
                                    }
                                }
                                else
                                {
                                    js.RegionalManager = "";
                                    // js.FieldManager = "";
                                }

                                if (job.ManagerUserGUID != null && job.ManagerUserGUID != Guid.Empty)
                                {
                                    GlobalUser _globalUser = _IGlobalUserRepository.GetGlobalUserByID(new Guid(job.ManagerUserGUID.ToString()));
                                    if (_globalUser != null)
                                    {
                                        UserProfile _userprofile = _IUserProfileRepository.GetUserProfileByUserID(_globalUser.UserGUID, pOrganizationUsersMap.OrganizationGUID);
                                        if (_userprofile != null)
                                        {
                                            js.FieldManager = _userprofile.FirstName + " " + _userprofile.LastName;
                                        }
                                        else
                                        {
                                            js.FieldManager = "";
                                        }
                                    }
                                }
                                else
                                {
                                    js.FieldManager = "";
                                }

                                jobStatus.JobStatusModel.Add(js);
                            }
                        }
                        else
                        {
                            ViewBag.TotalRows = 0;
                        }
                        if (!string.IsNullOrEmpty(assigneduserguid) && !string.IsNullOrEmpty(jobindexguid))
                        {
                            GlobalUser _GlobalUser = _IGlobalUserRepository.GetGlobalUserByID(new Guid(assigneduserguid));
                            jobStatus.GlobalUsers = new List<GlobalUserModel>();
                            if (_GlobalUser != null)
                            {
                                jobStatus.GlobalUsers.Add(new GlobalUserModel
                                {
                                    UserGUID = _GlobalUser.UserGUID,
                                    UserName = _GlobalUser.UserName
                                });
                            }
                            if (!string.IsNullOrEmpty(jobindexguid))
                            {
                                jobStatus.JobModel = new JobModel();
                                jobStatus.JobModel.JobName = _IJobRepository.GetJobByID(new Guid(jobindexguid)).JobName;
                                jobStatus.JobModel.JobIndexGUID = new Guid(jobindexguid);
                            }
                        }
                    }

                    if (jobStatus.JobStatusModel != null && jobStatus.JobStatusModel.Count > 0)
                    {
                        if (Session["JobStatusModel"] != null)
                        {
                            Session["JobStatusModel"] = null;
                            Session["JobStatusModel"] = jobStatus.JobStatusModel.ToList();
                        }
                        else
                        {
                            Session["JobStatusModel"] = jobStatus.JobStatusModel.ToList();
                        }
                    }
                    else
                    {
                        Session["JobStatusModel"] = null;
                    }
                    if (!string.IsNullOrEmpty(RowCount))
                        ViewBag.pageCountValue = int.Parse(RowCount);
                    else
                        ViewBag.pageCountValue = 5;
                    return View(jobStatus);
                }
                else
                {
                    return RedirectToAction("SessionTimeOut", "User");
                }
            }
            catch (Exception ex)
            {
                Logger.Error(ex.Message);
                return RedirectToAction("Login", "User");
            }
        }
        private void LoadUnits(int productId, int attrId)
        {
            if (attrId == 0)
            {
                cbmUnits.Enabled = false;
                cbmUnits.SelectedValue = 0;
            }
            else
            {
                cbmUnits.Enabled = true;
                MeasurementUnitService unitService = new MeasurementUnitService();
                MeasurementUnit u = new MeasurementUnit
                {
                    Name = "Tất cả",
                    Id = 0
                };

                units = productLogService.GetUnitsOfProductAttribute(productId, attrId);
                units.Add(u);
                units = units.OrderBy(a => a.Id).ToList();
                if (units != null)
                {
                    cbmUnits.DataSource = units;
                    cbmUnits.DisplayMember = "Name";
                    cbmUnits.ValueMember = "Id";
                }
            }
        }
        private void LoadAttributes(int productId)
        {
            if (productId == 0)
            {
                cbmAttrs.Enabled = false;
                cbmAttrs.SelectedValue = 0;
                cbmUnits.Enabled = false;
                cbmUnits.SelectedValue = 0;
            }
            else
            {
                cbmAttrs.Enabled = true;
                BaseAttributeService attrService = new BaseAttributeService();
                BaseAttribute ba = new BaseAttribute
                {
                    AttributeName = "Tất cả",
                    Id = 0
                };

                ProductService productService = new ProductService();
                Product p = productService.GetProduct(productId);
                List<ProductAttribute> pas = p.ProductAttributes.ToList();
                attrs = new List<BaseAttribute>();
                attrs.Add(ba);
                foreach (ProductAttribute pa in pas)
                {
                    attrs.Add(pa.BaseAttribute);
                }
                attrs = attrs.OrderBy(a => a.Id).ToList();
                if (attrs != null)
                {
                    cbmAttrs.DataSource = attrs;
                    cbmAttrs.DisplayMember = "AttributeName";
                    cbmAttrs.ValueMember = "Id";
                }
                LoadUnits(productId, 0);
            }
        }
 private void LoadProducts(int productTypeId)
 {
     if (productTypeId == 0)
     {
         cbmProducts.Enabled = false;
         cbmProducts.SelectedValue = 0;
         cbmAttrs.Enabled = false;
         cbmAttrs.SelectedValue = 0;
         cbmUnits.Enabled = false;
         cbmUnits.SelectedValue = 0;
     }
     else
     {
         cbmProducts.Enabled = true;
         ProductService productService = new ProductService();
         Product product = new Product
         {
             ProductName = "Tất cả",
             Id = 0
         };
         products = productService.GetProducts().Where(p => p.ProductType == productTypeId).ToList();
         products.Add(product);
         products = products.OrderBy(p => p.Id).ToList();
         if (products != null)
         {
             cbmProducts.DataSource = products;
             cbmProducts.DisplayMember = "ProductName";
             cbmProducts.ValueMember = "Id";
         }
         LoadAttributes(0);
     }
 }