Exception message: Server cannot set status after HTTP headers have been sent. when generate pdf file in ASP.NET MVC3

I resolved this issue by changing my code as below:

Add below code to the return statement of your action in the controller.

return null;

public ActionResult DownloadAttachment()
        {
            try
            {
                LocalReport localReport = new LocalReport();
            localReport.ReportPath = Server.MapPath("~/Reports/rptInvoice.rdlc");
            ReportDataSource reportDataSource = new ReportDataSource("ProductDataSet",
                new InvoiceViewModel().GetAllProductInvoice());
            localReport.DataSources.Add(reportDataSource);

            string reportType = "pdf";
            string mimeType;
            string encoding;
            string fileNameExtension;
            //The DeviceInfo settings should be changed based on the reportType             
            //http://msdn2.microsoft.com/en-us/library/ms155397.aspx             
            string deviceInfo =
                "<DeviceInfo>" +
                "  <OutputFormat>PDF</OutputFormat>" +
                "  <PageWidth>8.5in</PageWidth>" +
                "  <PageHeight>11in</PageHeight>" +
                "  <MarginTop>0.5in</MarginTop>" +
                "  <MarginLeft>1in</MarginLeft>" +
                "  <MarginRight>1in</MarginRight>" +
                "  <MarginBottom>0.5in</MarginBottom>" +
                "</DeviceInfo>";
            Warning[] warnings;
            string[] streams;
            byte[] renderedBytes;
            //Render the report             
            renderedBytes = localReport.Render(
                reportType,
                deviceInfo,
                out mimeType,
                out encoding,
                out fileNameExtension,
                out streams,
                out warnings);

                Response.Clear();
                Response.ClearHeaders();
                Response.ClearContent();
                Response.ContentType = "application/pdf";
                Response.AddHeader("Content-Disposition", string.Format("attachment; filename=Invoice.pdf"));
                Response.BinaryWrite(content);
            }
            catch { }

            return null;
        }

Happy Coding

Posted in Uncategorized | 1 Comment

ASP.NET MVC 3: Save .pdf file to database and download pdf file from databse.

The article previous I was introduce about Using Microsoft Report Viewer in ASP.NET MVC3. In this article I will introduce about how to save .pdf file to database in ASP.NET MVC 3.

1. Create a new database to store pdf file and set named Database.mdf.

2. Create a new table and set named DataFiles

image

3. Create a new DataFileModel.edmx under Models folder.

image

4.Add two buttons Save and Download in Index.aspx file

</pre>
<div style="float: left; width: 100%;"><% using(Html.BeginForm("SaveFile","Home")) { %>
 <input style="float: left;" type="submit" value="Save file" />
 <%} %>

 <% using(Html.BeginForm("Download","Home")) { %>
 <input style="float: left;" type="submit" value="Download" />
 <%} %></div>
<pre>

5. Create method SaveFile in HomeController.

public ActionResult SaveFile()
        {
            LocalReport localReport = new LocalReport();
            localReport.ReportPath = Server.MapPath("~/Reports/rptCustomer.rdlc");
            ReportDataSource reportDataSource = new ReportDataSource("Customer",
                new CustomerModel().GetAllCustomer());
            localReport.DataSources.Add(reportDataSource);

            string reportType = "pdf";
            string mimeType;
            string encoding;
            string fileNameExtension;
            //The DeviceInfo settings should be changed based on the reportType
            //http://msdn2.microsoft.com/en-us/library/ms155397.aspx
            string deviceInfo =
                "" +
                "  PDF" +
                "  8.5in" +
                "  11in" +
                "  0.5in" +
                "  1in" +
                "  1in" +
                "  0.5in" +
                "";
            Warning[] warnings;
            string[] streams;
            byte[] renderedBytes;
            //Render the report
            renderedBytes = localReport.Render(
                reportType,
                deviceInfo,
                out mimeType,
                out encoding,
                out fileNameExtension,
                out streams,
                out warnings);

            // Save to Database
            DataFile dataFile = new DataFile {
                FileName = "Customer",
                FileData = renderedBytes,
                FileExtension = ".pdf"
            };

            bool Status;
            try
            {
                context.DataFiles.AddObject(dataFile);
                context.SaveChanges();
                ViewBag.Status = true;
                return View();
            }
            catch {
                ViewBag.Status = false;
                return View();
            }
        }

6. Create SaveFile.aspx to display message after save file

