Downloading large files asp.net mvc 3? - asp.net

I have a large pdf file (upto 2 GBs) on a database server which I want to send to client for download. Also, I have size limitations on my web server and cannot store complete file on it, after requesting from data server. I am using asp.net mvc 3. Any suggestions on how can I accomplish this? Also I want it to be asynchronous since I don't want to block the user from clicking other buttons on the web page.
I have tried using this code.
//code for getting data from data server into inputstream
HttpContext.Response.ContentType = "application/pdf";
HttpContext.Response.AddHeader("Content-Disposition", "attachment; filename=" + filename);
HttpContext.Response.BufferOutput = false;
try
{
using (Stream inputStream = resp.GetResponseStream())
{
byte[] buffer = new byte[SegmentSize];
int bytesRead;
while ((bytesRead = inputStream.Read(buffer, 0, SegmentSize)) > 0)
{
HttpContext.Response.OutputStream.Write(buffer, 0, bytesRead);
HttpContext.Response.Flush();
}
}
}
catch (Exception ex)
{
//some code
}
This downloads the file but then I don't know how to make it asynchronous? Also is there any other way to do the download that would be asynchronous too?

You can use AJAX which is Asynchronous. For that use a library like JqueryUI and a plugin, take a look a this example
http://www.plupload.com/example_custom.php
Im sure this will do! :D

