Esempio n. 1
0
        public FileStreamResult ExportarPDF()
        {
            var     autores  = db.Autores.Include(a => a.Pais);
            WebGrid grid     = new WebGrid(source: autores, canPage: false, canSort: false);
            string  gridHtml = grid.GetHtml(
                columns: grid.Columns
                (
                    grid.Column("ID", header: "Codigo"),
                    grid.Column("Apellido", header: "Apellido"),
                    grid.Column("Nombre", header: "Nombre"),
                    grid.Column("Nacionalidad", header: "CodPais"),
                    grid.Column("Pais.Descripcion", header: "Pais"),
                    grid.Column("FechaNacimiento", header: "Fecha Nacimiento", format: (item) => string.Format("{0:dd/MM/yyyy}", item.FechaNacimiento))
                )
                ).ToString();
            string exportData = String.Format("<html><head>{0}</head><body>{1}</body></html>", "<p>Lista de Autores</p> <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.A4, 50, 50, 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;
                return(new FileStreamResult(output, "application/pdf"));
            }
        }
Esempio n. 2
0
        public static string ToHtmlString(this PagingMgr pagingMgr, Controller mvcController)
        {
            // Get the pagingState and pagingDirection
            var    route           = mvcController.RouteData;
            var    controllerName  = route.GetRequiredString("controller");
            var    actionName      = route.GetRequiredString("action");
            string pagingState     = mvcController.Request.Params["pagingState"];
            string pagingDirection = mvcController.Request.Params["pagingDirection"] ?? "first";

            // Set the pagingState before getting the intended page
            pagingMgr.RestorePagingState(pagingState);

            // Set the paging option and get the next page
            PagingMgr.PagingDbCmdEnum pagingOption = pagingDirection == "first" ? PagingMgr.PagingDbCmdEnum.First
                : pagingDirection == "next" ? PagingMgr.PagingDbCmdEnum.Next
                : pagingDirection == "prev" ? PagingMgr.PagingDbCmdEnum.Previous
                : PagingMgr.PagingDbCmdEnum.Last;
            DataTable             pageTable = pagingMgr.GetPage(pagingOption);
            IEnumerable <dynamic> pageData  = DataTableToEnumerable(pageTable);

            // Realize the loop
            WebGrid webGrid = new WebGrid(pageData, rowsPerPage: pagingMgr.PageSize);

            // Get the new paging state for next and previous link
            string newPagingState = pagingMgr.GetPagingState();
            string html           =
                string.Format("<a href=\"/OurAdminWeb/Grid/TestSequences?pagingState={0}&pagingDirection={1}\">Previous</a>", newPagingState, "prev")
                + " | "
                + string.Format("<a href=\"/OurAdminWeb/Grid/TestSequences?pagingState={0}&pagingDirection={1}\">Next</a><br />", newPagingState, "next");

            return(html + webGrid.Table().ToHtmlString());
        }
Esempio n. 3
0
        /// <summary>
        /// Create an mvc WebGrid using defaults or supplied params
        /// If autoSortAndPage is false, totalRowCount must be provided for server-side paging to work
        /// </summary>
        /// <param name="htmlHelper"></param>
        /// <param name="sourceData"></param>
        /// <param name="pagerMode"></param>
        /// <param name="ajaxUpdateCallback">jQueryTableStyling required to update theme to match jQuery Theme. If you must call other method, include this call in the other method.
        /// </param>
        /// <param name="rowsPerPage"></param>
        /// <param name="pagerLinksCount"></param>
        /// <param name="defaultSort"></param>
        /// <param name="canPage"></param>
        /// <param name="canSort"></param>
        /// <returns></returns>
        public static WebGrid WebGridCustom(this HtmlHelper htmlHelper,
                                            IEnumerable <object> sourceData,
                                            string ajaxUpdateCallback    = "jQueryTableStyling",
                                            string ajaxUpdateContainerId = "grid",
                                            int rowsPerPage      = PAGE_SIZE,
                                            string defaultSort   = null,
                                            bool canPage         = true,
                                            bool canSort         = true,
                                            bool autoSortAndPage = true,
                                            int totalRowCount    = 0)
        {
            WebGrid grid = null;

            if (autoSortAndPage)
            {       //automatic paging and sorting handled by the grid
                grid = new WebGrid(sourceData, canPage: canPage, canSort: canSort,
                                   rowsPerPage: rowsPerPage,
                                   ajaxUpdateContainerId: ajaxUpdateContainerId,
                                   ajaxUpdateCallback: ajaxUpdateCallback,              //jQuery theme applied
                                   defaultSort: defaultSort);
            }
            else
            {       //paging and sorting handled by the repository
                grid = new WebGrid(null,
                                   canPage: canPage, canSort: canSort,
                                   rowsPerPage: rowsPerPage,
                                   ajaxUpdateContainerId: ajaxUpdateContainerId,
                                   ajaxUpdateCallback: ajaxUpdateCallback,              //jQuery theme applied
                                   defaultSort: defaultSort);
                grid.Bind(source: sourceData, rowCount: totalRowCount, autoSortAndPage: false);
            }
            return(grid);
        }
