Sunday, February 19, 2012

ChangingResponse type at server side on click of button which is in updatepanel

ASPX Code :

< asp:ScriptManager ID="scManager" runat="server">< /asp:ScriptManager>
< asp:UpdatePanel ID="aaa" runat="server" UpdateMode="Conditional">
< ContentTemplate>
< asp:Button ID="Button1" runat="server" onclick="Button1_Click" Text="Downlaod" />
< /ContentTemplate>
< Triggers>
< /Triggers>
< /asp:UpdatePanel>

Page Load Event :

string strScriptKey = this.ClientID + "_AsposeDownload";
if (!this.Page.ClientScript.IsClientScriptBlockRegistered(strScriptKey))
{
string strScriptBlock = "";
this.Page.ClientScript.RegisterClientScriptBlock(this.GetType(), strScriptKey, strScriptBlock);
}


JS Code :


function blockUIForDownload() {
Download();
}


function Download() {
try {
location.href = "Handler1.ashx";
//finishDownload();
}
catch (err) {
}
return false; // Return false to stop the page posting back
}


Global Handler with the following code:


using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using Aspose.Slides.Pptx;

namespace WebApplication1
{
///
/// Summary description for Handler1
///
public class Handler1 : IHttpHandler
{

public void ProcessRequest(HttpContext context)
{
PresentationEx pres = new PresentationEx();
SlideEx slide = pres.Slides[0];
slide.Shapes.AddAutoShape(ShapeTypeEx.Rectangle, 0, 0, 500, 100);
slide.Shapes.AddAutoShape(ShapeTypeEx.Rectangle, 0, 305, 500, 100);
TextFrameEx tf1 = ((AutoShapeEx)slide.Shapes[0]).TextFrame;
TextFrameEx tf2 = ((AutoShapeEx)slide.Shapes[1]).TextFrame;
for (int i = 0; i < 500; i++)
{
tf1.Text += "\r\rQa will continue &amp; testing for al formatting issue\r\r";
tf2.Text += "";
}
ParagraphEx para1 = tf1.Paragraphs[0];
ParagraphEx para2 = tf2.Paragraphs[0];
para2.BulletType = BulletTypeEx.Numbered;
ParagraphEx para3 = new ParagraphEx();
para3.BulletType = BulletTypeEx.Numbered;
para3.Indent = 144;
para3.Alignment = TextAlignmentEx.Center;
para3.Text = "";
tf2.Paragraphs.Add(para3);
para1.MarginLeft = 72;
para2.Indent = 144;
float Par1Margin = para1.MarginLeft;
string strHttpResCT = "application/vnd.ms-powerpoint";
string strHttpHdrCD = "attachment; filename=PowerPointFile.pptx";
Aspose.Slides.Export.SaveFormat sfOutputFormat = Aspose.Slides.Export.SaveFormat.Pptx;
HttpContext.Current.Response.ContentType = strHttpResCT;
HttpContext.Current.Response.AddHeader("Content-Disposition", strHttpHdrCD);
pres.Save(HttpContext.Current.Response.OutputStream, sfOutputFormat);
HttpContext.Current.Response.Flush();

}

public bool IsReusable
{
get
{
return false;
}
}
}
}

Wednesday, February 15, 2012

AJAX, file downloads, and IFRAMEs

We’ve probably all implemented this functionality in ASP.NET applications at least several times. Any time you’re dealing with report data, it’s expected that the data be available for download. Unfortunately, AJAX makes this somewhat difficult. Since there is no traditional HTTP response, you have no context with which to send the file to the browser for normal download.

Enter inline frames (IFRAME). Probably one of the most under utilized HTML elements around, dynamically creating an IFRAME allows you to round trip an HTTP request and response without disrupting the AJAX-ness of your async postback. Since any browser that supports XmlHttpRequest supports IFRAMEs, it is as safe to use as AJAX is in the first place. This is a simple example of the technique, using a static list of files in a dropdown, but it could be adapted to more dynamic file creation scenarios easily.


This is the example download page. The JavaScript comments explain how the IFRAME is created and directed to the GenerateFile.aspx:

< html>

< body>

< form id="form1" runat="server">

< asp:ScriptManager runat="server" />

< script language="javascript">

// Get a PageRequestManager reference.

var prm = Sys.WebForms.PageRequestManager.getInstance();

// Hook the _initializeRequest event and add our own handler.

prm.add_initializeRequest(InitializeRequest);

function InitializeRequest(sender, args)

{

// Check to be sure this async postback is actually

// requesting the file download.

if (sender._postBackSettings.sourceElement.id == "DownloadFile")

{

// Create an IFRAME.

var iframe = document.createElement("iframe");

// Get the desired region from the dropdown.

var region = $get("Region").value;

// Point the IFRAME to GenerateFile, with the

// desired region as a querystring argument.

iframe.src = "GenerateFile.aspx?region=" + region;

// This makes the IFRAME invisible to the user.

iframe.style.display = "none";

// Add the IFRAME to the page. This will trigger

// a request to GenerateFile now.

document.body.appendChild(iframe);

}

}

< /script>

< asp:UpdatePanel runat="server">

< ContentTemplate>

< asp:DropDownList runat="server" ID="Region">

< asp:ListItem Value="N">North Region< /asp:ListItem>

< asp:ListItem Value="W">West Region< /asp:ListItem>

