Ejemplo n.º 1
1
        public void GetExcel(String plazasId, String patronesId, String clientesId, 
            String gruposId, String opcion, String valor, String statusId)
        {
            Usuario user = Session["UsuarioData"] as Usuario;
            var plazasAsignadas = (from x in db.TopicosUsuarios
                                   where x.usuarioId.Equals(user.Id)
                                   && x.tipo.Equals("P")
                                   select x.topicoId);

            var clientesAsignados = (from x in db.TopicosUsuarios
                                     where x.usuarioId.Equals(user.Id)
                                     && x.tipo.Equals("C")
                                     select x.topicoId);

            var patronesAsignados = (from x in db.TopicosUsuarios
                                     where x.usuarioId.Equals(user.Id)
                                     && x.tipo.Equals("B")
                                     select x.topicoId);

            List<Acreditado> allCust = new List<Acreditado>();

            var acreditados = from s in db.Acreditados
                              join cli in db.Clientes on s.clienteId equals cli.Id
                             where plazasAsignadas.Contains(s.Cliente.Plaza_id) &&
                                   clientesAsignados.Contains(s.Cliente.Id) &&
                                   patronesAsignados.Contains(s.PatroneId)
                             select s;

            if (!String.IsNullOrEmpty(plazasId))
            {
                @ViewBag.pzaId = plazasId;
                int idPlaza = int.Parse(plazasId.Trim());
                acreditados = acreditados.Where(s => s.Cliente.Plaza_id.Equals(idPlaza));
            }
            if (!String.IsNullOrEmpty(patronesId))
            {
                @ViewBag.patId = patronesId;
                int idPatron = int.Parse(patronesId.Trim());
                acreditados = acreditados.Where(s => s.PatroneId.Equals(idPatron));
            }

            if (!String.IsNullOrEmpty(clientesId))
            {
                @ViewBag.cteId = clientesId;
                int idCliente = int.Parse(clientesId.Trim());
                acreditados = acreditados.Where(s => s.Cliente.Id.Equals(idCliente));
            }

            if (!String.IsNullOrEmpty(gruposId))
            {
                @ViewBag.gpoId = gruposId;
                int idGrupo = int.Parse(gruposId.Trim());
                acreditados = acreditados.Where(s => s.Cliente.Grupo_id.Equals(idGrupo));
            }

            if (!String.IsNullOrEmpty(opcion))
            {
                @ViewBag.opBuscador = opcion;
                @ViewBag.valBuscador = valor;
                TempData["buscador"] = "0";
                switch (opcion)
                {
                    case "1":
                        acreditados = acreditados.Where(s => s.Patrone.registro.Contains(valor));
                        break;
                    case "2":
                        acreditados = acreditados.Where(s => s.numeroAfiliacion.Contains(valor));
                        break;
                    case "3":
                        acreditados = acreditados.Where(s => s.CURP.Contains(valor));
                        break;
                    case "4":
                        acreditados = acreditados.Where(s => s.RFC.Contains(valor));
                        break;
                    case "5":
                        acreditados = acreditados.Where(s => s.nombreCompleto.Contains(valor));
                        break;
                    case "6":
                        acreditados = acreditados.Where(s => s.fechaAlta.ToString().Contains(valor));
                        break;
                    case "7":
                        acreditados = acreditados.Where(s => s.fechaBaja.ToString().Contains(valor));
                        break;
                    case "8":
                        acreditados = acreditados.Where(s => s.sdi.ToString().Contains(valor));
                        break;
                    case "9":
                        acreditados = acreditados.Where(s => s.Cliente.claveCliente.Contains(valor));
                        break;
                    case "10":
                        acreditados = acreditados.Where(s => s.Cliente.Grupos.nombre.Contains(valor));
                        break;
                    case "11":
                        acreditados = acreditados.Where(s => s.ocupacion.Contains(valor));
                        break;
                    case "12":
                        acreditados = acreditados.Where(s => s.Cliente.Plaza.cveCorta.Contains(valor));
                        break;
                }
            }

            if (statusId != null)
            {
                @ViewBag.statusId = statusId;

                if (statusId.Trim().Equals("A"))
                {
                    ViewBag.statusId = statusId;
                    acreditados = acreditados.Where(s => !s.fechaBaja.HasValue);
                }
                else if (statusId.Trim().Equals("B"))
                {
                    ViewBag.statusId = statusId;
                    acreditados = acreditados.Where(s => s.fechaBaja.HasValue);
                }
            }

            allCust = acreditados.ToList();

            WebGrid grid = new WebGrid(source: allCust, canPage: false, canSort: false);
            List<WebGridColumn> gridColumns = new List<WebGridColumn>();

            gridColumns.Add(grid.Column("Patrone.registro", "Registro"));
            gridColumns.Add(grid.Column("apellidoPaterno", "Apellido Paterno"));
            gridColumns.Add(grid.Column("apellidoMaterno", "Apellido Materno"));
            gridColumns.Add(grid.Column("nombre", "Nombre"));
            gridColumns.Add(grid.Column("nombreCompleto", "Nombre Completo"));
            gridColumns.Add(grid.Column("curp","CURP"));
            gridColumns.Add(grid.Column("rfc", "RFC"));
            gridColumns.Add(grid.Column("ocupacion", "Ocupación"));
            gridColumns.Add(grid.Column("idGrupo", "Grupo"));
            gridColumns.Add(grid.Column("numeroAfiliacion", "Numero Afiliación"));
            gridColumns.Add(grid.Column("numeroCredito", "Numero Credito"));
            gridColumns.Add(grid.Column("fechaAlta", "Alta", format: (item) => String.Format("{0:yyyy-MM-dd}", item.fechaAlta)));
            gridColumns.Add(grid.Column("fechaBaja", "Fecha Baja", format: (item) => item.fechaBaja != null ? String.Format("{0:yyyy-MM-dd}", item.fechaBaja) : String.Empty));
            gridColumns.Add(grid.Column("Cliente.claveCliente", "Cliente"));
            gridColumns.Add(grid.Column("fechaInicioDescuento", "Inicio descuento", format: (item) => String.Format("{0:yyyy-MM-dd}", item.fechaAlta)));
            gridColumns.Add(grid.Column("fechaFinDescuento", "Fin descuento", format: (item) => item.fechaFinDescuento != null ? String.Format("{0:yyyy-MM-dd}", item.fechaFinDescuento) : String.Empty));
            gridColumns.Add(grid.Column("smdv", "SMDV"));
            gridColumns.Add(grid.Column("sdi", "SDI"));
            gridColumns.Add(grid.Column("sd", "SD"));
            gridColumns.Add(grid.Column("vsm", "VSM"));
            gridColumns.Add(grid.Column("porcentaje", "Porcentaje"));
            gridColumns.Add(grid.Column("cuotaFija", "Cuota Fija"));
            gridColumns.Add(grid.Column("descuentoBimestral", "Descuento Bimestral"));
            gridColumns.Add(grid.Column("descuentoMensual", "Descuento Mensual"));
            gridColumns.Add(grid.Column("descuentoSemanal", "Descuento Semanal"));
            gridColumns.Add(grid.Column("descuentoCatorcenal", "Descuento Catorcenal"));
            gridColumns.Add(grid.Column("descuentoQuincenal", "Descuento Quincenal"));
            gridColumns.Add(grid.Column("descuentoVeintiochonal", "Descuento Veintiochonal"));
            gridColumns.Add(grid.Column("descuentoDiario", "Descuento Diario"));
            gridColumns.Add(grid.Column("Plaza.descripcion", "Plaza"));
            /*grid.Column("Cliente.descripcion", "Cliente/Ubicación"),*/

            string gridData = grid.GetHtml(
                columns: grid.Columns(gridColumns.ToArray())
                    ).ToString();

            Response.ClearContent();
            DateTime date = DateTime.Now;
            String fileName = "Acreditados-" + date.ToString("ddMMyyyyHHmm") + ".xls";
            Response.AddHeader("content-disposition", "attachment; filename=" + fileName);
            Response.ContentType = "application/excel";
            Response.Write(gridData);
            Response.End();
        }
        public PreComputedGridDataSource(WebGrid grid, IEnumerable<dynamic> values, int totalRows) {
            Debug.Assert(grid != null);
            Debug.Assert(values != null);

            _totalRows = totalRows;
            _rows = values.Select((value, index) => new WebGridRow(grid, value: value, rowIndex: index)).ToList();
        }
 public WebGridRow(WebGrid webGrid, object value, int rowIndex)
 {
     _grid     = webGrid;
     _value    = value;
     _rowIndex = rowIndex;
     _dynamic  = value as IDynamicMetaObjectProvider;
 }
        private static string GetRowStyle(WebGrid webGrid, int rowIndex, string rowStyle, string alternatingRowStyle, string selectedRowStyle)
        {
            StringBuilder style = new StringBuilder();

            if (rowIndex % 2 == 0)
            {
                if (!String.IsNullOrEmpty(rowStyle))
                {
                    style.Append(rowStyle);
                }
            }
            else
            {
                if (!String.IsNullOrEmpty(alternatingRowStyle))
                {
                    style.Append(alternatingRowStyle);
                }
            }

            if (!String.IsNullOrEmpty(selectedRowStyle) && (rowIndex == webGrid.SelectedIndex))
            {
                if (style.Length > 0)
                {
                    style.Append(" ");
                }
                style.Append(selectedRowStyle);
            }
            return(style.ToString());
        }