Esempio n. 4
0
        public static string PagingMgrGrid(this HtmlHelper htmlHelper, PagingMgr pagingMgr)
        {
            // Get the pagingState and pagingDirection
            var    route           = htmlHelper.ViewContext.RouteData;
            var    controllerName  = route.GetRequiredString("controller");
            var    actionName      = route.GetRequiredString("action");
            string pagingState     = htmlHelper.ViewContext.HttpContext.Request.Params["pagingState"];
            string pagingDirection = htmlHelper.ViewContext.HttpContext.Request.Params["pagingDirection"];

            PagingMgr.PagingDbCmdEnum pagingOption = string.IsNullOrWhiteSpace(pagingDirection) ?
                                                     PagingMgr.PagingDbCmdEnum.First :
                                                     (PagingMgr.PagingDbCmdEnum)Enum.Parse(typeof(PagingMgr.PagingDbCmdEnum), pagingDirection);

            if (!string.IsNullOrWhiteSpace(pagingState))
            {
                // Set the pagingState before getting the intended page
                pagingMgr.RestorePagingState(pagingState);

//                string initHtml = @"
//
//function showPage(action, data) {{
//    $.ajax({{
//        url: action,
//        type: ""get"",
//        format: ""html"",
//        cache: false,
//        data: data,
//        success: function (result) {{
//            // alert(result);
//            $(""#gridContainer"").html(result);
//        }},
//        error: function (xhr, status, error) {{
//
//            //?? CALL the client side error handling function which may be provided by the client
//
//            alert(xhr.responseText);
//            //?? showModalDialog(xhr.statusText, xhr.responseText);
//        }}
//    }});
//}}
//
//";
            }

            // Set the paging option and get the next page
            DataTable             pageTable = pagingMgr.GetPage(pagingOption);
            IEnumerable <dynamic> pageData  = DataTableToEnumerable(pageTable);

            // Realize the loop
            WebGrid webGrid = new WebGrid(pageData, rowsPerPage: pagingMgr.PageSize);

            // Get the new paging state for next and previous link
            string newPagingState = pagingMgr.GetPagingState();
            string html           =
                string.Format("<a href=\"/OurAdminWeb/Grid/TestSequences?pagingState={0}&pagingDirection={1}\">Previous</a>", newPagingState, "prev")
                + " | "
                + string.Format("<a href=\"/OurAdminWeb/Grid/TestSequences?pagingState={0}&pagingDirection={1}\">Next</a><br />", newPagingState, "next");

            return(html + webGrid.Table().ToHtmlString());
        }
        public void GetExcel()
        {
            List <Agentii_Table> allCust = new List <Agentii_Table>();

            using (Agentii2Entities25 dc = new Agentii2Entities25())
            {
                allCust = dc.Agentii_Table.ToList();
            }

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

            string gridData = grid.GetHtml(
                columns: grid.Columns(
                    grid.Column("Agentie", "Agentie"),
                    grid.Column("Intrare", "Intrare"),
                    grid.Column("Iesire", "Iesire"),
                    grid.Column("Explicatii", "Expicatii"),
                    grid.Column("Operator", "Operator"),
                    grid.Column("DataOra", "Data_Ora"),
                    grid.Column("Sold", "Sold"),
                    grid.Column("UltimaOp", "UltimaOp"),
                    grid.Column("Zile", "Zile")
                    )
                ).ToString();


            Response.ClearContent();
            Response.AddHeader("content-disposition", "attachment; filename=Agentii.xls");
            Response.ContentType = "application/vnd.ms-excel"; //excel

            Response.Write(gridData);
            Response.End();
        }
Esempio n. 6
0
        // GET: Inseminador
        public void GetExcel()
        {
            List <inseminador> inseminador = new List <inseminador>();

            using (bdagricolaEntities dc = new bdagricolaEntities())
            {
                inseminador = dc.inseminador.ToList();
            }

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

            string gridData = grid.GetHtml(
                columns: grid.Columns(
                    grid.Column("id", "ID"),
                    grid.Column("nombre", "Nombre"),
                    grid.Column("apellido", "Apellido"),
                    grid.Column("numero", "Telefono")

                    )
                ).ToString();

            Response.ClearContent();
            Response.AddHeader("content-disposition", "attachment; filename=Inseminadores.xls");
            Response.ContentType = "application/excel";
            Response.Write(gridData);
            Response.End();
        }