</pre>
<h2></h2>
<pre>
 <% if (ViewBag.Status == true)      { %></pre>
<div>Save file to Database is successful!</div>
<pre>
     <%         }      else      {       %></pre>
<div>Save file to Database is fail!</div>
<pre>
     <%       } %>

7. Build and run website so click Save button to save file to database.

image

8. Open database to check data.

image

9. The next we will implement action download pdf file from database.

Create a new method Download in HomeController.

public ActionResult Download()
        {
            DataFile dataFile = context.DataFiles.SingleOrDefault(p => p.Id == 1);
            byte[] fileData = dataFile.FileData;

            // Generate PDF file
            Warning[] warnings = null;
            String[] streamids = null;
            String mimeType = null;
            String encoding = null;
            String extension = null;

            Response.Clear();
            Response.ClearHeaders();
            Response.ClearContent();
            Response.ContentType = mimeType;
            Response.AddHeader("Content-Disposition", string.Format("attachment; filename=Customer.pdf"));
            Response.BinaryWrite(fileData);
            Response.End();

            return RedirectToAction("Index");
        }

10. Build and run website, so click Download button to download pdf file.

image

View pdf file after download.

image

Happy coding!

Posted in ASP.NET MVC | 3 Comments

Using Partial View to implement Search Bar in ASP.NET MVC3

In this article previous I was introduce about Using Partial View in ASP.NET MVC 3. To day I will introduce step by step how to use Partial View to implement Search Bar in ASP.NET MVC3.

1. Create a new project with Razor View engine and set named MvcApplications.SearchBar

image

2. Create two classes Product.cs and ProductModel.cs under Model folder

public class Product
    {
        public int Id { get; set; }
        public string Name { get; set; }
        public double Price { get; set; }
        public string Description { get; set; }
    }

 

public class ProductModel
    {
        public static List Products()
        {
            List productList = new List() {
                new Product {Id = 1, Name = "HTC HD7", Price = 100, Description = "HTC HD7"},
                new Product {Id = 2, Name = "HTC Trophy", Price = 80, Description = "HTC Trophy"},
                new Product {Id = 3, Name = "Samsung Galaxy S1", Price = 100, Description = "Samsung Galaxy S1"},
                new Product {Id = 4, Name = "Samsung Galaxy S2", Price = 110, Description = "Samsung Galaxy S2"},
                new Product {Id = 5, Name = "Samsung Galaxy S3", Price = 120, Description = "Samsung Galaxy S3"},
            };

            return productList;
        }

        public static List FillProduct(string name)
        {
            List productList = new List();
            productList = Products().Where(p => p.Name.Contains(name)).ToList();

            return productList;
        }
    }

3. Create a  SearchController under /Controllers that contains a Resultsaction.  This action will be called when a search request is entered and the user presses Enter or the Search button.  The action accepts a string parameter,searchText, which will contain the string the user searched on.  We can do our search logic in here and present a view containing the search results that match the user’s request.

image

4. Create a new PartialView under /Views/Shared, called _SearchBarPartial.cshtml. This contains a TextBox and a Search button wrapped inside a Form.

image

The form in _SearchBarPartial.cshtml is declared with some additional parameters to tell it that the Post should go to a our Results action in the Searchcontroller.

_SearchBarPartial.cshtml

</pre>
<div class="search-bar">@using (Html.BeginForm("Results", "Search"))
{
 @Html.TextBox("SearchText")
 <input class="search-button1" type="submit" value="Search" />
}</div>
<pre>

6. In the _Layout.cshtml we will call _SearchBarPartial.cshtml

@Html.Partial("_SearchBarPartial")

The _Layout.cshtml


    @ViewBag.Title
<script type="text/javascript" src="@Url.Content("></script>

</pre>
<div class="page">
<div id="header">
<div id="title">
<h1>Search Bar Application</h1>
</div>
<div id="logindisplay">@Html.Partial("_LogOnPartial")</div>
<div id="searchdisplay">@Html.Partial("_SearchBarPartial")</div>
<div id="menucontainer">
<ul id="menu">
	<li>@Html.ActionLink("Home", "Index", "Home")</li>
	<li>@Html.ActionLink("About", "About", "Home")</li>
</ul>
</div>
</div>
<div id="main">@RenderBody()</div>
<div id="footer"></div>
</div>
<pre>

7. The next we will implement action Result in SearchController.

[HttpPost]
public ActionResult Results(string searchText)
{
   var result = ProductModel.FillProduct(searchText);
   return View(result);
}

8. Add Results.cshtml to display result.

image

9. Build and run website

image

Happy coding!

Posted in ASP.NET MVC | 2 Comments