Ejemplo n.º 5
0
        /// <summary>
        /// Small Util function, that adds columns and plain formatting for 
        /// the column values resulting in a huge performance gain
        /// </summary>
        /// <param name="data">The web grid data</param>
        /// <returns></returns>
        public static IHtmlString GridHtmlFromExpandoList(IEnumerable<ExpandoObject> data)
        {
            WebGrid grid = new WebGrid(
                    source: data
                );

            var cols = new List<WebGridColumn>();

            if (data.Count() > 0)
            {
                IEnumerable<KeyValuePair<string, Object>> example = data.First();

                foreach (var pair in example)
                    cols.Add(grid.Column(
                        columnName: pair.Key,
                        //Seems that specifying a formatter saves the web grid ridiculous amounts of time
                        format: (item => ((IDictionary<String, Object>)item.Value)[pair.Key])
                    ));
            }

            return grid.GetHtml(
                tableStyle: "table",
                columns: cols
            );
        }
Ejemplo n.º 6
0
        public PreComputedGridDataSource(WebGrid grid, IEnumerable <dynamic> values, int totalRows)
        {
            Debug.Assert(grid != null);
            Debug.Assert(values != null);

            _totalRows = totalRows;
            _rows      = values.Select((value, index) => new WebGridRow(grid, value: value, rowIndex: index)).ToList();
        }
 private static bool ShowSortableColumnHeader(
     WebGrid grid,
     WebGridColumn column
     )
 {
     return(grid.CanSort &&
            column.CanSort &&
            !column.ColumnName.IsEmpty());
 }
Ejemplo n.º 8
0
 private static WebGridColumn AddVisibleCheckBoxColumnForCheckedItems(WebGrid webGrid, string checkBoxValue, bool defaultCheckedState)
 {
     var newVisibleCheckBoxColumn = webGrid.Column(header: "{}",// This header will be replaced by checkbox
     format: item => new HelperResult(writer =>
     {
         var id = item.Value.GetType().GetProperty(checkBoxValue).GetValue(item.Value, null).ToString();
         writer.Write("<input class=\"singleCheckBox\" name=\"selectedRows\" value=\"" + id + "\" id=\"checked" + id + "\" type=\"checkbox\" " + (defaultCheckedState ? "checked=\"checked\"" : string.Empty) + "\" />");
     }));
     return newVisibleCheckBoxColumn;
 }
Ejemplo n.º 9
0
 private static WebGridColumn AddInvisibleCheckboxColumnForUncheckedItems(WebGrid webGrid, string checkBoxValue, bool defaultCheckedState)
 {
     var newInvisibleCheckBoxColumn = webGrid.Column(header: "",
     format: item => new HelperResult(writer =>
     {
         var id = item.Value.GetType().GetProperty(checkBoxValue).GetValue(item.Value, null).ToString();
         writer.Write("<input class=\"singleHiddenCheckBox\" name=\"unSelectedRows\" value=\"" + id + "\" id=\"unChecked" + id + "\" type=\"checkbox\" " + (defaultCheckedState ? "checked=\"checked\"" : string.Empty) + " />");
     }), style: "invisiblecolumn");
     return newInvisibleCheckBoxColumn;
 }
Ejemplo n.º 10
0
        /// <summary>
        /// Partial view used for lazy loading of web grid with no columns/formatting
        /// </summary>
        /// <param name="totalColumns">The columns for the grid</param>
        /// <param name="totalRows">The rows for the grid</param>
        /// <returns></returns>
        public PartialViewResult NoColumnsGrid(int totalColumns, int totalRows)
        {
            var data = generateData(totalColumns, totalRows);

            var noColumnsGrid = new WebGrid(
                source: data
            );

            return PartialView("BaseGrid", noColumnsGrid.GetHtml("table"));
        }
        public WebGridDataSource(WebGrid grid, IEnumerable <dynamic> values, Type elementType, bool canPage, bool canSort)
        {
            Debug.Assert(grid != null);
            Debug.Assert(values != null);

            _grid        = grid;
            _values      = values;
            _elementType = elementType;
            _canPage     = canPage;
            _canSort     = canSort;
        }
Ejemplo n.º 12
0
 private static String GridLink(WebGrid webGrid, string url, string text)
 {
     TagBuilder builder = new TagBuilder("a");
     builder.SetInnerText(text);
     builder.MergeAttribute("href", url);
     if (webGrid.IsAjaxEnabled)
     {
         builder.MergeAttribute("data-swhglnk", "true");
     }
     return builder.ToString(TagRenderMode.Normal);
 }
        public static IHtmlString GridLink(WebGrid webGrid, string url, string text)
        {
            TagBuilder builder = new TagBuilder("a");

            builder.SetInnerText(text);
            builder.MergeAttribute("href", url);
            if (webGrid.IsAjaxEnabled)
            {
                builder.MergeAttribute("data-swhglnk", "true");
            }
            return(builder.ToHtmlString(TagRenderMode.Normal));
        }
        public static HelperResult GridInitScript(
            WebGrid webGrid,
            HttpContextBase httpContext
            )
        {
            return(new HelperResult(
                       __razor_helper_writer =>
            {
                if (!webGrid.IsAjaxEnabled)
                {
                    return;
                }
                if (!IsGridScriptRendered(httpContext))
                {
                    SetGridScriptRendered(httpContext, true);

                    WriteLiteralTo(
                        @__razor_helper_writer,
                        "        <script type=\"text/javascript\">\r\n        (function($) {\r\n            $.fn" +
                        ".swhgLoad = function(url, containerId, callback) {\r\n                url = url + " +
                        "(url.indexOf(\'?\') == -1 ? \'?\' : \'&\') + \'__swhg=\' + new Date().getTime();\r\n\r\n    " +
                        "            $(\'<div/>\').load(url + \' \' + containerId, function(data, status, xhr" +
                        ") {\r\n                    $(containerId).replaceWith($(this).html());\r\n          " +
                        "          if (typeof(callback) === \'function\') {\r\n                        callba" +
                        "ck.apply(this, arguments);\r\n                    }\r\n                });\r\n        " +
                        "        return this;\r\n            }\r\n\r\n            $(function() {\r\n             " +
                        "   $(\'table[data-swhgajax=\"true\"],span[data-swhgajax=\"true\"]\').each(function() {" +
                        "\r\n                    var self = $(this);\r\n                    var containerId =" +
                        " \'#\' + self.data(\'swhgcontainer\');\r\n                    var callback = getFuncti" +
                        "on(self.data(\'swhgcallback\'));\r\n\r\n                    $(containerId).parent().de" +
                        "legate(containerId + \' a[data-swhglnk=\"true\"]\', \'click\', function() {\r\n         " +
                        "               $(containerId).swhgLoad($(this).attr(\'href\'), containerId, callba" +
                        "ck);\r\n                        return false;\r\n                    });\r\n          " +
                        "      })\r\n            });\r\n\r\n            function getFunction(code, argNames) {\r" +
                        "\n                argNames = argNames || [];\r\n                var fn = window, pa" +
                        "rts = (code || \"\").split(\".\");\r\n                while (fn && parts.length) {\r\n  " +
                        "                  fn = fn[parts.shift()];\r\n                }\r\n                if" +
                        " (typeof (fn) === \"function\") {\r\n                    return fn;\r\n               " +
                        " }\r\n                argNames.push(code);\r\n                return Function.constr" +
                        "uctor.apply(null, argNames);\r\n            }\r\n        })(jQuery);\r\n        </scri" +
                        "pt>\r\n"
                        );
                }
            }
                       ));
        }