Esempio n. 7
0
        public void GetExcel()
        {
            List <Membrii> allCust = new List <Membrii>();

            using (ArtClubContext dc = new ArtClubContext())
            {
                allCust = dc.Membriis.ToList();
            }

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

            string gridData = grid.GetHtml(
                columns: grid.Columns(
                    grid.Column("ID_Username", "Username"),
                    grid.Column("Nume", "Nume"),
                    grid.Column("Prenume", "Prenume"),
                    grid.Column("Email", "Email"),
                    grid.Column("Parola", "Parola"),
                    grid.Column("ID_NumeFunctie", "NumeFunctie")
                    )
                ).ToString();


            Response.ClearContent();
            Response.AddHeader("content-disposition", "attachment; filename=Membrii.xls");
            Response.ContentType = "application/vnd.ms-excel"; //excel

            Response.Write(gridData);
            Response.End();
        }
Esempio n. 8
0
        public override void Export()
        {
            WebGrid grid     = new WebGrid(source: _list, canPage: false, canSort: false);
            string  gridHtml = grid.GetHtml(
                columns: grid.Columns(
                    grid.Column("Action", "Czynność"),
                    grid.Column("Topic", "Temat"),
                    grid.Column("Start", "Data rozpoczęcia"),
                    grid.Column("End", "Data zakończenia"),
                    grid.Column("ActualStatus", "Status"),
                    grid.Column("ActualPriority", "Priorytet"),
                    grid.Column("Progress", "%")
                    )
                ).ToString();
            string exportData = String.Format("{0}{1}", "", gridHtml);
            var    bytes      = System.Text.Encoding.UTF8.GetBytes(exportData);

            using (var input = new MemoryStream(bytes)) {
                var      output   = new MemoryStream();
                Document document = new Document(PageSize.A4, 50, 50, 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;
                _memory         = output;
            }
        }
        //public ActionResult BuscarFecha(DateTime Fecha_Ordena)
        //{
        //    var fecha = from s in db.ordena select s;
        //    if (!DateTime(Fecha_Ordena))
        //}
        public void GetExcel()
        {
            List <ordena> ordena = new List <ordena>();

            using (bdagricolaEntities dc = new bdagricolaEntities())
            {
                ordena = dc.ordena.ToList();
            }

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

            string gridData = grid.GetHtml(
                columns: grid.Columns(
                    grid.Column("id", "ID"),
                    grid.Column("fecha", "Fecha"),
                    grid.Column("litros", "Litros"),
                    grid.Column("lecheria_id", "Lecheria"),
                    grid.Column("jornada", "Jornada")
                    )
                ).ToString();

            Response.ClearContent();
            Response.AddHeader("content-disposition", "attachment; filename=Ordeñas.xls");
            Response.ContentType = "application/excel";
            Response.Write(gridData);
            Response.End();
        }
        public FileResult ExportData()
        {
            int userid = 0;

            userid = Convert.ToInt32(Session["UserID"]);

            List <TaskViewModel> allTasks = new List <TaskViewModel>();

            allTasks = GetTask(userid);

            var    grid       = new WebGrid(source: allTasks, canPage: false, canSort: false);
            string exportData = grid.GetHtml(
                columns: grid.Columns(
                    grid.Column("ContactID", "Contact ID"),
                    grid.Column("FirstName", "First Name"),
                    grid.Column("LastName", "Last Name"),
                    grid.Column("ContactNo1", "Contact No1"),
                    grid.Column("ContactNo2", "Contact No2"),
                    grid.Column("EmailID", "Email ID")
                    )
                ).ToHtmlString();

            return(File(new System.Text.UTF8Encoding().GetBytes(exportData),
                        "application/vnd.ms-excel",
                        "Tasks.xls"));
        }
Esempio n. 11
0
        public void GetExcel()
        {
            List <secamiento> secamiento = new List <secamiento>();
            List <animal>     animal     = new List <animal>();

            using (bdagricolaEntities dc = new bdagricolaEntities())
            {
                secamiento = dc.secamiento.ToList();
                animal     = dc.animal.ToList();
            }

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

            string gridData = grid.GetHtml(
                columns: grid.Columns(
                    grid.Column("id", "ID"),
                    grid.Column("fecha", "Fecha"),
                    grid.Column("cantidad_ubres", "Tetas Secadas"),
                    grid.Column("animal.codigo_sag", "Animal")
                    )
                ).ToString();

            Response.ClearContent();
            Response.AddHeader("content-disposition", "attachment; filename=Secamientos.xls");
            Response.ContentType = "application/excel";
            Response.Write(gridData);
            Response.End();
        }
Esempio n. 12
0
        public FileStreamResult GetFile()
        {
            List <Customer> list = new List <Customer>();
            // collect data from database and store webgrid
            WebGrid grid = new WebGrid(source: db.Customers.ToList(), canPage: false, canSort: false);
            //serialige data to view formate.
            string gridhtml = grid.GetHtml(
                columns: grid.Columns(
                    grid.Column("Id", "Id"),
                    grid.Column("Name", "Name"),
                    grid.Column("Address", "Address"),
                    grid.Column("City", "City")
                    )
                ).ToString();
            //add some style for pdf view
            string       exportdata = string.Format("<html><head>{0}</head><body>{1}</body></html>", "<style>table{border-spacing:10px;border-collapse:separate;}</style>", gridhtml);
            var          bytes      = System.Text.Encoding.UTF8.GetBytes(exportdata);
            MemoryStream input      = new MemoryStream(bytes);
            var          output     = new MemoryStream();
            //declare page sige and page margin
            var document = new iTextSharp.text.Document(PageSize.A4, 50, 50, 50, 50);
            var writer   = PdfWriter.GetInstance(document, output);

            writer.CloseStream = false;
            document.Open();
            var xml = iTextSharp.tool.xml.XMLWorkerHelper.GetInstance();

            xml.ParseXHtml(writer, document, input, System.Text.Encoding.UTF8);
            document.Close();
            output.Position = 0;
            return(new FileStreamResult(output, "application/pdf"));
        }
Esempio n. 13
0
        public void GetExcel()
        {
            List <medicamento> medicamento = new List <medicamento>();

            using (bdagricolaEntities dc = new bdagricolaEntities())
            {
                medicamento = dc.medicamento.ToList();
            }

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

            string gridData = grid.GetHtml(
                columns: grid.Columns(
                    grid.Column("id", "ID"),
                    grid.Column("nombre", "Nombre"),
                    grid.Column("descripcion", "Descripcion")

                    )
                ).ToString();

            Response.ClearContent();
            Response.AddHeader("content-disposition", "attachment; filename=Medicamentos.xls");
            Response.ContentType = "application/excel";
            Response.Write(gridData);
            Response.End();
        }
Esempio n. 14
0
        public ActionResult Customers()
        {
            SqlConnection con = new SqlConnection("Server=PRINCE\\MYSQL8;Database=SellDeer;Trusted_Connection = yes; ");

            if (con.State == ConnectionState.Closed)
            {
                con.Open();
            }
            SqlCommand     cmd = new SqlCommand("select * from Customer", con);
            SqlDataAdapter ad  = new SqlDataAdapter(cmd);

            DataTable dt = new DataTable();

            con.Close();
            ad.Fill(dt);
            var fg = dt.AsEnumerable();
            var ht = dt.Rows;
            var k  = ht[0].ItemArray;
            List <SellDeer.Models.modelcust> h = new List <Models.modelcust>();

            h.Add(new Models.modelcust
            {
                id            = 1,
                address       = "aaa",
                customer_name = "ddd",
                phone         = "123"
            }
                  );
            WebGrid d = new WebGrid(dt.AsEnumerable());
            var     x = d.Rows[1].Value;

            ViewBag.viewCustData = h;

            return(View());
        }
Esempio n. 15
0
        public void GetExcel()
        {
            List <alerta_mantencion> alerta_mantencion = new List <alerta_mantencion>();

            using (bdagricolaEntities dc = new bdagricolaEntities())
            {
                alerta_mantencion = dc.alerta_mantencion.ToList();
            }

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

            string gridData = grid.GetHtml(
                columns: grid.Columns(
                    grid.Column("id", "ID"),
                    grid.Column("fecha", "Fecha"),
                    grid.Column("lecheria_id", "Lecheria")
                    )
                ).ToString();

            Response.ClearContent();
            Response.AddHeader("content-disposition", "attachment; filename=MantencionesLecheria.xls");
            Response.ContentType = "application/excel";
            Response.Write(gridData);
            Response.End();
        }
Esempio n. 16
0
    private static String GridLink(WebGrid webGrid, string url, string text, bool IsPartialAjax)
    {
        var builder = new TagBuilder("a");

        builder.SetInnerText(text);
        if (!IsPartialAjax)
        {
            builder.MergeAttribute("class", "pagerCls");
            builder.MergeAttribute("href", url);
            if (webGrid.IsAjaxEnabled)
            {
                builder.MergeAttribute("data-swhglnk", "true");
            }
        }
        else
        {
            builder.MergeAttribute("href", "#");
            builder.MergeAttribute("data-id", text);
            if (webGrid.IsAjaxEnabled)
            {
                builder.MergeAttribute("data-swhglnk", "true");
            }
        }
        return(builder.ToString(TagRenderMode.Normal));
    }
        /// <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
                       ));
        }
