WiredWorx || Web design || SEO || Bournemouth

Web design, website development and search engine optimisation (SEO) in Bournemouth, Dorset, UK.

Exporting to an excel file from ASP.NET MVC


I was intrigued about how to create an excel file from a datasource the other day as ASP.NET MVC obviously is very different from web forms. In web forms there are a hundred and one ways to do this, the easiest we found was to use a plug in such as ASPOSE which then allows you easily to export to a .xls file.

After a bit of searching the t'interweb I stumbled upon this great article from Bill SternBerger. I have also copied and pasted it in below as I'm worried that his blog hasn't been updated for over a year and so it may just disappear one day!

Since programming way back in the Classic ASP days, at some point a client always wants to export an html grid into an Excel grid. In c#, that need didn’t disappear, but got a lot easier with GridView and the HtmlTextWriter. Finally reached that point in my ASP.NET MVC programming world, and quite frankly, am surprised it took this long, for this same need! But I digress. To pull this off, all we are really going to do is add an export method to a controller, most of which will look very familiar to asp.net web forms.

Add using statements

using System.Web.UI;
using System.Web.UI.WebControls;
using System.IO;

We are going to use our dear old friend the GridView from web forms as a placeholder for our data, which is why we need the second using statement.

Create Controller Method

This one is pretty easy, consisting of three parts:

  • Creating the GridView placeholder
  • Binding the query results to the GridView placeholder
  • Dumping the results back to the browser

This example queries all contacts that have not unsubscribed, but you can imagine how easy it is to extend.
var contacts = Contact.FindAll();
var grid = new System.Web.UI.WebControls.GridView();

grid.DataSource = from contact in contacts
where contact.Unsubscribe == false
select new
{
ContactID = contact.ID,
FullName = contact.FullName,
Email = contact.Email
};
grid.DataBind();

Response.ClearContent();
Response.AddHeader("content-disposition", "attachment; filename=YourFileName.xls");
Response.ContentType = "application/excel";
StringWriter sw = new StringWriter();
HtmlTextWriter htw = new HtmlTextWriter(sw);
grid.RenderControl(htw);
Response.Write(sw.ToString());
Response.End();

That’s it!

Create a mock session in ASP.NET MVC using Rhino Mocks


screenshot of a mock session

Firstly we will introduce a few of the objects:
_testRepository => is a repository which implements the same interface as the controller we are putting to test.
_controller r => is the controller we are testing, which has an over-ridden constructor passing in the _testRepository.
_mockRepository => is a Rhino.Mocks class to create the mock data which we will be using.

The process is then fairly simple (although took about a day's worth of work to figure out!)
The first block of code is used to create the HttpSessionStateBase object and then create a stub which in effect is the mocked session variable and value.

The second block is where we create the HttpContextBase object, as the session needs to live in the context this step is necessary. There are also other elements of the context which may be mocked as well (such as request, response etc) but for this example we're not worried about them. We then set it so that when a session is requested from the calling code, the object will return the session mock that we just created.

The third block of code was what baffled me for a while! I am still not 100% sure what it is doing, but it seems that in order for these objects to be accessible to calling code they must be set into a 'Replay' state.

Finally we set the ControllerContext of our controller to be the mock context we have just set up... Et voila, the session variables that are set up are now accessible from the unit tests!

Ultimate ASP.NET MVC resource


This is more for our benefit than anyone else's but this hopefully should end up being a great resource for ASP.NET MVC reference material...

Development

UI
MVCContrib (HTML Helpers, Grid etc)
Creating a grid using MVCContrib and JQuery datatables

Coding
Creating Dynamic Linq queries and Scott Gu's blog post
Exporting to an excel file from ASP.NET MVC

Testing

How to create a mock session in ASP.NET MVC
Mocking HttpContext (sessions etc) in ASP.NET MVC unit tests

How to consume myspace events and then use that data to feed a website


For the artist management project we are currently working on one of the requirements was to have gigs and events that were currently up to date. One issue is that having to update this data is duplicating what is already held (and readily maintained) on other sites, the foremost being myspace (especially since they announced their new events features).

After some scouring the interweb it seemed that there wasn't yet a dedicated Myspace API. We found a couple of good hosted solutions (http://makedatamakesense.com/myspace/event/ and http://myspace.jochemschutte.nl/ ), but although these looked reliable we needed to be able to guarantee that in the future the service we were to use would not simply disappear and so really have to write our own!

We found the following article on codersource which details how to call upon a webpage and then to analyse and store the contents of what has been returned. This coupled with the very helpful regular expression on the MakeDataMakeSense page means that we should be able to cobble something together!

Will update with progress!

Save apostrophe to a MYSQL database using c#

Comments (0)

This is quite obvious, but I thought I'd post in anyhow!

On testing of a site the save kept failing on the create. After a bit of head scratching and staring at SQL it was because I had failed to validate the strings, so there were still apostrophes in there, MYSQL was thinking it was a string terminator and therefore getting it's knickers in a bit of a twist!

Continue reading

Forcing ie8 compatibility mode

Comments (0)

We all know that the last thing that really should be done is to try to force browsers into something they don't want to but when it comes to internet explorer, sometime there's nothing else for it!

Continue reading

Previewing a dataset in Visual Studio using dataset visualiser


For years I have had the problem of having populated datasets whilst debugging code but then not having a decent method of quickly previewing what was in these datasets, short of sticking a gridview on the page and looking that way!

Continue reading

Problem when trying to run site in visual studio


It seems that Microsoft in their wisdom altered Defender, on the 9th March which means that Windows Defender mistakenly raised the Win32/PossibleHostsFileHijack alarm deleting the crucial mapping between localhost and 127.0.0.1!

Continue reading

Retrieve the current page name


string sPath = System.Web.HttpContext.Current.Request.Url.AbsolutePath;
System.IO.FileInfo oInfo = new System.IO.FileInfo(sPath);
string sRet = oInfo.Name;


where sRet will be the name of the current page.