Ejemplo n.º 15
0
        public static MvcHtmlString SortDirection(this HtmlHelper helper, ref WebGrid grid, String columnName)
        {
            String html = "";

            if (grid.SortColumn == columnName && grid.SortDirection == System.Web.Helpers.SortDirection.Ascending)
            {
                html = "▼";
            }
            else if (grid.SortColumn == columnName && grid.SortDirection == System.Web.Helpers.SortDirection.Descending)
            {
                html = "▲";
            }
            else
            {
                html = "";
            }

            return MvcHtmlString.Create(html);
        }
        public FileStreamResult ExportData()
        {
            EmployeeDBContext db = new EmployeeDBContext();
            List<Employee> employees = new List<Employee>();
            employees = db.Employees.ToList();

            WebGrid webGrid = new WebGrid(employees, canPage: true, rowsPerPage: 10);
            string gridData = webGrid.GetHtml(
                columns: webGrid.Columns(
                webGrid.Column(columnName: "Name", header: "Name"),
                webGrid.Column(columnName: "Designation", header: "Designation"),
                webGrid.Column(columnName: "Gender", header: "Gender"),
                webGrid.Column(columnName: "Salary", header: "Salary"),
                webGrid.Column(columnName: "City", header: "City"),
                webGrid.Column(columnName: "State", header: "State"),
                webGrid.Column(columnName: "Zip", header: "Zip")
            )).ToString();

            StringBuilder pdfExportData = new StringBuilder();
            pdfExportData.AppendLine("<html><head><style>.webgrid-table {font-family: Arial,Helvetica,sans-serif;font-size: 14px;font-weight: normal;width: 650px;display: table;border-collapse: collapse;border: solid px #C5C5C5;background-color: white;}</style>");
            pdfExportData.AppendLine("</head><body>" + gridData + "</body></html>");
            

            var bytes  = System.Text.Encoding.UTF8.GetBytes(pdfExportData.ToString());
            using(var stream = new MemoryStream(bytes))
            {
                var outStream = new MemoryStream();
                var doc= new iTextSharp.text.Document(PageSize.A4,50,50,50,50);
                var writer = PdfWriter.GetInstance(doc,outStream);
                writer.CloseStream = false;
                doc.Open();

                var xmlWorker = iTextSharp.tool.xml.XMLWorkerHelper.GetInstance();
                xmlWorker.ParseXHtml(writer,doc,stream,System.Text.Encoding.UTF8);
                doc.Close();
                outStream.Position = 0;
                return new FileStreamResult(outStream,"application/pdf");
            }
           
        }
        public static HelperResult GridInitScript(WebGrid webGrid, HttpContextBase httpContext)
        {
            return new HelperResult(__razor_helper_writer =>
            {
                if (!webGrid.IsAjaxEnabled)
                {
                    return;
                }
                if (!IsGridScriptRendered(httpContext))
                {
                    SetGridScriptRendered(httpContext, true);

                    WriteLiteralTo(@__razor_helper_writer, "        <script type=\"text/javascript\">\r\n        (function($) {\r\n            $.fn" +
                                                           ".swhgLoad = function(url, containerId, callback) {\r\n                url = url + " +
                                                           "(url.indexOf(\'?\') == -1 ? \'?\' : \'&\') + \'__swhg=\' + new Date().getTime();\r\n\r\n    " +
                                                           "            $(\'<div/>\').load(url + \' \' + containerId, function(data, status, xhr" +
                                                           ") {\r\n                    $(containerId).replaceWith($(this).html());\r\n          " +
                                                           "          if (typeof(callback) === \'function\') {\r\n                        callba" +
                                                           "ck.apply(this, arguments);\r\n                    }\r\n                });\r\n        " +
                                                           "        return this;\r\n            }\r\n\r\n            $(function() {\r\n             " +
                                                           "   $(\'table[data-swhgajax=\"true\"],span[data-swhgajax=\"true\"]\').each(function() {" +
                                                           "\r\n                    var self = $(this);\r\n                    var containerId =" +
                                                           " \'#\' + self.data(\'swhgcontainer\');\r\n                    var callback = getFuncti" +
                                                           "on(self.data(\'swhgcallback\'));\r\n\r\n                    $(containerId).parent().de" +
                                                           "legate(containerId + \' a[data-swhglnk=\"true\"]\', \'click\', function() {\r\n         " +
                                                           "               $(containerId).swhgLoad($(this).attr(\'href\'), containerId, callba" +
                                                           "ck);\r\n                        return false;\r\n                    });\r\n          " +
                                                           "      })\r\n            });\r\n\r\n            function getFunction(code, argNames) {\r" +
                                                           "\n                argNames = argNames || [];\r\n                var fn = window, pa" +
                                                           "rts = (code || \"\").split(\".\");\r\n                while (fn && parts.length) {\r\n  " +
                                                           "                  fn = fn[parts.shift()];\r\n                }\r\n                if" +
                                                           " (typeof (fn) === \"function\") {\r\n                    return fn;\r\n               " +
                                                           " }\r\n                argNames.push(code);\r\n                return Function.constr" +
                                                           "uctor.apply(null, argNames);\r\n            }\r\n        })(jQuery);\r\n        </scri" +
                                                           "pt>\r\n");
                }
            });
        }
        public void ExportData()
        {
            EmployeeDBContext db = new EmployeeDBContext();
            List<Employee> employees = new List<Employee>();
            employees = db.Employees.ToList();

            WebGrid webGrid = new WebGrid(employees, canPage: true, rowsPerPage: 10);
            string gridData = webGrid.GetHtml(
                columns: webGrid.Columns(
                webGrid.Column(columnName: "Name", header: "Name"),
                webGrid.Column(columnName: "Designation", header: "Designation"),
                webGrid.Column(columnName: "Gender", header: "Gender"),
                webGrid.Column(columnName: "Salary", header: "Salary"),
                webGrid.Column(columnName: "City", header: "City"),
                webGrid.Column(columnName: "State", header: "State"),
                webGrid.Column(columnName: "Zip", header: "Zip")
            )).ToString();

            Response.ClearContent();
            Response.AddHeader("content-disposition","attachment; filename=Employee-Details.xls");
            Response.ContentType = "applicatiom/excel";
            Response.Write(gridData);
            Response.End();
        }
        public FileStreamResult GETPdf()
        {
            List<test> all = new List<test>();
            //  item1 = Session["selecdate"].ToString();
            //  Console.Write(item1);
            using (ReportSupEntities1 dc = new ReportSupEntities1())
            {
                //   all = (from e in dc).ToList();
                all = (from e in dc.sp_matrix_weekdays(15, "08 - 17 - 2015") select new test { Nombre = e.name, FechaEntradaMonday = e.Hora_de_LLegada_Lunes, FechaSalidaMonday = e.Hora_de_salida_Lunes, HorasMonday = e.Monday, FechaEntradaTuesday = e.Hora_de_LLegada_Martes, FechaSalidaTuesday = e.Hora_de_salida_Martes, HorasTuesday = e.Tuesday, FechaEntradaWendnsday = e.Hora_de_LLegada_Miercoles, FechaSalidaWendnsday = e.Hora_de_salida_Miercoles, HorasWendnsday = e.Wednsday, FechaEntradaThursday = e.Hora_de_LLegada_Jueves, FechaSalidaThursday = e.Hora_de_salida_Jueves, HorasThursday = e.Thursday, FechaEntradaFriday = e.Hora_de_LLegada_Viernes, FechaSalidaFriday = e.Hora_de_salida_Viernes, HorasFriday = e.Friday, FechaEntradaSaturday = e.Hora_de_LLegada_Sabado, FechaSalidaSaturday = e.Hora_de_salida_Sabado, HorasSaturday = e.Saturday, FechaEntradaSunday = e.Hora_de_LLegada_Domingo, FechaSalidaSunday = e.Hora_de_salida_Domingo, HorasSunday = e.Sunday }).ToList();
            }

            WebGrid grid = new WebGrid(source: all, canPage: false, canSort: false);
            string gridHtml = grid.GetHtml(
            columns: grid.Columns(
            grid.Column("Nombre", "Nombre", canSort: true, style: "name"),
                         grid.Column("FechaEntradaMonday", "Fecha de Entrada LUNES"),
            grid.Column("FechaSalidaMonday", "Fecha de Salida"),
                            grid.Column("HorasMonday", "Horas Trabajadas Lunes"),
                         grid.Column("FechaEntradaTuesday", "Fecha de Entrada MARTES"),
            grid.Column("FechaSalidaTuesday", "Fecha de Salida"),
                          grid.Column("HorasTuesday", "Horas Trabajadas Martes"),
                         grid.Column("FechaEntradaWendnsday", "Fecha de Entrada MIERCOLES"),
            grid.Column("FechaSalidaWendnsday", "Fecha de Salida"),
                          grid.Column("HorasWendnsday", "Horas Trabajadas Miertcoles"),
                         grid.Column("FechaEntradaThursday", "Fecha de JUEVES"),
            grid.Column("FechaSalidaThursday", "Fecha de Salida"),
                        grid.Column("HorasThursday", "Horas Trabajadas Jueves"),
                        grid.Column("FechaEntradaFriday", "Fecha de Entrada VIERNES"),
            grid.Column("FechaSalidaFriday", "Fecha de Salida"),
                        grid.Column("HorasFriday", "Horas Trabajadas Viernes"),
                         grid.Column("FechaEntradaSaturday", "Fecha de Sabado"),
            grid.Column("FechaSalidaSaturday", "Fecha de Salida"),
                         grid.Column("HorasSaturday", "Horas Trabajadas Sabado"),
                         grid.Column("FechaEntradaSunday", "Fecha de DOMINGO"),
            grid.Column("FechaSalidaSunday", "Fecha de Salida")
              )
                ).ToHtmlString();

            string exportData = String.Format("<html><head>{0}</head><body><div><span>Reporte</span></div>{1}</body></html>", "<style>table{ border-spacing: 1000px; border-collapse: separate; .name {width: 550px;} }</style>", gridHtml);
            var bytes = System.Text.Encoding.UTF8.GetBytes(exportData);
            using (var input = new MemoryStream(bytes))
            {
                var output = new MemoryStream();
                var document = new iTextSharp.text.Document(PageSize.A0, 50, 50, 25, 50);
                var writer = PdfWriter.GetInstance(document, output);
                writer.CloseStream = false;
                document.Open();

                var xmlWorker = iTextSharp.tool.xml.XMLWorkerHelper.GetInstance();
                xmlWorker.ParseXHtml(writer, document, input, System.Text.Encoding.UTF8);
                document.Close();
                output.Position = 0;
                string path = this.Server.MapPath(".") + "Libraries\\Documents\\doc.pdf";

                //        return new FileStreamResult(output, "C:\application.pdf");
                return new FileStreamResult(output, "aplication/pdf")
                {
                    FileDownloadName = "PDFPERFORMACE" + ".pdf"
                };
            }
        }