Turns out in my final application I did not use web service but simple AJAX and ASPX pages this is how I got it done!
Default.ASPX file
<%# Page Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="CloudWF._Default"
Culture="auto" meta:resourcekey="PageResource1" UICulture="auto" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
<link type="text/css" href="css/redmond/jquery-ui-1.8.21.custom.css" rel="stylesheet" />
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:ScriptManager ID="jsEng" runat="server">
<Scripts>
<asp:ScriptReference Path="~/js/jquery-1.7.2.min.js" />
<asp:ScriptReference Path="~/js/jquery-ui-1.8.21.custom.min.js" />
</Scripts>
</asp:ScriptManager>
<input type='submit' value='Process New Records' id='trigger' onclick='BeginProcess(); return false;' />
</div>
</form>
</body>
<script type="text/javascript">
var btnStart;
$(function () {
btnStart = $("#trigger").button();
imgLoad = $("#loader").hide();
});
function BeginProcess() {
btnStart.val("Collecting Data...");
//to get the value of the radiobuttons
//alert($('input[name=A]:checked').val()) --> [name=*] where *= whatever the name of the radioset
// Create an iframe.
var iframe = document.createElement("iframe");
// Point the iframe to the location of
// the long running process.
iframe.src = "process.aspx";
// Make the iframe invisible.
iframe.style.display = "none";
// Add the iframe to the DOM. The process
// will begin execution at this point.
document.body.appendChild(iframe);
btnStart.val("Processing...");
imgLoad.show();
btnStart.button("disable");
}
function UpdateProgress(RecordComplete, Message, step) {
btnStart.val("Downloaded Record " + RecordComplete + Message);
$("#progressbar").progressbar({
value: step
});
if (step >= 100) {
imgLoad.hide();
btnStart.val("Download Complete!");
}
}
</script>
Process.aspx.cs
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Web;
public partial class process : System.Web.UI.Page
{
WebClient wc = new WebClient();
Dictionary<string, string> AudioURLs = new Dictionary<string, string>();
protected void Page_Load(object sender, EventArgs e)
{
// Padding to circumvent IE's buffer*
Response.Write(new string('*', 256));
Response.Flush();
ProcessRecords();
}
public void ProcessRecords()
{
int recTotal;
recordList = (IQueryable<Record>)(Session["UNPROCESSED"]);
recTotal = recordList.Count();
if (recordList.Count() > 0)
{
foreach (Record record in recordList)
{
try
{
curRow++;
step = ((decimal)curRow / (decimal)recTotal) * 100;
CreateDictionary();
CreateFolderwithAudios(record.tSessionID);
//record.processed = true;
db.SubmitChanges();
UpdateProgress(curRow, " of " + recTotal, step);
}
catch (Exception x)
{
HttpContext.Current.Response.Write("Exception: " + x.Message);
}
}
Session["UNPROCESSED"] = null;
}
}
public Dictionary<string, string> CreateDictionary()
{
AudioURLs.Clear();
#region Add Values to Dictionary
return AudioURLs;
}
public void DownloadAudios(string _subFolder, Dictionary<string, string> _AudioSources)
{
foreach (KeyValuePair<string, string> kvp in _AudioSources)
{
if (kvp.Value.StartsWith("http://"))
{
try
{
wc.DownloadFile(kvp.Value, audiosPath + "\\" + _subFolder + "\\" + kvp.Key + ".wav");
}
catch (WebException webex)
{
throw new WebException(webex.Message);
}
catch (Exception ex)
{
throw new Exception(ex.Message);
}
}
}
}
public void CreateFolderwithAudios(string folderName)
{
try
{
//create the folder where the audios are going to be saved
Directory.CreateDirectory(audiosPath + folderName);
//create and read the Dictionary that contains the URLs for the audio files
DownloadAudios(folderName, AudioURLs);
}
catch (AccessViolationException ae)
{
HttpContext.Current.Response.Write(ae.Message);
}
catch (System.Exception x)
{
HttpContext.Current.Response.Write(x.Message);
}
}
protected void UpdateProgress(int PercentComplete, string Message, decimal step)
{
// Write out the parent script callback.
Response.Write(String.Format(
"<script>parent.UpdateProgress({0}, '{1}',{2});</script>",
PercentComplete, Message, step));
// To be sure the response isn't buffered on the server.
Response.Flush();
}

Related

Signalr and Devexpress

I want to create a grid and automatic update it, when data changes in the database. It works with a simple table control.
public partial class index : System.Web.UI.Page
{
static string connectionString = #"Data Source=*******;initial catalog=Test;persist security info=True; Integrated Security=SSPI;";
protected void Page_Load(object sender, EventArgs e)
{
}
[WebMethod]
public static IEnumerable<Person> GetData()
{
using (var connection = new SqlConnection(connectionString))
{
connection.Open();
using (SqlCommand command = new SqlCommand(#"SELECT [Id],[Name] FROM [dbo].[Persons]", connection))
{
command.Notification = null;
SqlDependency.Start(connectionString);
SqlDependency dependency = new SqlDependency(command);
dependency.OnChange += new OnChangeEventHandler(Dependency_OnChange);
if (connection.State == ConnectionState.Closed)
connection.Open();
using (var reader = command.ExecuteReader())
return reader.Cast<IDataRecord>()
.Select(x => new Person(x.GetInt32(0), x.GetString(1))).ToList();
}
}
}
private static void Dependency_OnChange(object sender, SqlNotificationEventArgs e)
{
MyHub.Show();
}
public void FillGrid()
{
List<Person> persons = new List<Person>();
using (var connection = new SqlConnection(connectionString))
{
connection.Open();
using (SqlCommand command = new SqlCommand(#"SELECT [Id],[Name] FROM [dbo].[Persons]", connection))
{
if (connection.State == ConnectionState.Closed)
connection.Open();
using (SqlDataReader rdr = command.ExecuteReader())
{
while (rdr.Read())
{
var id = rdr.GetInt32(0);
var name = rdr.GetString(1);
persons.Add(new Person(id, name));
}
}
}
}
grid.DataSource = persons;
grid.DataBind();
}
}
public class MyHub : Hub
{
public static void Show()
{
IHubContext context = GlobalHost.ConnectionManager.GetHubContext<MyHub>();
context.Clients.All.displayStatus();
}
}
And the apsx Page :
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
<script src="Scripts/jquery-1.6.4.min.js"></script>
<script src="Scripts/jquery.signalR-2.2.2.min.js"></script>
<script src="signalr/hubs"></script>
<script type="text/javascript">
$(function () {
// Proxy created on the fly
var job = $.connection.myHub;
// Declare a function on the job hub so the server can invoke it
job.client.displayStatus = function () {
getData();
};
// Start the connection
$.connection.hub.start();
getData();
});
function getData()
{
var $tbl = $('#tbl');
$.ajax({
url: '/index.aspx/GetData',
contentType: 'application/json;charset=utf-8',
datatype: 'json',
type: 'POST',
success: function (data) {
if (data.d.length > 0) {
var newdata = data.d;
$tbl.empty();
$tbl.append(' <tr><th>ID</th><th>Name</th></tr>');
var rows = [];
for (var i = 0; i < newdata.length; i++) {
rows.push(' <tr><td>' + newdata[i].Id + '</td><td>' + newdata[i].Name + '</td><td></tr>');
}
$tbl.append(rows.join(''));
}
}
});
}
</script>
</head>
<body>
<form id="form1" runat="server">
<div>
<table id="tbl"></table>
<dx:ASPxGridView ID="grid" runat="server"></dx:ASPxGridView>
</div>
</form>
</body>
</html>
However I want to use a Devepress Aspxgridview. The Devexpress Site states they don't support SignalR. However since the Javascript function is triggered when data changes in the database, is it possible somehow to force the client to get the data from the server? Force a postback and/or call the FillGrid method? ( To create the grid from js is not possible since the AspxgridView Control is much more complicated).
SOURCE: https://www.youtube.com/watch?v=30m-7wpmbrc
Although SignalR is not supported out of the box, it should be possible to manually notify the server side about the update using the existing API. You can send a callback to the server using the ASPxClientGridView.PerformCallback method, and handle the server side ASPxGridView.CustomCallback event to reload data from the SQL server.

Uploading image to ASP.NET site with avalible content-type

I currently have a web service set up to upload and save a file (.png image) to my website using the following code:
[WebMethod]
public string SaveDocument(byte[] docbinaryarray, string docname)
{
string strdocPath;
string docDirPath = Server.MapPath("\\") + uploadDir;
strdocPath = docDirPath + docname;
if (!Directory.Exists(docDirPath))
Directory.CreateDirectory(docDirPath);
FileStream objfilestream = new FileStream(strdocPath, FileMode.Create, FileAccess.ReadWrite);
objfilestream.Write(docbinaryarray, 0, docbinaryarray.Length);
objfilestream.Close();
return "http:\\\\example.com\\" + uploadDir + docname;
}
This code works fine, however when I access the image via the url I am not getting a content type that matches the png file (image/png). Is it possible to associate the content type when you upload a file so that when you visit the url (example.com/myimage.png) it returns the image with the image/png content type? Or do I need to somehow dynamically create webpages with the content type that link to these links?
EDIT:
The goal is to use this with a 3rd party API that needs to do a GET request and needs to know the content-type, right now it specifies as invalid.
I think that something is not configired well in a your web server that blocks files or you pass wrong file name to this web service method.
I tested it and wrote simple implementation and all worked well. ASP.NET page uploads image to web service, web service returns a URL to uploaded image, page displays the image through Image1 control.
My simple implementation:
Default.aspx:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<form runat="server">
<asp:FileUpload ID="FileUpload1" runat="server" />
<asp:Button ID="Button1" runat="server" Text="Button" OnClick="Button1_OnClick" />
<asp:Image ID="Image1" runat="server" />
</form>
</body>
</html>
Default.aspx.cs:
namespace TestAspNetWebApp
{
using System.IO;
using System;
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void Button1_OnClick(object sender, EventArgs e)
{
string appPath = Request.PhysicalApplicationPath + "\\uploads\\";
if (!Directory.Exists(appPath))
Directory.CreateDirectory(appPath);
if (FileUpload1.HasFile)
{
string savePath = appPath + Server.HtmlEncode(FileUpload1.FileName);
FileUpload1.SaveAs(savePath);
using (var objfilestream = new FileStream(savePath, FileMode.Open, FileAccess.Read))
{
var len = (int) objfilestream.Length;
var mybytearray = new Byte[len];
objfilestream.Read(mybytearray, 0, len);
var myservice = new WebService();
var fileurl = myservice.SaveDocument(mybytearray, FileUpload1.FileName);
Image1.ImageUrl = fileurl;
}
File.Delete(savePath);
}
}
}
}
WebService.asmx.cs:
namespace TestAspNetWebApp
{
using System.IO;
using System.Web.Services;
[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
[System.ComponentModel.ToolboxItem(false)]
public class WebService : System.Web.Services.WebService
{
private const string uploadDir = "uploads-websevice";
[WebMethod]
public string SaveDocument(byte[] docbinaryarray, string docname)
{
string strdocPath;
string docDirPath = Server.MapPath("\\") + uploadDir + "\\";
strdocPath = docDirPath + docname;
if (!Directory.Exists(docDirPath))
Directory.CreateDirectory(docDirPath);
var objfilestream = new FileStream(strdocPath, FileMode.Create, FileAccess.ReadWrite);
objfilestream.Write(docbinaryarray, 0, docbinaryarray.Length);
objfilestream.Close();
return "http://localhost:57064/" + uploadDir + "/" + docname;
}
}
}
Please add some example of your code to help you to define the problem and to solive it.
It seems that server returns all headers and also 'Content-type' as usual.
using (var client = new WebClient())
{
string uri = "http://chronicletwilio.azurewebsites.net/res/12345.png";
byte[] data = client.DownloadData(uri);
string contentType = client.ResponseHeaders["content-type"];
// contentType is 'image/png'
}
I figured out the problem. Even though the content type header was set, the file was not being read as an image, but only as a file. That being the case the 3rd party API I was using was not correctly reading it and complained about the content type. The fix ended up being chaning my method to the following:
[WebMethod]
public string SaveImage(byte[] docbinaryarray, string docname)
{
string strdocPath;
string docDirPath = Server.MapPath("/") + uploadDir;
strdocPath = docDirPath + docname;
if (!Directory.Exists(docDirPath))
Directory.CreateDirectory(docDirPath);
using (Image image = Image.FromStream(new MemoryStream(docbinaryarray)))
{
image.Save(strdocPath, ImageFormat.Png); // Or Png
}
return "http://example.com/" + uploadDir + docname;
}

Database notification using signalr and asp.net not displaying the data in UI

i followed the tutorial to from one of the online blog and am able get the application out with out error, but main issue is its not giving error as well as output.
My hub class looks like this
public void NotifyAllClients(string msg)
{
IHubContext context = GlobalHost.ConnectionManager.GetHubContext<NotificationsHub>();
context.Clients.All.displayNotification(msg);
}
My ASPX.CS page looks like this
protected void Page_Load(object sender, EventArgs e)
{
SendNotifications();
}
public void SendNotifications()
{
string message = string.Empty;
string conStr = ConfigurationManager.ConnectionStrings["TestDB"].ConnectionString;
using (SqlConnection connection = new SqlConnection(conStr))
{
string query = "SELECT [Message] FROM [dbo].[MessageBuffer]";
using (SqlCommand command = new SqlCommand(query, connection))
{
command.Notification = null;
SqlDependency dependency = new SqlDependency(command);
dependency.OnChange += new OnChangeEventHandler(dependency_OnChange);
connection.Open();
SqlDataReader reader = command.ExecuteReader();
if (reader.HasRows)
{
reader.Read();
message = reader[0].ToString();
}
}
}
NotificationsHub nHub = new NotificationsHub();
nHub.NotifyAllClients(message);
}
private void dependency_OnChange(object sender, SqlNotificationEventArgs e)
{
if (e.Type == SqlNotificationType.Change)
{
SendNotifications();
}
}
and My aspx page is --
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<script src="Scripts/jquery-1.8.2.min.js"></script>
<script src="Scripts/jquery.signalR-2.1.2.js"></script>
<script src="signalr/hubs"></script>
<script type="text/javascript">
$(function () {
var notify = $.connection.notificationsHub;
notify.client.displayNotification = function (msg) {
$('#newData').append('<li><strong>' + msg + '</li>');
};
$.connection.hub.start();
});
</script>
<div style="padding:10px 0px 10px 10px">
New Messages:
<ul id="newData"></ul>
</div>
</body>
</html>
i have done different samples, i have used same format to display, i am able to get those out in a hand, but here i am stuck with this. i am getting value in aspx.cs page, it calling the DB, which i have given in global.asax. and i have added sqldependency as well, enbabled broker in DB. but issue is still there. i cant see anything in UI.
Thanks in advance
I had a similar problem a while back. I just used the hub method name attribute and it worked for me. So you want something like
[HubMethodName("SendNotifications")]
public string SendNotifications()
And then at the front end just do
$.connection.hub.start(function () {
notify.server.SendNotifications();
});
Update
You could have a span the way I have in my code. so something like
<div>
<ul>
<li>New Messages:<span id="newData">0</span></a></li>
</ul>
</div>
Then do
$('#newData').text(msg);

Binding data to html5 DataList in asp.net

I'm trying my hands with HTML5. Is it possible to bind data to datalist in html5 as we bind data from a datatable to asp.net dropdown control.
Where i can find this details. any pointers is much appreciated. :)
Thanks
1) Assign runat="server" to the datalist so that it can be accessed from code behind:
Enter your favorite browser name:<br />
<input id="browserName" list="browsers" />
<datalist id="browsers" runat="server" />
2) Loop through the DataTable, construct and concatenate a list of options using a StringBuilder and add the result to the InnerHtml property of the datalist
protected void Page_Load(object sender, EventArgs e)
{
DataTable table = new DataTable();
table.Columns.Add("BrowserName");
table.Rows.Add("IE");
table.Rows.Add("Chrome");
table.Rows.Add("Firefox");
table.Rows.Add("Opera");
table.Rows.Add("Safari");
var builder = new System.Text.StringBuilder();
for (int i = 0; i < table.Rows.Count; i++)
builder.Append(String.Format("<option value='{0}'>",table.Rows[i][0]));
browsers.InnerHtml = builder.ToString();
}
If you're going to need this functionality in multiple places in your site, you can either create a WCF service and call it via jQuery where you can populate the datalist or create an HTTP handler like this:
1)Add a Generic Handler to your project and call it AutoCompleteHandler.ashx
2)Inside AutoCompleteHandler.ashx put:
public class AutoCompleteHandler : IHttpHandler
{
public void ProcessRequest(HttpContext context)
{
context.Response.ContentType = "text/plain";
context.Response.Clear();
var options = new System.Text.StringBuilder();
options.Append("<option value='IE'>");
options.Append("<option value='Chrome'>");
options.Append("<option value='Firefox'>");
options.Append("<option value='Safari'>");
options.Append("<option value='Opera'>");
context.Response.Write(options.ToString());
context.Response.End();
}
public bool IsReusable
{
get{return false;}
}
}
3)Call the handler via jQuery when the page loads and populate the datalist with the returned result:
<script src="Scripts/jquery-1.9.1.js" type="text/javascript"></script>
<script type="text/javascript">
$(document).ready(function () {
$.post('AutoCompleteHandler.ashx', function (data) {
$('#browsers').html(data);
});
});
</script>

