0

Using SharePoint 2010 sandbox webpart, I am dynamically making a pdf file in memory. I want to have a download browser prompt after the file is made however I am having issues with HttpContext.Current.Response where it throws the error

System.NullReferenceException: Object reference not set to an instance of an object. at System.Web.HttpApplication.CompleteRequest() at System.Web.HttpResponse.End()

Here is my code

    protected override void CreateChildControls() {
        Button btnExport = new Button();
        btnExport.Text = "Export";
        btnExport.Click += new EventHandler(this.btnExport_Click);
        this.Controls.Add(btnExport);
    }

    protected void btnExport_Click(object sender, EventArgs e) {
        // shorten code that is making PDF document
        saveFileLocal();
    }

    public void saveFileLocal(){
        var Response = HttpContext.Current.Response;
        byte[] file = returnPDFBytes();
        Response.Clear();
        // Clear the content of the response
        Response.ClearContent();
        Response.ClearHeaders();

        // Buffer response so that page is sent after processing is complete.
        Response.BufferOutput = true;

        // Add the file name and attachment, which will force the open/cance/save dialog to show, to the header
        Response.AddHeader("Content-Disposition", "attachment; filename=myfile.pdf");

        // Add the file size into the response header
        Response.AddHeader("Content-Length", file.Length.ToString());

        // Set the ContentType
        Response.ContentType = "Application/pdf";

        Response.BinaryWrite(file);
        Response.Flush();
        Response.End();
    }

I hope the provided information helps explain as it's very odd to me that this isn't work.

Amal Hashim
  • 28,306
  • 5
  • 31
  • 61
user3643344
  • 177
  • 1
  • 10

2 Answers2

1

Sandbox solution runs on its own process. Hence the HttpContext you are using will not work.

Write file to response problem

Amal Hashim
  • 28,306
  • 5
  • 31
  • 61
  • So is there no alternative solution to allow a user to download the newly made file? – user3643344 Jan 30 '15 at 18:32
  • Could you write the created file to a document library and present that link to the user? – Eric Alexander Jan 30 '15 at 18:50
  • Something like will end having to be the last resort as I'm thinking what we will have to do is upload to library, run _layouts/download.aspx?SourceURL=LIBRARYURLHERE and then delete it which is very hacky ;/ – user3643344 Jan 30 '15 at 18:57
0

This could be your problem. Try this and let know how it turns out.

HttpContext modification breaks SharePoint Site http://www.codeproject.com/Tips/135864/HttpContext-modification-breaks-SharePoint-Site

jpollar
  • 1,127
  • 1
  • 7
  • 12