Ejemplo n.º 20
0
 public static MvcHtmlString Grid(this HtmlHelper html, IEnumerable<dynamic> Modal, IEnumerable<WebGridColumn> columns)
 {
     var grid = new WebGrid(Modal, canPage: true, rowsPerPage: 10, selectionFieldName: "selectedRow", ajaxUpdateContainerId: "gridContent");
     var gridHtml = grid.GetHtml(columns: columns);
     return new MvcHtmlString(gridHtml.ToHtmlString());
 }
Ejemplo n.º 21
0
    private static HelperResult PagerList(
        WebGrid webGrid,
        WebGridPagerModes mode,
        string firstText,
        string previousText,
        string nextText,
        string lastText,
        int numericLinksCount,
        bool explicitlyCalled)
    {
        int currentPage = webGrid.PageIndex;
        int totalPages = webGrid.PageCount;
        int lastPage = totalPages - 1;

        var ul = new TagBuilder("ul");
        var li = new List<TagBuilder>();

        if (webGrid.TotalRowCount <= webGrid.PageCount)
        {
            return new HelperResult(writer =>
            {
                writer.Write(string.Empty);
            });
        }

        if (ModeEnabled(mode, WebGridPagerModes.FirstLast))
        {
            if (String.IsNullOrEmpty(firstText))
            {
                firstText = "Перв.";
            }

            var part = new TagBuilder("li")
            {
                InnerHtml = GridLink(webGrid, webGrid.GetPageUrl(0), firstText)
            };

            if (currentPage == 0)
            {
                part.MergeAttribute("class", "disabled");
            }

            li.Add(part);

        }

        if (ModeEnabled(mode, WebGridPagerModes.NextPrevious))
        {
            if (String.IsNullOrEmpty(previousText))
            {
                previousText = "Пред.";
            }

            int page = currentPage == 0 ? 0 : currentPage - 1;

            var part = new TagBuilder("li")
            {
                InnerHtml = GridLink(webGrid, webGrid.GetPageUrl(page), previousText)
            };

            if (currentPage == 0)
            {
                part.MergeAttribute("class", "disabled");
            }

            li.Add(part);

        }

        if (ModeEnabled(mode, WebGridPagerModes.Numeric) && (totalPages > 1))
        {
            int last = currentPage + (numericLinksCount / 2);
            int first = last - numericLinksCount + 1;
            if (last > lastPage)
            {
                first -= last - lastPage;
                last = lastPage;
            }
            if (first < 0)
            {
                last = Math.Min(last + (0 - first), lastPage);
                first = 0;
            }
            for (int i = first; i <= last; i++)
            {

                var pageText = (i + 1).ToString(CultureInfo.InvariantCulture);
                var part = new TagBuilder("li")
                {
                    InnerHtml = GridLink(webGrid, webGrid.GetPageUrl(i), pageText)
                };

                if (i == currentPage)
                {
                    part.MergeAttribute("class", "active");
                }

                li.Add(part);

            }
        }

        if (ModeEnabled(mode, WebGridPagerModes.NextPrevious))
        {
            if (String.IsNullOrEmpty(nextText))
            {
                nextText = "След.";
            }

            int page = currentPage == lastPage ? lastPage : currentPage + 1;

            var part = new TagBuilder("li")
            {
                InnerHtml = GridLink(webGrid, webGrid.GetPageUrl(page), nextText)
            };

            if (currentPage == lastPage)
            {
                part.MergeAttribute("class", "disabled");
            }

            li.Add(part);

        }

        if (ModeEnabled(mode, WebGridPagerModes.FirstLast))
        {
            if (String.IsNullOrEmpty(lastText))
            {
                lastText = "Посл.";
            }

            var part = new TagBuilder("li")
            {
                InnerHtml = GridLink(webGrid, webGrid.GetPageUrl(lastPage), lastText)
            };

            if (currentPage == lastPage)
            {
                part.MergeAttribute("class", "disabled");
            }

            li.Add(part);

        }

        ul.InnerHtml = string.Join("", li);

        var html = "";
        if (explicitlyCalled && true)
        {
            var span = new TagBuilder("span");
            span.MergeAttribute("data-swhgajax", "true");
            span.MergeAttribute("data-swhgcontainer", webGrid.AjaxUpdateContainerId);
            span.MergeAttribute("data-swhgcallback", webGrid.AjaxUpdateCallback);

            span.InnerHtml = ul.ToString();
            html = span.ToString();

        }
        else
        {
            html = ul.ToString();
        }

        return new HelperResult(writer =>
        {
            writer.Write(html);
        });
    }
        public static HelperResult Table(WebGrid webGrid,
                                         HttpContextBase httpContext,
                                         string tableStyle,
                                         string headerStyle,
                                         string footerStyle,
                                         string rowStyle,
                                         string alternatingRowStyle,
                                         string selectedRowStyle,
                                         string caption,
                                         bool displayHeader,
                                         bool fillEmptyRows,
                                         string emptyRowCellValue,
                                         IEnumerable <WebGridColumn> columns,
                                         IEnumerable <string> exclusions,
                                         Func <dynamic, object> footer,
                                         object htmlAttributes)
        {
            return(new HelperResult(__razor_helper_writer =>
            {
                if (emptyRowCellValue == null)
                {
                    emptyRowCellValue = "&nbsp;";
                }

                WriteTo(@__razor_helper_writer, GridInitScript(webGrid, httpContext));

                var htmlAttributeDictionary = TypeHelper.ObjectToDictionary(htmlAttributes);
                if (webGrid.IsAjaxEnabled)
                {
                    htmlAttributeDictionary["data-swhgajax"] = "true";
                    htmlAttributeDictionary["data-swhgcontainer"] = webGrid.AjaxUpdateContainerId;
                    htmlAttributeDictionary["data-swhgcallback"] = webGrid.AjaxUpdateCallback;
                }

                WriteLiteralTo(@__razor_helper_writer, "    <table");

                WriteTo(@__razor_helper_writer, tableStyle.IsEmpty() ? null : Raw(" class=\"" + HttpUtility.HtmlAttributeEncode(tableStyle) + "\""));

                WriteTo(@__razor_helper_writer, PrintAttributes(htmlAttributeDictionary));

                WriteLiteralTo(@__razor_helper_writer, ">\r\n");

                if (!caption.IsEmpty())
                {
                    WriteLiteralTo(@__razor_helper_writer, "        <caption>");

                    WriteTo(@__razor_helper_writer, caption);

                    WriteLiteralTo(@__razor_helper_writer, "</caption>\r\n");
                }

                if (displayHeader)
                {
                    WriteLiteralTo(@__razor_helper_writer, "    <thead>\r\n        <tr");

                    WriteTo(@__razor_helper_writer, CssClass(headerStyle));

                    WriteLiteralTo(@__razor_helper_writer, ">\r\n");

                    foreach (var column in columns)
                    {
                        WriteLiteralTo(@__razor_helper_writer, "            <th scope=\"col\">\r\n");

                        if (ShowSortableColumnHeader(webGrid, column))
                        {
                            var text = column.Header.IsEmpty() ? column.ColumnName : column.Header;

                            WriteTo(@__razor_helper_writer, GridLink(webGrid, webGrid.GetSortUrl(column.ColumnName), text));
                        }
                        else
                        {
                            WriteTo(@__razor_helper_writer, column.Header ?? column.ColumnName);
                        }

                        WriteLiteralTo(@__razor_helper_writer, "            </th>\r\n");
                    }

                    WriteLiteralTo(@__razor_helper_writer, "        </tr>\r\n    </thead>\r\n");
                }

                if (footer != null)
                {
                    WriteLiteralTo(@__razor_helper_writer, "    <tfoot>\r\n        <tr ");

                    WriteTo(@__razor_helper_writer, CssClass(footerStyle));

                    WriteLiteralTo(@__razor_helper_writer, ">\r\n            <td colspan=\"");

                    WriteTo(@__razor_helper_writer, columns.Count());

                    WriteLiteralTo(@__razor_helper_writer, "\">");

                    WriteTo(@__razor_helper_writer, Format(footer, null));

                    WriteLiteralTo(@__razor_helper_writer, "</td>\r\n        </tr>\r\n    </tfoot>\r\n");
                }

                WriteLiteralTo(@__razor_helper_writer, "    <tbody>\r\n");

                int rowIndex = 0;

                foreach (var row in webGrid.Rows)
                {
                    string style = GetRowStyle(webGrid, rowIndex++, rowStyle, alternatingRowStyle, selectedRowStyle);

                    WriteLiteralTo(@__razor_helper_writer, "        <tr");

                    WriteTo(@__razor_helper_writer, CssClass(style));

                    WriteLiteralTo(@__razor_helper_writer, ">\r\n");

                    foreach (var column in columns)
                    {
                        var value = (column.Format == null) ? HttpUtility.HtmlEncode(row[column.ColumnName]) : Format(column.Format, row).ToString();

                        WriteLiteralTo(@__razor_helper_writer, "            <td");

                        WriteTo(@__razor_helper_writer, CssClass(column.Style));

                        WriteLiteralTo(@__razor_helper_writer, ">");

                        WriteTo(@__razor_helper_writer, Raw(value));

                        WriteLiteralTo(@__razor_helper_writer, "</td>\r\n");
                    }

                    WriteLiteralTo(@__razor_helper_writer, "        </tr>\r\n");
                }

                if (fillEmptyRows)
                {
                    rowIndex = webGrid.Rows.Count;
                    while (rowIndex < webGrid.RowsPerPage)
                    {
                        string style = GetRowStyle(webGrid, rowIndex++, rowStyle, alternatingRowStyle, null);

                        WriteLiteralTo(@__razor_helper_writer, "            <tr");

                        WriteTo(@__razor_helper_writer, CssClass(style));

                        WriteLiteralTo(@__razor_helper_writer, ">\r\n");

                        foreach (var column in columns)
                        {
                            WriteLiteralTo(@__razor_helper_writer, "                    <td");

                            WriteTo(@__razor_helper_writer, CssClass(column.Style));

                            WriteLiteralTo(@__razor_helper_writer, ">");

                            WriteTo(@__razor_helper_writer, Raw(emptyRowCellValue));

                            WriteLiteralTo(@__razor_helper_writer, "</td>\r\n");
                        }

                        WriteLiteralTo(@__razor_helper_writer, "            </tr>\r\n");
                    }
                }

                WriteLiteralTo(@__razor_helper_writer, "    </tbody>\r\n    </table>\r\n");
            }));
        }
        public static HelperResult Pager(
            WebGrid webGrid,
            HttpContextBase httpContext,
            WebGridPagerModes mode,
            string firstText,
            string previousText,
            string nextText,
            string lastText,
            int numericLinksCount,
            bool renderAjaxContainer)
        {
            return new HelperResult(__razor_helper_writer =>
            {
                int currentPage = webGrid.PageIndex;
                int totalPages = webGrid.PageCount;
                int lastPage = totalPages - 1;

                WriteTo(@__razor_helper_writer, GridInitScript(webGrid, httpContext));

                if (renderAjaxContainer && webGrid.IsAjaxEnabled)
                {
                    WriteLiteralTo(@__razor_helper_writer, "        ");

                    WriteLiteralTo(@__razor_helper_writer, "<span data-swhgajax=\"true\" data-swhgcontainer=\"");

                    WriteTo(@__razor_helper_writer, webGrid.AjaxUpdateContainerId);

                    WriteLiteralTo(@__razor_helper_writer, "\" data-swhgcallback=\"");

                    WriteTo(@__razor_helper_writer, webGrid.AjaxUpdateCallback);

                    WriteLiteralTo(@__razor_helper_writer, "\">\r\n");
                }

                if (ModeEnabled(mode, WebGridPagerModes.FirstLast) && currentPage > 1)
                {
                    if (String.IsNullOrEmpty(firstText))
                    {
                        firstText = "<<";
                    }

                    WriteTo(@__razor_helper_writer, GridLink(webGrid, webGrid.GetPageUrl(0), firstText));

                    WriteTo(@__razor_helper_writer, Raw(" "));
                }

                if (ModeEnabled(mode, WebGridPagerModes.NextPrevious) && currentPage > 0)
                {
                    if (String.IsNullOrEmpty(previousText))
                    {
                        previousText = "<";
                    }

                    WriteTo(@__razor_helper_writer, GridLink(webGrid, webGrid.GetPageUrl(currentPage - 1), previousText));

                    WriteTo(@__razor_helper_writer, Raw(" "));
                }

                if (ModeEnabled(mode, WebGridPagerModes.Numeric) && (totalPages > 1))
                {
                    int last = currentPage + (numericLinksCount / 2);
                    int first = last - numericLinksCount + 1;
                    if (last > lastPage)
                    {
                        first -= last - lastPage;
                        last = lastPage;
                    }
                    if (first < 0)
                    {
                        last = Math.Min(last + (0 - first), lastPage);
                        first = 0;
                    }
                    for (int i = first; i <= last; i++)
                    {
                        var pageText = (i + 1).ToString(CultureInfo.InvariantCulture);
                        if (i == currentPage)
                        {
                            WriteTo(@__razor_helper_writer, pageText);
                        }
                        else
                        {
                            WriteTo(@__razor_helper_writer, GridLink(webGrid, webGrid.GetPageUrl(i), pageText));
                        }

                        WriteTo(@__razor_helper_writer, Raw(" "));
                    }
                }

                if (ModeEnabled(mode, WebGridPagerModes.NextPrevious) && (currentPage < lastPage))
                {
                    if (String.IsNullOrEmpty(nextText))
                    {
                        nextText = ">";
                    }

                    WriteTo(@__razor_helper_writer, GridLink(webGrid, webGrid.GetPageUrl(currentPage + 1), nextText));

                    WriteTo(@__razor_helper_writer, Raw(" "));
                }

                if (ModeEnabled(mode, WebGridPagerModes.FirstLast) && (currentPage < lastPage - 1))
                {
                    if (String.IsNullOrEmpty(lastText))
                    {
                        lastText = ">>";
                    }

                    WriteTo(@__razor_helper_writer, GridLink(webGrid, webGrid.GetPageUrl(lastPage), lastText));
                }

                if (renderAjaxContainer && webGrid.IsAjaxEnabled)
                {
                    WriteLiteralTo(@__razor_helper_writer, "        ");

                    WriteLiteralTo(@__razor_helper_writer, "</span>\r\n");
                }
            });
        }
        //
        // GET: /UserInfo/Search/date
        public FileStreamResult Pdf()
        {
            List<CharmanderLaMeraPija> all = new List<CharmanderLaMeraPija>();
            using (ReportSupEntities1 dc = new ReportSupEntities1())
            {
                all = (from e in dc.sp_dateRange((string)(Session["inicio"]), (string)(Session["fin"]), (string)(Session["selectDept"])) select new CharmanderLaMeraPija { Nombre = e.Name, Horas = e.horaTrabajada, FechaEntrada = e.horaEntrada, FechaSalida = e.horasalida }).ToList();

            }

            WebGrid grid = new WebGrid(source: all, canPage: false, canSort: false);
            string gridHtml  = grid.GetHtml(
                    columns: grid.Columns(
                               grid.Column("Nombre", "Nombre"),
            grid.Column("FechaEntrada", "Fecha de Entrada       "),
            grid.Column("FechaSalida", "Fecha de Salida                        "),
            grid.Column("Horas","Horas Trabajadas")
                        )
                    ).ToString();

            string exportData = String.Format("<html><head>{0}</head><body><div><span>Reporte</span></div>{1}</body></html>", "<style>table{ border-spacing: 10px; border-collapse: separate; }</style>", gridHtml);
            var bytes = System.Text.Encoding.UTF8.GetBytes(exportData);
            using (var input = new MemoryStream(bytes))
            {
                var output = new MemoryStream();
                var document = new iTextSharp.text.Document(PageSize.LETTER, 150, 150, 50, 50);
                var writer = PdfWriter.GetInstance(document, output);
                writer.CloseStream = false;
                document.Open();

                var xmlWorker = iTextSharp.tool.xml.XMLWorkerHelper.GetInstance();
                xmlWorker.ParseXHtml(writer, document, input, System.Text.Encoding.UTF8);
                document.Close();
                output.Position = 0;
              //  string path = this.Server.MapPath(".") + "Libraries\\Documents\\doc.pdf";

                //          return new FileStreamResult(output, "C:\application.pdf");
                return new FileStreamResult(output, "aplication/pdf")
                {
                    FileDownloadName = "Reporte" + Session["selecdate"].ToString() + ".pdf"
                };

            }
        }