Esempio n. 18
0
        public void GetExcel()
        {
            List <venta>     venta     = new List <venta>();
            List <animal>    animal    = new List <animal>();
            List <comprador> comprador = new List <comprador>();

            using (bdagricolaEntities dc = new bdagricolaEntities())
            {
                venta     = dc.venta.ToList();
                animal    = dc.animal.ToList();
                comprador = dc.comprador.ToList();
            }

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

            string gridData = grid.GetHtml(
                columns: grid.Columns(
                    grid.Column("id", "ID"),
                    grid.Column("fecha", "Fecha"),
                    grid.Column("pesaje", "Pesaje"),
                    grid.Column("precio", "Precio"),
                    grid.Column("animal.codigo_sag", "Animal"),
                    grid.Column("comprador.nombre", "Comprador")
                    )
                ).ToString();

            Response.ClearContent();
            Response.AddHeader("content-disposition", "attachment; filename=Ventas.xls");
            Response.ContentType = "application/excel";
            Response.Write(gridData);
            Response.End();
        }
Esempio n. 19
0
        public FileStreamResult CreatePdf() //Export to PDF
        {
            List <UploadProduct> all = new List <UploadProduct>();

            all = db.uploadproduct.ToList();
            WebGrid grid     = new WebGrid(source: all, canPage: false, canSort: false);
            string  gridHtml = grid.GetHtml(
                columns: grid.Columns(
                    grid.Column("ProductID", "ProductID"),
                    grid.Column("ProductName", "ProductName"),
                    grid.Column("ProductPrice", "ProductPrice"),
                    grid.Column("SellingCategory", "SellingCategory")
                    )
                ).ToString();
            string exportData = String.Format("{0}{1}", "", 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.A4, 50, 50, 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;
                return(new FileStreamResult(output, "application/pdf"));
            }
        }