Read server variables in classic ASP that have been set in ASP.NET httpmodule

EDIT:
Simple version of the question:
I want to create server variables in the .NET httpmodule and read them in my classic ASP code.
Is this possible? or the wrong approach?
ENDEDIT:
So I have taken over a classic asp application and the author wrote an ISASPI Filter dll and he used it to set server variables for his classic asp applications. I read on the IIS forums that the custom ISAPI filters are a bad idea and I should be using http modules if I'm going to move it forward.
So I pulled this method off of the internet that lets me set the server variables in my httpmodule, which seems to work for adding the item to the server variable collection... however I can't read it from my classic asp code.
Do I have the wrong approach?
BindingFlags temp = BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.Static;
var context = app.Context;
MethodInfo addStatic = null;
MethodInfo makeReadOnly = null;
MethodInfo makeReadWrite = null;
Type type = app.Request.ServerVariables.GetType();
MethodInfo[] methods = type.GetMethods(temp);
foreach(var method in methods)
{
switch( method.Name)
{
case "MakeReadWrite":
makeReadWrite = method;
break;
case "MakeReadOnly":
makeReadOnly = method;
break;
case "AddStatic":
addStatic = method;
break;
}
}
makeReadWrite.Invoke(context.Request.ServerVariables, null);
string[] values = { "DaveVar", "hehehe" };
addStatic.Invoke(context.Request.ServerVariables, values);
makeReadOnly.Invoke(context.Request.ServerVariables, null);
Which seems to set them correctly; however, when I try to read them from my classic asp page they do not appear...
CLASSIC ASP:
<html>
<%
for each x in Request.ServerVariables
response.write("<h2>"& x & "</h2>")
next
%>
<h2>hello!</h2>
</html>
ASP.NET ASPX Page where they do appear:
<%# Page Language="C#"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<div>
<%
foreach (var x in Request.ServerVariables)
{
%>
<div>
<%= x.ToString() %>
</div>
<%
}
%>
</div>
</form>
</body>
</html>
full http module:
namespace PlatoModules
{
public class PlatoModule : IHttpModule
{
public void Init(HttpApplication context)
{
context.BeginRequest += (s, e) => BeginRequest(s, e);
context.EndRequest += (s, e) => EndRequest(s, e);
}
public String ModuleName
{
get { return "test"; }
}
public void Dispose()
{
}
private void BeginRequest(Object source,
EventArgs e)
{
HttpApplication application = (HttpApplication)source;
HttpContext context = application.Context;
try
{
System.Diagnostics.Debugger.Launch();
// Create HttpApplication and HttpContext objects to access
// request and response properties.
string filePath = context.Request.FilePath;
string fileExtension =
VirtualPathUtility.GetExtension(filePath);
/* if (fileExtension.Equals(".aspx"))
{
context.Response.Write("<h1><font color=red>" +
"HelloWorldModule: Beginning of Request" +
"</font></h1><hr>");
}*/
BlackMagicSetServerVariables(application);
if (fileExtension.Equals(".asp"))
{
string content = #"<h1><font color=red>" +
"BeginReq" +
#"</font></h1><br>";
context.Response.Write(content);
context.Response.Flush();
}
}
catch (Exception ex)
{
context.Response.Write(#"<h1><font color=red>" +
"error" + ex.Message +
#"</font></h1><br>");
}
}
private void EndRequest(Object source, EventArgs e)
{
HttpApplication application = (HttpApplication)source;
HttpContext context = application.Context;
context.Response.Write(#"<br><h1><font color=red>" +
#"Enter endreq </font></h1>");
string filePath = context.Request.FilePath;
string fileExtension =
VirtualPathUtility.GetExtension(filePath);
if (fileExtension.Equals(".asp"))
{
context.Response.Write(#"<br><h1><font color=red>" +
#"EndReq </font></h1>");
}
context.Response.Flush();
}
void BlackMagicSetServerVariables(HttpApplication app)
{
BindingFlags temp = BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.Static;
var context = app.Context;
MethodInfo addStatic = null;
MethodInfo makeReadOnly = null;
MethodInfo makeReadWrite = null;
Type type = app.Request.ServerVariables.GetType();
MethodInfo[] methods = type.GetMethods(temp);
foreach(var method in methods)
{
switch( method.Name)
{
case "MakeReadWrite":
makeReadWrite = method;
break;
case "MakeReadOnly":
makeReadOnly = method;
break;
case "AddStatic":
addStatic = method;
break;
}
}
makeReadWrite.Invoke(context.Request.ServerVariables, null);
string[] values = { "DaveVar", "hehehe" };
addStatic.Invoke(context.Request.ServerVariables, values);
makeReadOnly.Invoke(context.Request.ServerVariables, null);
}
}
}
<%
for each x in Request.ServerVariables
response.write(x & "<br />")
next
%>
The code sample you have for listing all server variables in Classic ASP is broken.
It only gives you a list of all the available variables, but not their values.
Try this:
<%
for each x in Request.ServerVariables
response.write(x & " = " & Request.ServerVariables(x) & "<br />")
next
%>
Solution ...
Tentatively -
I cannot modify server variables and have them be 'picked up' by the classic asp code on the request; however I could get this code add in headers, so I'm going to use headers. If this is an awful way to be doing things please let me know in the comments! Thanks for helping me out Frank!
SO here's the code:
CLASSIC ASP:
<%
for each x in Request.ServerVariables
Response.Write("<h2>"& x & ":" & Request.ServerVariables(x) & "</h2>")
next
Response.Write("<h2> DAVE: " & Request.ServerVariables("HTTP_DAVE") & "</h2>")
Response.Flush()
%>
<h2>hello!</h2>
</html>
HTTPMODULE:
namespace PlatoModules
{
public class PlatoModule : IHttpModule
{
public void Init(HttpApplication context)
{
context.BeginRequest += (s, e) => BeginRequest(s, e);
context.EndRequest += (s, e) => EndRequest(s, e);
}
public String ModuleName
{
get { return "test"; }
}
public void Dispose()
{
}
// Your BeginRequest event handler.
private void BeginRequest(Object source, EventArgs e)
{
Debugger.Launch();
HttpApplication application = (HttpApplication)source;
HttpContext context = application.Context;
try
{
context.Response.Write(
"<h1><font color=red>HelloWorldModule: Beginning of Request</font></h1><hr>");
context.Request.Headers.Add("DAVE", "DAVOLIO");
context.Response.Flush();
}
catch (Exception ex)
{
context.Response.Write(
ex.Message);
}
}
private void EndRequest(object source, EventArgs e)
{
HttpApplication application = (HttpApplication)source;
HttpContext context = application.Context;
var content = #"<hr><h1><font color=red>HelloWorldModule: End of Request</font></h1>";
context.Response.Write(content);
context.Response.Flush();
}
}
}
Relevent web.config
<system.webServer>
<modules runAllManagedModulesForAllRequests="true">
<add name="PlatoModule" type="PlatoModules.PlatoModule" />
</modules>
...
</system.webserver>

Resources