Ejemplo n.º 25
0
        public void GetExcel(String plazasId, String patronesId, String clientesId,
            String gruposId, String opcion, String valor, String statusId)
        {
            Usuario user = Session["UsuarioData"] as Usuario;
            var plazasAsignadas = (from x in db.TopicosUsuarios
                                   where x.usuarioId.Equals(user.Id)
                                   && x.tipo.Equals("P")
                                   select x.topicoId);

            var clientesAsignados = (from x in db.TopicosUsuarios
                                     where x.usuarioId.Equals(user.Id)
                                     && x.tipo.Equals("C")
                                     select x.topicoId);

            var patronesAsignados = (from x in db.TopicosUsuarios
                                     where x.usuarioId.Equals(user.Id)
                                     && x.tipo.Equals("B")
                                     select x.topicoId);

            List<Asegurado> allCust = new List<Asegurado>();

            var asegurados = from s in db.Asegurados
                             join cli in db.Clientes on s.ClienteId equals cli.Id
                             where plazasAsignadas.Contains(s.Cliente.Plaza_id) &&
                                   clientesAsignados.Contains(s.Cliente.Id) &&
                                   patronesAsignados.Contains(s.PatroneId)
                             select s;

            if (!String.IsNullOrEmpty(plazasId))
            {
                @ViewBag.pzaId = plazasId;
                int idPlaza = int.Parse(plazasId.Trim());
                asegurados = asegurados.Where(s => s.Cliente.Plaza_id.Equals(idPlaza));
            }
            if (!String.IsNullOrEmpty(patronesId))
            {
                @ViewBag.patId = patronesId;
                int idPatron = int.Parse(patronesId.Trim());
                asegurados = asegurados.Where(s => s.PatroneId.Equals(idPatron));
            }

            if (!String.IsNullOrEmpty(clientesId))
            {
                @ViewBag.cteId = clientesId;
                int idCliente = int.Parse(clientesId.Trim());
                asegurados = asegurados.Where(s => s.Cliente.Id.Equals(idCliente));
            }

            if (!String.IsNullOrEmpty(gruposId))
            {
                @ViewBag.gpoId = gruposId;
                int idGrupo = int.Parse(gruposId.Trim());
                asegurados = asegurados.Where(s => s.Cliente.Grupo_id.Equals(idGrupo));
            }

            if (!String.IsNullOrEmpty(opcion))
            {
                @ViewBag.opBuscador = opcion;
                @ViewBag.valBuscador = valor;
                TempData["buscador"] = "0";

                switch (opcion)
                {
                    case "1":
                        asegurados = asegurados.Where(s => s.Patrone.registro.Contains(valor));
                        break;
                    case "2":
                        asegurados = asegurados.Where(s => s.numeroAfiliacion.Contains(valor));
                        break;
                    case "3":
                        asegurados = asegurados.Where(s => s.CURP.Contains(valor));
                        break;
                    case "4":
                        asegurados = asegurados.Where(s => s.RFC.Contains(valor));
                        break;
                    case "5":
                        asegurados = asegurados.Where(s => s.nombre.Contains(valor));
                        break;
                    case "6":
                        asegurados = asegurados.Where(s => s.fechaAlta.ToString().Contains(valor));
                        break;
                    case "7":
                        asegurados = asegurados.Where(s => s.fechaBaja.ToString().Contains(valor));
                        break;
                    case "8":
                        asegurados = asegurados.Where(s => s.salarioImss.ToString().Contains(valor.Trim()));
                        break;
                    case "9":
                        asegurados = asegurados.Where(s => s.Cliente.claveCliente.Contains(valor));
                        break;
                    case "10":
                        asegurados = asegurados.Where(s => s.Cliente.Grupos.nombre.Contains(valor));
                        break;
                    case "11":
                        asegurados = asegurados.Where(s => s.ocupacion.Contains(valor));
                        break;
                    case "12":
                        asegurados = asegurados.Where(s => s.Cliente.Plaza.cveCorta.Contains(valor));
                        break;
                    case "13":
                        asegurados = asegurados.Where(s => s.extranjero.Contains(valor));
                        break;
                }
            }

            if (statusId != null)
            {
                @ViewBag.statusId = statusId;

                if (statusId.Trim().Equals("A"))
                {
                    ViewBag.statusId = statusId;
                    asegurados = asegurados.Where(s => !s.fechaBaja.HasValue);
                }
                else if (statusId.Trim().Equals("B"))
                {
                    ViewBag.statusId = statusId;
                    asegurados = asegurados.Where(s => s.fechaBaja.HasValue);
                }
            }

            allCust = asegurados.ToList();

            WebGrid grid = new WebGrid(source: allCust, canPage: false, canSort: false);

            List<WebGridColumn> gridColumns = new List<WebGridColumn>();
            gridColumns.Add(grid.Column("Patrone.registro", "Registro "));
            gridColumns.Add(grid.Column("numeroAfiliacion", "Numero Afiliacion",format: (item) => String.Format("{0,11:S}", item.numeroAfiliacion)));
            gridColumns.Add(grid.Column("curp", "CURP"));
            gridColumns.Add(grid.Column("rfc", "RFC"));
            gridColumns.Add(grid.Column("apellidoPaterno", "Nombre"));
            gridColumns.Add(grid.Column("apellidoMaterno", "Nombre"));
            gridColumns.Add(grid.Column("nombres", "Nombre"));
            gridColumns.Add(grid.Column("nombreTemporal", "Nombre"));
            gridColumns.Add(grid.Column("fechaAlta", "Fecha Alta", format: (item) => String.Format("{0:yyyy-MM-dd}", item.fechaAlta)));
            gridColumns.Add(grid.Column("fechaBaja", "Fecha Baja", format: (item) => item.fechaBaja != null ? String.Format("{0:yyyy-MM-dd}", item.fechaBaja) : String.Empty));
            gridColumns.Add(grid.Column("salarioImss", "Salario IMSS"));
            gridColumns.Add(grid.Column("Cliente.claveCliente", "Ubicación"));
            gridColumns.Add(grid.Column("Cliente.Grupos.nombreCorto", "Grupo"));
            gridColumns.Add(grid.Column("ocupacion", "Ocupación"));
            gridColumns.Add(grid.Column("Cliente.Plaza.cveCorta", "Plaza"));
            gridColumns.Add(grid.Column("extranjero", "Extranjero"));
            gridColumns.Add(grid.Column("fechaCreacion", "Fecha Creación", format: (item) => String.Format("{0:yyyy-MM-dd}", item.fechaCreacion)));
            gridColumns.Add(grid.Column("fechaModificacion", "Fecha Modificación", format: (item) => item.fechaModificacion != null ? String.Format("{0:yyyy-MM-dd}", item.fechaModificacion) : String.Empty));
            gridColumns.Add(grid.Column("alta", "Alta"));
            gridColumns.Add(grid.Column("baja", "Baja"));
            gridColumns.Add(grid.Column("modificacion", "Modificación"));
            gridColumns.Add(grid.Column("permanente", "Permanente"));

            string gridData = grid.GetHtml(
                columns: grid.Columns(gridColumns.ToArray())
                    ).ToString();

            Response.ClearContent();
            DateTime date = DateTime.Now;
            String fileName = "Asegurados-" + date.ToString("ddMMyyyyHHmm") + ".xls";
            Response.AddHeader("content-disposition", "attachment; filename=" + fileName);
            Response.ContentType = "application/excel";
            Response.Write(gridData);
            Response.End();
        }
 private static bool ShowSortableColumnHeader(WebGrid grid, WebGridColumn column)
 {
     return grid.CanSort && column.CanSort && !column.ColumnName.IsEmpty();
 }