Esempio n. 20
0
        public void PrintWord() // Export to MS-Word
        {
            List <UploadProduct> exceldata = new List <UploadProduct>();

            {
                exceldata = db.uploadproduct.ToList();
            }
            //create object to webgrid
            WebGrid grid     = new WebGrid(source: exceldata, canPage: false, canSort: false);
            string  gridData = grid.GetHtml(
                columns: grid.Columns(
                    grid.Column("ProductID", "ProductID"),
                    grid.Column("ProductName", "ProductName"),
                    grid.Column("ProductPrice", "ProductPrice"),
                    grid.Column("SellingCategory", "SellingCategory")
                    )).ToString();

            Response.ClearContent();
            //give name to excel sheet.
            Response.AddHeader("content-disposition", "attachment; filename=UserData.doc");
            //specify content type
            Response.ContentType = "application/ms-word";
            //write excel data using this method
            Response.Write(gridData);
            Response.End();
        }
Esempio n. 21
0
        public FileStreamResult BaoCaoSanPham()
        {
            var     sp       = db.SanPhams.Where(s => s.BiXoa == 0).ToList <SanPham>();
            WebGrid gird     = new WebGrid(source: sp, canPage: false, canSort: false);
            string  girdHtml = gird.GetHtml(
                columns: gird.Columns(
                    gird.Column("MaSanPham", "STT"),
                    gird.Column("TenSanPham", "Tên"),
                    gird.Column("SoLuongTon", "SL")
                    )
                ).ToString();
            string exportData = string.Format("<html><head><meta charset=" + "utf - 8" + "/>{0}</head><body>{1}</body></html>", "<style>table{border-spacing:10px; border-collapse:separate;}</style>", girdHtml);
            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.A4, 50, 50, 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;
                return(new FileStreamResult(output, "application/pdf"));
            }
        }