< asp:ListItem Value="SE">Southeast Region< /asp:ListItem>

< /asp:DropDownList>

< asp:Button runat="server" ID="DownloadFile" Text="Generate Report" />

< /ContentTemplate>

< /asp:UpdatePanel>

< /form>

< /body>

< /html>

GenerateFile.aspx can be empty, other than the Page directive to wire up the code file. There, you write the file to the response object just the same as you normally would:

protected void Page_Load(object sender, EventArgs e)

{

string FileResponse;

string Region = Request.QueryString["Region"];

// Code here to fill FileResponse with the

// appropriate data based on the selected Region.

Response.AddHeader("Content-disposition", "attachment; filename=report.csv");

Response.ContentType = "application/octet-stream";

Response.Write(FileResponse);

Response.End();

}

Now, when DownloadFile is clicked the file will be sent to the user asynchronously. Easy as that.

Monday, February 13, 2012

DoCallback Function Implementation for Response.end Response.flush

Here is DoCallback Function Implementation when you use Response.end Response.flush in your aspx page

ASPX Code :

< %@ Page language="c#" Codebehind="WebForm1.aspx.cs" inherits="MsdnMag.CallbackPage" %>

< SCRIPT language="javascript">

function DoCallback(url, params)

{

var pageUrl = url + "?callback=true&param=" + params;

var xmlRequest = new ActiveXObject("Microsoft.XMLHTTP");

xmlRequest.open("POST", pageUrl, false);

xmlRequest.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");

xmlRequest.send(null);

return xmlRequest;

}

function MoreInfo()

{

var selectedEmpID = document.all["EmployeeList"].value;

var xmlRequest = DoCallback("webform1.aspx", selectedEmpID);

// sync updates

Msg.innerHTML = xmlRequest.responseText;

}

< /SCRIPT>

< HTML>

< HEAD>

< title>Script Callbacks< /title>

< /HEAD>

< body>

< form runat="server">

< h1>Demonstrate Out-of-band Calls< /h1>

< h2>< %=Request.Url%>< /h2>

< hr>

< asp:DropDownList Runat="server" ID="EmployeeList" />

< Button Runat="server" ID="ButtonGo">Go Get Data< /Button>

< hr>

< span ID="Msg" />

< /form>

< /body>

< /HTML>

Code Behind:

using System;

using System.Data;

using System.Data.SqlClient;

using System.Drawing;

using System.Web;

using System.Web.SessionState;

using System.Web.UI;

using System.Web.UI.WebControls;

using System.Web.UI.HtmlControls;

// Definition of the page class

namespace MsdnMag

{

public class CallbackPage : System.Web.UI.Page

{

// References to page controls

protected DropDownList EmployeeList;

protected HtmlButton ButtonGo;

// Initialize the page here

private void Page_Load(object sender, EventArgs e)

{

if (IsCallback())

return;

if (!IsPostBack)

PopulateList();

// Button-to-callback binding

string callbackRef = "MoreInfo()";

ButtonGo.Attributes["onclick"] = callbackRef;

}

private bool IsCallback()

{

if (Request.QueryString["callback"] != null)

{

string param = Request.QueryString["param"].ToString();

Response.Write(RaiseCallbackEvent(param));

Response.Flush();

Response.End();

return true;

}

return false;

}

// Handle the "Go Get Data" button click

protected void OnGoGetData(object sender, EventArgs e)

{

}

// Populate the drop-down list with employee names

private void PopulateList()

{

//SqlDataAdapter adapter = new SqlDataAdapter(

// "SELECT employeeid, lastname FROM employees",

// "SERVER=(local);DATABASE=northwind;TRUSTED_CONNECTION=true;");

//DataTable table = new DataTable();

//adapter.Fill(table);

//EmployeeList.DataTextField = "lastname";

//EmployeeList.DataValueField = "employeeid";

DataTable dt = CreateDataTable();

AddDataToTable("test", "test", "test", dt);

EmployeeList.DataSource = dt;

EmployeeList.DataBind();

}

private DataTable CreateDataTable()

{

DataTable myDataTable = new DataTable();

DataColumn myDataColumn;

myDataColumn = new DataColumn();

myDataColumn.DataType = Type.GetType("System.String");

myDataColumn.ColumnName = "id";

myDataTable.Columns.Add(myDataColumn);

myDataColumn = new DataColumn();

myDataColumn.DataType = Type.GetType("System.String");

myDataColumn.ColumnName = "username";

myDataTable.Columns.Add(myDataColumn);

myDataColumn = new DataColumn();

myDataColumn.DataType = Type.GetType("System.String");

myDataColumn.ColumnName = "firstname";

myDataTable.Columns.Add(myDataColumn);

myDataColumn = new DataColumn();

myDataColumn.DataType = Type.GetType("System.String");

myDataColumn.ColumnName = "lastname";

myDataTable.Columns.Add(myDataColumn);

return myDataTable;

}

private void AddDataToTable(string username, string firstname, string lastname, DataTable myTable)

{

DataRow row;

row = myTable.NewRow();

row["id"] = Guid.NewGuid().ToString();

row["username"] = username;

row["firstname"] = firstname;

row["lastname"] = lastname;

myTable.Rows.Add(row);

}

// *******************************************************

// Implement the callback interface

string RaiseCallbackEvent(string eventArgument)

{

return "You clicked: " + eventArgument;

}

// *******************************************************

}

}