Ejemplo n.º 27
0
        public void GetExcel(String plazasId)
        {
            Usuario user = Session["UsuarioData"] as Usuario;
            var patronesAsignados = (from x in db.TopicosUsuarios
                                     where x.usuarioId.Equals(user.Id)
                                     && x.tipo.Equals("B")
                                     select x.topicoId);

            var patrones = from s in db.Patrones
                           where patronesAsignados.Contains(s.Id)
                           select s;

            if (!String.IsNullOrEmpty(plazasId))
            {
                int plazaIdTemp = int.Parse(plazasId);
                patrones = patrones.Where(p => p.Plaza.id.Equals(plazaIdTemp));
            }

            List<Patrone> allCust = new List<Patrone>();

            allCust = patrones.ToList();

            WebGrid grid = new WebGrid(source: allCust, canPage: false, canSort: false);

            List<WebGridColumn> gridColumns = new List<WebGridColumn>();
            gridColumns.Add(grid.Column("registro", "Registro Patronal "));
            gridColumns.Add(grid.Column("Plaza.cveCorta", "ID Plaza"));
            gridColumns.Add(grid.Column("rfc", "RFC"));
            gridColumns.Add(grid.Column("nombre", "Nombre"));
            gridColumns.Add(grid.Column("telefono", "Teléfono"));
            gridColumns.Add(grid.Column("domicilio", "Domicilio"));
            gridColumns.Add(grid.Column("zona", "Zona"));
            gridColumns.Add(grid.Column("inicioAfiliacion", "Ini.Afiliación"));
            gridColumns.Add(grid.Column("STyPS", "STyPS"));
            gridColumns.Add(grid.Column("carEnt", "Entidad"));
            gridColumns.Add(grid.Column("carDel", "Delegación"));
            gridColumns.Add(grid.Column("codigoPostal", "C. P."));
            gridColumns.Add(grid.Column("direccionArchivo", "Carpeta"));

            string gridData = grid.GetHtml(
                columns: grid.Columns(gridColumns.ToArray())
                    ).ToString();

            Response.ClearContent();
            DateTime date = DateTime.Now;
            String fileName = "Patrones-" + date.ToString("ddMMyyyyHHmm") + ".xls";
            Response.AddHeader("content-disposition", "attachment; filename=" + fileName);
            Response.ContentType = "application/excel";
            Response.Write(gridData);
            Response.End();
        }
        private static string GetRowStyle(WebGrid webGrid, int rowIndex, string rowStyle, string alternatingRowStyle, string selectedRowStyle)
        {
            StringBuilder style = new StringBuilder();

            if (rowIndex % 2 == 0)
            {
                if (!String.IsNullOrEmpty(rowStyle))
                {
                    style.Append(rowStyle);
                }
            }
            else
            {
                if (!String.IsNullOrEmpty(alternatingRowStyle))
                {
                    style.Append(alternatingRowStyle);
                }
            }

            if (!String.IsNullOrEmpty(selectedRowStyle) && (rowIndex == webGrid.SelectedIndex))
            {
                if (style.Length > 0)
                {
                    style.Append(" ");
                }
                style.Append(selectedRowStyle);
            }
            return style.ToString();
        }
        public static HelperResult Table(WebGrid webGrid,
                                         HttpContextBase httpContext,
                                         string tableStyle,
                                         string headerStyle,
                                         string footerStyle,
                                         string rowStyle,
                                         string alternatingRowStyle,
                                         string selectedRowStyle,
                                         string caption,
                                         bool displayHeader,
                                         bool fillEmptyRows,
                                         string emptyRowCellValue,
                                         IEnumerable<WebGridColumn> columns,
                                         IEnumerable<string> exclusions,
                                         Func<dynamic, object> footer,
                                         object htmlAttributes)
        {
            return new HelperResult(__razor_helper_writer =>
            {
                if (emptyRowCellValue == null)
                {
                    emptyRowCellValue = "&nbsp;";
                }

                WriteTo(@__razor_helper_writer, GridInitScript(webGrid, httpContext));

                var htmlAttributeDictionary = TypeHelper.ObjectToDictionary(htmlAttributes);
                if (webGrid.IsAjaxEnabled)
                {
                    htmlAttributeDictionary["data-swhgajax"] = "true";
                    htmlAttributeDictionary["data-swhgcontainer"] = webGrid.AjaxUpdateContainerId;
                    htmlAttributeDictionary["data-swhgcallback"] = webGrid.AjaxUpdateCallback;
                }

                WriteLiteralTo(@__razor_helper_writer, "    <table");

                WriteTo(@__razor_helper_writer, tableStyle.IsEmpty() ? null : Raw(" class=\"" + HttpUtility.HtmlAttributeEncode(tableStyle) + "\""));

                WriteTo(@__razor_helper_writer, PrintAttributes(htmlAttributeDictionary));

                WriteLiteralTo(@__razor_helper_writer, ">\r\n");

                if (!caption.IsEmpty())
                {
                    WriteLiteralTo(@__razor_helper_writer, "        <caption>");

                    WriteTo(@__razor_helper_writer, caption);

                    WriteLiteralTo(@__razor_helper_writer, "</caption>\r\n");
                }

                if (displayHeader)
                {
                    WriteLiteralTo(@__razor_helper_writer, "    <thead>\r\n        <tr");

                    WriteTo(@__razor_helper_writer, CssClass(headerStyle));

                    WriteLiteralTo(@__razor_helper_writer, ">\r\n");

                    foreach (var column in columns)
                    {
                        WriteLiteralTo(@__razor_helper_writer, "            <th scope=\"col\">\r\n");

                        if (ShowSortableColumnHeader(webGrid, column))
                        {
                            var text = column.Header.IsEmpty() ? column.ColumnName : column.Header;

                            WriteTo(@__razor_helper_writer, GridLink(webGrid, webGrid.GetSortUrl(column.ColumnName), text));
                        }
                        else
                        {
                            WriteTo(@__razor_helper_writer, column.Header ?? column.ColumnName);
                        }

                        WriteLiteralTo(@__razor_helper_writer, "            </th>\r\n");
                    }

                    WriteLiteralTo(@__razor_helper_writer, "        </tr>\r\n    </thead>\r\n");
                }

                if (footer != null)
                {
                    WriteLiteralTo(@__razor_helper_writer, "    <tfoot>\r\n        <tr ");

                    WriteTo(@__razor_helper_writer, CssClass(footerStyle));

                    WriteLiteralTo(@__razor_helper_writer, ">\r\n            <td colspan=\"");

                    WriteTo(@__razor_helper_writer, columns.Count());

                    WriteLiteralTo(@__razor_helper_writer, "\">");

                    WriteTo(@__razor_helper_writer, Format(footer, null));

                    WriteLiteralTo(@__razor_helper_writer, "</td>\r\n        </tr>\r\n    </tfoot>\r\n");
                }

                WriteLiteralTo(@__razor_helper_writer, "    <tbody>\r\n");

                int rowIndex = 0;

                foreach (var row in webGrid.Rows)
                {
                    string style = GetRowStyle(webGrid, rowIndex++, rowStyle, alternatingRowStyle, selectedRowStyle);

                    WriteLiteralTo(@__razor_helper_writer, "        <tr");

                    WriteTo(@__razor_helper_writer, CssClass(style));

                    WriteLiteralTo(@__razor_helper_writer, ">\r\n");

                    foreach (var column in columns)
                    {
                        var value = (column.Format == null) ? HttpUtility.HtmlEncode(row[column.ColumnName]) : Format(column.Format, row).ToString();

                        WriteLiteralTo(@__razor_helper_writer, "            <td");

                        WriteTo(@__razor_helper_writer, CssClass(column.Style));

                        WriteLiteralTo(@__razor_helper_writer, ">");

                        WriteTo(@__razor_helper_writer, Raw(value));

                        WriteLiteralTo(@__razor_helper_writer, "</td>\r\n");
                    }

                    WriteLiteralTo(@__razor_helper_writer, "        </tr>\r\n");
                }

                if (fillEmptyRows)
                {
                    rowIndex = webGrid.Rows.Count;
                    while (rowIndex < webGrid.RowsPerPage)
                    {
                        string style = GetRowStyle(webGrid, rowIndex++, rowStyle, alternatingRowStyle, null);

                        WriteLiteralTo(@__razor_helper_writer, "            <tr");

                        WriteTo(@__razor_helper_writer, CssClass(style));

                        WriteLiteralTo(@__razor_helper_writer, ">\r\n");

                        foreach (var column in columns)
                        {
                            WriteLiteralTo(@__razor_helper_writer, "                    <td");

                            WriteTo(@__razor_helper_writer, CssClass(column.Style));

                            WriteLiteralTo(@__razor_helper_writer, ">");

                            WriteTo(@__razor_helper_writer, Raw(emptyRowCellValue));

                            WriteLiteralTo(@__razor_helper_writer, "</td>\r\n");
                        }

                        WriteLiteralTo(@__razor_helper_writer, "            </tr>\r\n");
                    }
                }

                WriteLiteralTo(@__razor_helper_writer, "    </tbody>\r\n    </table>\r\n");
            });
        }