Esempio n. 22
0
        public static IHtmlString GetTableWithPager(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,
                                                    Func <dynamic, object> footer       = null,
                                                    WebGridPagerModes mode              = WebGridPagerModes.NextPrevious | WebGridPagerModes.Numeric,
                                                    string firstText      = null,
                                                    string previousText   = null,
                                                    string nextText       = null,
                                                    string lastText       = null,
                                                    int numericLinksCount = 5,
                                                    object parameters     = null,
                                                    string actionName     = null,
                                                    int?currerntPageIndex = null)
        {
            //get table with pager inside the footer
            IHtmlString strTable = GetTable(webGrid, tableStyle, headerStyle, footerStyle, rowStyle, alternatingRowStyle,
                                            selectedRowStyle, caption, displayHeader, fillEmptyRows, emptyRowCellValue, columns, exclusions
                                            , x => PagerList(webGrid, mode, firstText, previousText, nextText, lastText, numericLinksCount, parameters, actionName, currerntPageIndex ?? webGrid.PageIndex),
                                            parameters, actionName);

            //string
            return(strTable);
        }
Esempio n. 23
0
        public void GetExcel()
        {
            List <inseminacion>      inseminacion      = new List <inseminacion>();
            List <inseminador>       inseminador       = new List <inseminador>();
            List <animal>            animal            = new List <animal>();
            List <procedencia_semen> procedencia_semen = new List <procedencia_semen>();

            using (bdagricolaEntities dc = new bdagricolaEntities())
            {
                inseminacion      = dc.inseminacion.ToList();
                animal            = dc.animal.ToList();
                inseminador       = dc.inseminador.ToList();
                procedencia_semen = dc.procedencia_semen.ToList();
            }

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

            string gridData = grid.GetHtml(
                columns: grid.Columns(
                    grid.Column("id", "ID"),
                    grid.Column("fecha", "Fecha"),
                    grid.Column("inseminador.nombre", "Inseminador"),
                    grid.Column("animal.codigo_sag", "Animal"),
                    grid.Column("procedencia_semen.nombre", "Procedencia S***n")
                    )
                ).ToString();

            Response.ClearContent();
            Response.AddHeader("content-disposition", "attachment; filename=Inseminaciones.xls");
            Response.ContentType = "application/excel";
            Response.Write(gridData);
            Response.End();
        }
Esempio n. 24
0
        public void GetExcel()
        {
            List <tratamiento>      tratamiento      = new List <tratamiento>();
            List <tratador>         tratador         = new List <tratador>();
            List <tipo_tratamiento> tipo_tratamiento = new List <tipo_tratamiento>();

            using (bdagricolaEntities dc = new bdagricolaEntities())
            {
                tratamiento      = dc.tratamiento.ToList();
                tratador         = dc.tratador.ToList();
                tipo_tratamiento = dc.tipo_tratamiento.ToList();
            }

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

            string gridData = grid.GetHtml(
                columns: grid.Columns(
                    grid.Column("id", "ID"),
                    grid.Column("fecha", "Fecha"),
                    grid.Column("tratador.nombre", "tratador"),
                    grid.Column("tipo_tratamiento.nombre", "Tipo Tratamiento")
                    )
                ).ToString();

            Response.ClearContent();
            Response.AddHeader("content-disposition", "attachment; filename=Tratamientos.xls");
            Response.ContentType = "application/excel";
            Response.Write(gridData);
            Response.End();
        }
Esempio n. 25
0
        public FileStreamResult CreatePdf()
        { //HINT: https://stackoverflow.com/questions/47651119/asp-net-mvc-exporting-webgrid-to-pdf
            List <Articulo> all = new List <Articulo>();

            all = db.Articulos.ToList();
            WebGrid grid     = new WebGrid(source: all, canPage: false, canSort: false);
            string  gridHtml = grid.GetHtml(
                columns: grid.Columns(
                    grid.Column("Id", "Id"),
                    grid.Column("NombreArticulo", "NombreArticulo"),
                    grid.Column("DescArticulo", "DescArticulo"),
                    grid.Column("PrecioArt", "PrecioArt"),
                    grid.Column("UnidadesExistencia", "UnidadesExistencia")
                    )
                ).ToString();
            string exportData = String.Format("{0}{1}", "", 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.A4, 50, 50, 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;
                return(new FileStreamResult(output, "application/pdf"));
            }
        }
Esempio n. 26
0
        public void GetExcel()
        {
            List <animal> animal = new List <animal>();
            List <muerte> muerte = new List <muerte>();

            using (bdagricolaEntities dc = new bdagricolaEntities())
            {
                muerte = dc.muerte.ToList();
                animal = dc.animal.ToList();
            }

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

            string gridData = grid.GetHtml(
                columns: grid.Columns(
                    grid.Column("id", "ID"),
                    grid.Column("fecha", "Fecha"),
                    grid.Column("causa", "Causa"),
                    grid.Column("animal.codigo_sag", "Animal")

                    )
                ).ToString();

            Response.ClearContent();
            Response.AddHeader("content-disposition", "attachment; filename=Muertes.xls");
            Response.ContentType = "application/excel";
            Response.Write(gridData);
            Response.End();
        }