Using MS Report Viewer in ASP.NET MVC3

This article I  will introduce step by step how to use Microsoft Report Viewer in ASP.NET MVC3

1. Create a new project with View engine is ASPX and set named MvcApplications.MSReportViewer

image

2. Add references Microsoft.ReprotViewer.Common and Microsoft.ReportViewer.WebForms to project. You can find two .dll file in  “C:\Program Files (x86)\Microsoft Visual Studio 10.0\ReportViewer”.

3. Create two classes Customer.cs and CustomerModel under Models folder

public class Customer
    {
        public int Id { get; set; }

        public string Name { get; set; }

        public string Address { get; set; }

        public string Place { get; set; }
    }
public class CustomerModel
    {
        public virtual List GetAllCustomer()
        {
            List customerList = new List {
                new Customer { Id = 1, Name = "Patrick", Address = "Geuzenstraat 29", Place = "Amsterdam" },
                new Customer { Id = 2, Name = "Fred", Address = "Flink 9a", Place = "Rotterdam" },
                new Customer { Id = 3, Name = "Sjonnie", Address = "Paternatenplaats 44", Place = "Enkhuizen" },
                new Customer { Id = 4, Name = "Henk", Address = "Wakerdijk 74", Place = "Utrecht" },
                new Customer { Id = 5, Name = "Klaas", Address = "Paternatenplaats 44", Place = "Plaantan" },
                    new Customer { Id = 6, Name = "Andre", Address = "Wolbrantskerkweg 90B ", Place = "Los Angeles" },
                    new Customer { Id = 7, Name = "Pieter", Address = "Sam van Houtenstraat 191H", Place = "Emmen" },
                    new Customer { Id = 8, Name = "Sjohn", Address = "Polostraat, M. 103-II", Place = "Kantens" },
                    new Customer { Id = 9, Name = "John", Address = "Paternatenplaats 44", Place = "Leiden" },
                    new Customer { Id = 10, Name = "Bruin", Address = "Anthony Spatzierhof 9", Place = "Maasbracht" },
                    new Customer { Id = 11, Name = "Sjonnie", Address = "Van Heuven Goedhartlaan 201", Place = "Potters" },
                    new Customer { Id = 12, Name = "Lumunon", Address = "Paternatenplaats 44", Place = "Utrecht" },
                    new Customer { Id = 13, Name = "Friese", Address = "Burgemeester Roellstr 243-4", Place = "Rotterdam" },
                    new Customer { Id = 14, Name = "Hudephol", Address = "Bilhamerstraat 4", Place = "Vlaardingen" },
                    new Customer { Id = 15, Name = "Postema", Address = "Mastbos 77", Place = "Schiedam" },
                    new Customer { Id = 16, Name = "Scharn", Address = "Marius Bauerstraat 123", Place = "Dordrecht" },
                    new Customer { Id = 17, Name = "Wagenmakers", Address = "Pieter Postsingel 16", Place = "Ede" },
                    new Customer { Id = 18, Name = "Gedikli", Address = "Burgemeester Hogguerstr 283", Place = "Twello" },
                    new Customer { Id = 19, Name = "Zwollo", Address = "Meervalweg 140", Place = "Terschelling" },
                    new Customer { Id = 20, Name = "Sjonnie", Address = "Ruys de Beerenbrouckstr 79A", Place = "Ter Aar" },
                    new Customer { Id = 21, Name = "Schimmelmann", Address = "Ritzema Bosstraat 28-2", Place = "Vierenman" },
                    new Customer { Id = 22, Name = "Makhlouf", Address = "Ln vd Helende Meesters 12", Place = "Eindhoven" },
                    new Customer { Id = 23, Name = "Meyer", Address = "Burgemeester v Leeuwenln 79H", Place = "Breda" },
            };

            return customerList;
        }
    }

4. Create a folder and set named Reports.  After that create a new rptCustomer.rdlc file under this folder.

image

5. In Report Data window create new Dataset… and set property the same picture below

image

6. rptCustomer.rdlc file after designed:

image

7. Define action PrintReport in HomeController