Ejemplo n.º 30
0
        public static IHtmlString GetHtmlWithSelectAllCheckBox(this WebGrid webGrid, string tableStyle = null,
                                                               string headerStyle              = null, string footerStyle = null, string rowStyle = null,
                                                               string alternatingRowStyle      = null, string selectedRowStyle = null,
                                                               string caption                  = null, bool displayHeader = true, bool fillEmptyRows = false,
                                                               string emptyRowCellValue        = null, IEnumerable <WebGridColumn> columns = null,
                                                               IEnumerable <string> exclusions = null, WebGridPagerModes mode              = WebGridPagerModes.All,
                                                               string firstText                = null, string previousText   = null, string nextText    = null,
                                                               string lastText                 = null, int numericLinksCount = 5, object htmlAttributes = null,
                                                               string checkBoxValue            = "ID")
        {
            var newColumn = webGrid.Column(header: "{}",
                                           format: item => new HelperResult(writer =>
            {
                writer.Write("<input class=\"singleCheckBox\" name=\"selectedRows\" value=\""
                             + item.Value.GetType().GetProperty(checkBoxValue).GetValue(item.Value, null).ToString()
                             + "\" type=\"checkbox\" />"
                             );
            }));
            var newColumns = columns.ToList();

            newColumns.Insert(0, newColumn);
            var script = @"<script>
                if (typeof jQuery == 'undefined')
                {
                    document.write(
                        unescape(
                        ""%3Cscript src='http://ajax.aspnetcdn.com/ajax/jquery/jquery-1.9.0.min.js'%3E%3C/script%3E""
                        )
                     );
                }
                (function(){
                    window.setTimeout(function() { initializeCheckBoxes();  }, 1000);
                    function initializeCheckBoxes(){   
                        $(function () {
                            $('#allCheckBox').live('click',function () {
                                var isChecked = $(this).attr('checked');                       
                                $('.singleCheckBox').attr('checked', isChecked  ? true: false);
                                $('.singleCheckBox').closest('tr').addClass(isChecked  ? 'selected-row': 'not-selected-row');
                                $('.singleCheckBox').closest('tr').removeClass(isChecked  ? 'not-selected-row': 'selected-row');
                            });
                            $('.singleCheckBox').live('click',function () {
                                var isChecked = $(this).attr('checked');
                                $(this).closest('tr').addClass(isChecked  ? 'selected-row': 'not-selected-row');
                                $(this).closest('tr').removeClass(isChecked  ? 'not-selected-row': 'selected-row');
                                if(isChecked && $('.singleCheckBox').length == $('.selected-row').length)
                                     $('#allCheckBox').attr('checked',true);
                                else
                                    $('#allCheckBox').attr('checked',false);
                            });
                        });
                    }
                })();
            </script>";
            var html   = webGrid.GetHtml(tableStyle, headerStyle, footerStyle, rowStyle,
                                         alternatingRowStyle, selectedRowStyle, caption,
                                         displayHeader, fillEmptyRows, emptyRowCellValue,
                                         newColumns, exclusions, mode, firstText,
                                         previousText, nextText, lastText,
                                         numericLinksCount, htmlAttributes
                                         );

            return(MvcHtmlString.Create(html.ToString().Replace("{}",
                                                                "<input type='checkbox' id='allCheckBox'/>") + script));
        }
        public static HelperResult Pager(
            WebGrid webGrid,
            HttpContextBase httpContext,
            WebGridPagerModes mode,
            string firstText,
            string previousText,
            string nextText,
            string lastText,
            int numericLinksCount,
            bool renderAjaxContainer)
        {
            return(new HelperResult(__razor_helper_writer =>
            {
                int currentPage = webGrid.PageIndex;
                int totalPages = webGrid.PageCount;
                int lastPage = totalPages - 1;

                WriteTo(@__razor_helper_writer, GridInitScript(webGrid, httpContext));

                if (renderAjaxContainer && webGrid.IsAjaxEnabled)
                {
                    WriteLiteralTo(@__razor_helper_writer, "        ");

                    WriteLiteralTo(@__razor_helper_writer, "<span data-swhgajax=\"true\" data-swhgcontainer=\"");

                    WriteTo(@__razor_helper_writer, webGrid.AjaxUpdateContainerId);

                    WriteLiteralTo(@__razor_helper_writer, "\" data-swhgcallback=\"");

                    WriteTo(@__razor_helper_writer, webGrid.AjaxUpdateCallback);

                    WriteLiteralTo(@__razor_helper_writer, "\">\r\n");
                }

                if (ModeEnabled(mode, WebGridPagerModes.FirstLast) && currentPage > 1)
                {
                    if (String.IsNullOrEmpty(firstText))
                    {
                        firstText = "<<";
                    }

                    WriteTo(@__razor_helper_writer, GridLink(webGrid, webGrid.GetPageUrl(0), firstText));

                    WriteTo(@__razor_helper_writer, Raw(" "));
                }

                if (ModeEnabled(mode, WebGridPagerModes.NextPrevious) && currentPage > 0)
                {
                    if (String.IsNullOrEmpty(previousText))
                    {
                        previousText = "<";
                    }

                    WriteTo(@__razor_helper_writer, GridLink(webGrid, webGrid.GetPageUrl(currentPage - 1), previousText));

                    WriteTo(@__razor_helper_writer, Raw(" "));
                }

                if (ModeEnabled(mode, WebGridPagerModes.Numeric) && (totalPages > 1))
                {
                    int last = currentPage + (numericLinksCount / 2);
                    int first = last - numericLinksCount + 1;
                    if (last > lastPage)
                    {
                        first -= last - lastPage;
                        last = lastPage;
                    }
                    if (first < 0)
                    {
                        last = Math.Min(last + (0 - first), lastPage);
                        first = 0;
                    }
                    for (int i = first; i <= last; i++)
                    {
                        var pageText = (i + 1).ToString(CultureInfo.InvariantCulture);
                        if (i == currentPage)
                        {
                            WriteTo(@__razor_helper_writer, pageText);
                        }
                        else
                        {
                            WriteTo(@__razor_helper_writer, GridLink(webGrid, webGrid.GetPageUrl(i), pageText));
                        }

                        WriteTo(@__razor_helper_writer, Raw(" "));
                    }
                }

                if (ModeEnabled(mode, WebGridPagerModes.NextPrevious) && (currentPage < lastPage))
                {
                    if (String.IsNullOrEmpty(nextText))
                    {
                        nextText = ">";
                    }

                    WriteTo(@__razor_helper_writer, GridLink(webGrid, webGrid.GetPageUrl(currentPage + 1), nextText));

                    WriteTo(@__razor_helper_writer, Raw(" "));
                }

                if (ModeEnabled(mode, WebGridPagerModes.FirstLast) && (currentPage < lastPage - 1))
                {
                    if (String.IsNullOrEmpty(lastText))
                    {
                        lastText = ">>";
                    }

                    WriteTo(@__razor_helper_writer, GridLink(webGrid, webGrid.GetPageUrl(lastPage), lastText));
                }

                if (renderAjaxContainer && webGrid.IsAjaxEnabled)
                {
                    WriteLiteralTo(@__razor_helper_writer, "        ");

                    WriteLiteralTo(@__razor_helper_writer, "</span>\r\n");
                }
            }));
        }