Esempio n. 27
0
        public ProductModel()
        {
            PageSize   = 20;
            TotalCount = 4;
            Products   = new List <Product>();
            Columns    = new List <string>()
            {
                "Id", "Email", "CSV"
            };

            GridColumns = new WebGridColumn[Columns.Count];

            Grid = new WebGrid(null, rowsPerPage: PageSize);

            for (int i = 0; i < Columns.Count; i++)
            {
                var col = Grid.Column(Columns[i], Columns[i]);
                GridColumns[Columns.Count - 1 - i] = col;
            }

            Grid.Bind(Products, autoSortAndPage: true, rowCount: PageSize);
            Grid.GetHtml(tableStyle: "table table-bordered",
                         mode: WebGridPagerModes.All,
                         firstText: "<< First",
                         previousText: "< Prev",
                         nextText: "Next >",
                         lastText: "Last >>",
                         columns: GridColumns);
        }
Esempio n. 28
0
        public static IHtmlString ToHtmlString <T>(this PagingMgr pagingMgr, PagingMgr.PagingDbCmdEnum pagingDirection)
            where T : new()
        {
            IEnumerable <dynamic> pageData = (IEnumerable <dynamic>)pagingMgr.GetPage <T>(pagingDirection);
            WebGrid webGrid = new WebGrid(pageData);

            return(webGrid.Table());
        }
        public JsonResult GetNonradomizedStudies(string siteId)
        {
            var list       = DbUtils.GetStudyIDsNotRandomized(int.Parse(siteId));
            var grid       = new WebGrid(list, defaultSort: "StudyID", rowsPerPage: 50);
            var htmlString = grid.GetHtml();

            return(Json(new { Data = htmlString.ToHtmlString() }, JsonRequestBehavior.AllowGet));
        }
Esempio n. 30
0
        public static IHtmlString GetTable(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, Func <dynamic, object> footer = null, dynamic parameters = null, string actionName = null)
        {
            IHtmlString htmlStr = webGrid.Table(tableStyle, headerStyle, footerStyle, rowStyle, alternatingRowStyle,
                                                selectedRowStyle, caption, displayHeader, fillEmptyRows, emptyRowCellValue, columns, exclusions, footer);
            int pageNumber = webGrid.PageIndex + 1;

            string controllerName = HttpContext.Current.Request.RequestContext.RouteData.Values["controller"].ToString();

            if (string.IsNullOrEmpty(actionName))
            {
                actionName = "List";
            }

            var    html      = htmlStr.ToHtmlString();
            string strScript = "";
            string strTable  = html;

            //extract script tag from the document
            int scriptStartIndex = html.IndexOf("<script");

            if (scriptStartIndex > -1)
            {
                int scriptEndIndex = html.IndexOf("</script>") + 9;
                strScript = html.Substring(scriptStartIndex, scriptEndIndex - scriptStartIndex);
                strTable  = html.Substring(scriptEndIndex);
            }

            XDocument xdoc   = XDocument.Load(new StringReader(strTable));
            var       result = (from x in xdoc.Descendants(XName.Get("a"))
                                where x.Parent.Name == "th"
                                select x)
                               .ToArray();

            foreach (var item in result)
            {
                string href = item.Attribute(XName.Get("href")).Value;
                RouteValueDictionary parms = ParseParameters(href);
                parms.Add(webGrid.PageFieldName, pageNumber);
                parms = PopulateParameters(parms, parameters);

                //var actionNameDictionary = parms.SingleOrDefault(x => x.Key.ToLower().Equals("actionname"));
                //if (!actionNameDictionary.Equals(default(KeyValuePair<string, object>)))
                //{
                //    actionName = actionNameDictionary.Value.ToString();
                //    parms.Remove(actionNameDictionary.Key);
                //}

                UrlHelper urlHelper = new UrlHelper(HttpContext.Current.Request.RequestContext);
                var       url       = urlHelper.Action(actionName, controllerName, parms);

                item.Attribute(XName.Get("href")).Value = url;
            }

            string finalResult = xdoc.ToString();

            return(new MvcHtmlString(strScript + finalResult));
        }
        public void PreSortedDataSourceReturnsAllRows() {
            // Arrange
            var grid = new WebGrid(GetContext());
            var dataSource = new PreComputedGridDataSource(grid: grid, values: Enumerable.Range(0, 10).Cast<dynamic>(), totalRows: 10);

            // Act 
            var rows = dataSource.GetRows(new SortInfo { SortColumn = String.Empty }, 0);

            // Assert
            Assert.AreEqual(rows.Count, 10);
            Assert.AreEqual(rows.First().Value, 0);
            Assert.AreEqual(rows.Last().Value, 9);
        }