public ActionResult PrintReport()
        {
            LocalReport localReport = new LocalReport();
            localReport.ReportPath = Server.MapPath("~/Reports/rptCustomer.rdlc");
            ReportDataSource reportDataSource = new ReportDataSource("CustomerDataSet",
                new CustomerModel().GetAllCustomer());
            localReport.DataSources.Add(reportDataSource);

            string reportType = "pdf";
            string mimeType;
            string encoding;
            string fileNameExtension;
            //The DeviceInfo settings should be changed based on the reportType             
            //http://msdn2.microsoft.com/en-us/library/ms155397.aspx             
            string deviceInfo =
                "<DeviceInfo>" +
                "  <OutputFormat>PDF</OutputFormat>" +
                "  <PageWidth>8.5in</PageWidth>" +
                "  <PageHeight>11in</PageHeight>" +
                "  <MarginTop>0.5in</MarginTop>" +
                "  <MarginLeft>1in</MarginLeft>" +
                "  <MarginRight>1in</MarginRight>" +
                "  <MarginBottom>0.5in</MarginBottom>" +
                "</DeviceInfo>";
            Warning[] warnings;
            string[] streams;
            byte[] renderedBytes;
            //Render the report             
            renderedBytes = localReport.Render(
                reportType,
                deviceInfo,
                out mimeType,
                out encoding,
                out fileNameExtension,
                out streams,
                out warnings);
            //Response.AddHeader("content-disposition", "attachment; filename=NorthWindCustomers." + fileNameExtension);             
            return File(renderedBytes, mimeType);
        }

8. Add ActionLink in Index view

<p>
    <%: Html.ActionLink("PrintReport", "PrintReport", "Home")%>
</p>

9. Build and Run website.

image

10. Click PrinReport

image image

Posted in ASP.NET MVC | 6 Comments

Error: “The report definition has an invalid target namespace ‘http://schemas.microsoft.com/sqlserver/reporting/2008/01/reportdefinition’ which cannot be upgraded.” when run MS Reportviewer and ASP MVC3.

Solution to fix this problem:

Turns out the issue was my “C:\Program Files (x86)\MSBuild\Microsoft\VisualStudio\v10.0\ReportingServices\Microsoft.ReportingServices.targets” file had somehow changed. The top of my file was:

<Project xmlns="http://schemas.microsoft.com/developer/msbuild/2003"> <UsingTask TaskName="Microsoft.Reporting.RdlCompile" AssemblyName="Microsoft.ReportViewer.Common, Version=9.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a"/>

And it should have been:

<Project xmlns="http://schemas.microsoft.com/developer/msbuild/2003"> <UsingTask TaskName="Microsoft.Reporting.RdlCompile" AssemblyName="Microsoft.ReportViewer.WebForms, Version=10.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a"/>

OR

Just install Microsoft Report Viewer 2010 SP1. You can go to this link to download then install MS Report Viewer 2010 SP1

Posted in ASP.NET MVC | 5 Comments

Error: Server Error in Application "DEFAULT WEB SITE" when run asp.net MVC 3 in IIS 7.5 and Windows 7 64bit

When I run website in IIS 7.5 with Windows 7 64bit I have receive error message:

image

Solutions: To fix this problem you implement by steps:

1. Open IIS

2. Click Application Pools/Right click ASP.NET v4.0 in the list of Application Pools then click Advanced Setting

3. Change value of Enable 32-Bit Application property from False to True

image

4. Re-run application.

Posted in ASP.NET MVC | 3 Comments

Using Partial View in ASP.NET MVC3

1. Create a new project and set project name is MvcApplications.PartialView

image

2. Create a new class Product in Models folder

 public class Product
    {
        public int Id { get; set; }
        public string Name { get; set; }
        public float Price { get; set; }
    }

3. Create a new ProductViewModel in Models folder

public class ProductViewModel
    {
        public Product Pro;
    }

4. Create _FeaturedProduct partial view

Right click Shared folder –> add View. Sure Create as partial view checkbox is checked

image

So it is detail cshtml file:

@model MvcApplications.PartialView.Models.Product

<style type="text/css"> 
    .featuredProduct {border: solid 1px #000} 
</style>

<div> 
    <div> 
        <h2> 
            Our Featured product:<br /> 
            @ViewBag.FeaturedProduct.Name 
        </h2> 
    </div>    
    <div> 
        <h3> 
            Now discounted to $@String.Format("{0:F}", ((decimal)ViewBag.FeaturedProduct.Price)-100) 
        </h3> 
    </div>   

</div>

5. Call Partial view from Index view

<div>
  @Html.Partial("_FeaturedProduct")
</div>

6. In controller code-behind

ProductViewModel productModel = new ProductViewModel();

        public ActionResult Index()
        {
            ViewBag.FeaturedProduct = new Product() {Id = 1, Name = "HTC Trophy", Price= 400 };

            return View(productModel.Pro);
        }

7. Build solution and run

image

Posted in ASP.NET MVC | 2 Comments