Ejemplo n.º 32
0
        private static HelperResult PagerList(
            WebGrid webGrid,
            WebGridPagerModes mode,
            string firstText,
            string previousText,
            string nextText,
            string lastText,
            int numericLinksCount,
            bool explicitlyCalled)
        {
            int currentPage = webGrid.PageIndex;
            int totalPages = webGrid.PageCount;
            int lastPage = totalPages - 1;

            var ul = new TagBuilder("ul");
            ul.MergeAttribute("class", "pagination pagination-sm sigen-max-height");
            var li = new List<TagBuilder>();

            if (ModeEnabled(mode, WebGridPagerModes.FirstLast))
            {
                if (String.IsNullOrEmpty(firstText))
                {
                    firstText = "<<";
                }

                var part = new TagBuilder("li")
                {
                    InnerHtml = GridLink(webGrid, webGrid.GetPageUrl(0), firstText)
                };

                if (currentPage == 0)
                {
                    part.MergeAttribute("class", "disabled");
                }

                li.Add(part);

            }

            if (ModeEnabled(mode, WebGridPagerModes.NextPrevious))
            {
                if (String.IsNullOrEmpty(previousText))
                {
                    previousText = "<";
                }

                int page = currentPage == 0 ? 0 : currentPage - 1;

                var part = new TagBuilder("li")
                {
                    InnerHtml = GridLink(webGrid, webGrid.GetPageUrl(page), previousText)
                };

                if (currentPage == 0)
                {
                    part.MergeAttribute("class", "disabled");
                }

                li.Add(part);

            }

            if (ModeEnabled(mode, WebGridPagerModes.Numeric) && (totalPages > 1))
            {
                int last = currentPage + (numericLinksCount / 2);
                int first = last - numericLinksCount + 1;
                if (last > lastPage)
                {
                    first -= last - lastPage;
                    last = lastPage;
                }
                if (first < 0)
                {
                    last = Math.Min(last + (0 - first), lastPage);
                    first = 0;
                }
                for (int i = first; i <= last; i++)
                {

                    var pageText = (i + 1).ToString(CultureInfo.InvariantCulture);
                    var part = new TagBuilder("li")
                    {
                        InnerHtml = GridLink(webGrid, webGrid.GetPageUrl(i), pageText)
                    };

                    if (i == currentPage)
                    {
                        part.MergeAttribute("class", "sigen-active");
                    }

                    li.Add(part);

                }
            }

            if (ModeEnabled(mode, WebGridPagerModes.NextPrevious))
            {
                if (String.IsNullOrEmpty(nextText))
                {
                    nextText = ">";
                }

                int page = currentPage == lastPage ? lastPage : currentPage + 1;

                var part = new TagBuilder("li")
                {
                    InnerHtml = GridLink(webGrid, webGrid.GetPageUrl(page), nextText)
                };

                if (currentPage == lastPage)
                {
                    part.MergeAttribute("class", "disabled");
                }

                li.Add(part);

            }

            if (ModeEnabled(mode, WebGridPagerModes.FirstLast))
            {
                if (String.IsNullOrEmpty(lastText))
                {
                    lastText = ">>";
                }

                var part = new TagBuilder("li")
                {
                    InnerHtml = GridLink(webGrid, webGrid.GetPageUrl(lastPage), lastText)
                };

                if (currentPage == lastPage)
                {
                    part.MergeAttribute("class", "disabled");
                }

                li.Add(part);

            }

            ul.InnerHtml = string.Join("", li);

            var html = "";
            if (explicitlyCalled && webGrid.IsAjaxEnabled)
            {
                var span = new TagBuilder("span");
                span.MergeAttribute("data-swhgajax", "true");
                span.MergeAttribute("data-swhgcontainer", webGrid.AjaxUpdateContainerId);
                span.MergeAttribute("data-swhgcallback", webGrid.AjaxUpdateCallback);

                span.InnerHtml = ul.ToString();
                html = span.ToString();

            }
            else
            {
                html = ul.ToString();
            }

            /** Registro {} de {} **/
            var numeroRegistros = webGrid.RowsPerPage * webGrid.PageIndex + webGrid.Rows.Count;
            var contenido = string.Concat(
                "<div class='sigen-foot-page'>Registros : ",
                numeroRegistros.ToString(CultureInfo.InvariantCulture),
                " de ",
                webGrid.TotalRowCount.ToString(CultureInfo.InvariantCulture),
                "</div>");
            html = string.Concat(contenido, html);

            return new HelperResult(writer =>
            {
                writer.Write(html);
            });
        }
//------------------------------------------------------------------------------