Esempio n. 32
0
 static void grid_RowPrimaryKeyCheck(object sender, WebGrid.Events.GridRowBoundEventArgs e)
 {
     Assert.IsNotEmpty(e.Row.PrimaryKeyValues);
     Assert.AreEqual(e.Row.PrimaryKeyValues.Split(',').Length, 2);
 }
Esempio n. 33
0
        static void grid_GridRowBound(object sender, WebGrid.Events.GridRowBoundEventArgs e)
        {
            object myvalue = e.Row["intTest"].Value;
            //int type was was retrieved from data source
            if (myvalue == null)
                return;
            Assert.AreSame(myvalue.GetType(), typeof(int));

            //Number is 'long' type
            int? inttest = e.Row["intTest"].Value as int?;
            // Since we casted the value it should now be 'long' type
              //  myvalue = e.Row["intTest"].Value;
             //   Assert.AreSame(myvalue.GetType(), typeof(long));
            Assert.IsNotNull(inttest);
            Assert.Greater(inttest, 1);

            myvalue = e.Row["decTest"].Value;
            //Decimal type was was retrieved from data source
            Assert.AreSame(myvalue.GetType(), typeof(System.Decimal));

            decimal? dectest = e.Row["decTest"].Value as decimal?;
            Assert.IsNotNull(dectest);
            Assert.Greater(dectest, 1);

            string txttest = e.Row["vchtest"].Value as string;
            Assert.IsNotNull(txttest);

            myvalue = e.Row["dtmDate"].Value;
            //DateTime type was was retrieved from data source
            Assert.AreSame(myvalue.GetType(), typeof(System.DateTime));
            DateTime? dtmtest = e.Row["dtmDate"].Value as DateTime?;
            Assert.IsNotNull(dtmtest);
            Assert.GreaterOrEqual(dtmtest, new DateTime(2009, 1, 1));
        }
Esempio n. 34
0
 static void grid_BeforeUpdateInsert(object sender, WebGrid.Events.BeforeUpdateInsertEventArgs e)
 {
     //   e.Row["PagerPrefix"].Value = "Olav was here..";
 }
Esempio n. 35
0
 void grid_AfterUpdateInsert(object sender, WebGrid.Events.AfterUpdateInsertEventArgs e)
 {
     Assert.IsNotNull(e.DataRow);
     Assert.AreEqual(e.DataRow["Value"], "mytest");
 }
Esempio n. 36
0
        void grid_BeforeGetData(object sender, WebGrid.Events.BeforeGetDataEventArgs e)
        {
            if (e.Table == ((Grid)sender).MasterTable)
            {
                BeforeGetDataExecuted++;
                NorthwindEmployeeData employeedata = new NorthwindEmployeeData();

                List<NorthwindEmployee> employees = employeedata.GetAllEmployeesList("", 0, 100);
                e.Table.DataSource = employees;
            }
            else if (e.Table == ((WebGrid.Foreignkey)((Grid)sender).Columns["CustomerType"]).Table)
            {
                e.Table.Columns["CustomerType"].ColumnType = WebGrid.Enums.ColumnType.Number;
                e.Table.Columns["Title"].ColumnType = WebGrid.Enums.ColumnType.Text;

                WebGrid.Data.Row row = new WebGrid.Data.Row(e.Table);

                row["CustomerType"].Value = 1;
                row["Title"].Value = "Title";
                e.Table.Rows.Add(row);

                row = new WebGrid.Data.Row(e.Table);
                row["CustomerType"].Value = 2;
                row["Title"].Value = "Title";
                e.Table.Rows.Add(row);

                row = new WebGrid.Data.Row(e.Table);
                row["CustomerType"].Value = 3;
                row["Title"].Value = "Title";
                e.Table.Rows.Add(row);
            }
            else if (e.Table == ((WebGrid.Foreignkey)((Grid)sender).Columns["CustomerType2"]).Table)
            {
                NorthwindEmployeeData employeedata = new NorthwindEmployeeData();

                List<NorthwindEmployee> employees = employeedata.GetAllEmployeesList("", 0, 100);
                e.Table.DataSource = employees;
            }
        }
Esempio n. 37
0
 void grid_BeforeUpdateInsert(object sender, WebGrid.Events.BeforeUpdateInsertEventArgs e)
 {
     Assert.IsNotNull(e.Row["Value"].Value);
     Assert.AreEqual(e.Row["Value"].Value, "mytest");
 }