I have to reload my page after I write some html, script to my page using Response.Write. After using Response.Write I am using Response.Flush(), followed by Response.End(). The code works properly in one server and when I deploy it to another server it is not working.
As far as I know the code execution must stop once it executes the Response.End, but it is now behaving in the desired way.
Response.ClearContent();
Response.Write("Write some html, script content here");
Response.Flush();
Response.End();
Using Respose.Redirect(Request.RawUrl) will not work and will throw an exception stating that the redirection cannot happen once the headers are posted...
Can some one tell me, why the code execution is not stopped by Response.End() ??
EDIT: Actual Code
protected void Page_Load(object sender, EventArgs e)
{
if (Session["localTime"] == null && String.IsNullOrEmpty(Request.Params["localTime"]))
{
// then clear the content and write some html, a javascript code which submits the local time
Response.ClearContent();
Response.Write(#"<form id='local' method='post' name='local'>
<input type='hidden' id='localTime' name='localTime' />
<script type='text/javascript'>
document.getElementById('localTime').value = new Date();
document.getElementById('local').submit();
</script>
</form>");
//
Response.Flush();
// end the response so PageLoad, PagePreRender etc won't be executed
Response.End();//Page must reload after this line.
}
else
{
// if the request contains the localtime, then save it in Session
if (Request.Params["localTime"] != null)
{
Session["localTime"] = Request.Params["localTime"];
Response.Write(Request.Params["localTime"] + " ~2");
// and redirect back to the original url
Response.Redirect(Request.RawUrl);
}
}
}
Related
I have this code in my page:
protected void btn_add_Click(object sender, EventArgs e)
{
Session["truck_id"] = truck_id;
Session["user_id"] = user_id;
Session["usertype"] = usertype;
if (usertype == "viewer")
{
Response.Write("Sorry, you do not have access to this page.");
Response.StatusCode = 401;
Response.End();
}
Response.Redirect("JobOrderForm.aspx");
}
I have logged in as viewer and the error message is this
How can I change it to Unauthorized Access?
Change this:
Response.Redirect("JobOrderForm.aspx");
To this:
Response.Redirect("/JobOrderForm.aspx");
/ refers to the root directory. This may help because probably this page and redirected page is not in the same folder.
You have an error on your page. Have you tried debugging it? Set a breakpoint on the first line in the btn_add_Click method and step through to see which line is causing the error.
I created an asp.net site for downloading documents. I handle this with Page.Response.
try {
...
EndpointAddress endPoint = new EndpointAddress("xxxxx.svc");
FileServiceClient fileServiceProxy = new FileServiceClient(binding, endPoint);
// WCF WebService call
Stream stream = fileServiceProxy.GetFileStream(filePath);
Page.Response.ContentType = "application/pdf";
Page.Response.AddHeader("Content-Disposition",string.Format ("attachment; fileName=\"{0}\"", Path.GetFileName(filePath)));
Page.Response.AddHeader("Accept-Ranges", "bytes");
if (buffer != null){
Page.Response.BinaryWrite(buffer);
}
Page.Response.Flush();
}
catch (Exception e)
{
Page.Response.Clear();
Page.Response.ClearContent();
Page.Response.ClearHeaders();
}
finally
{
Page.Response.End();
}
And while the file is loading from a webservice I want to display a hourglass cursor. Showing loading cursor is working.
protected void Page_Load(object sender, EventArgs e)
{
btnDownload.Attributes.Add("onclick", "document.body.style.cursor = 'wait';");
}
But I can't change it back to normal cursor. I think because I don't fire a post back or don't reload the site.
What can I do to set default cursor if buttonClick event is over without site reload!?
Update: Updated the code with the wcf webservice call. I call the webservice with file path and get a stream back which I write to Page.Response.BinaryWriter
# Frédéric Hamidi THX for the link. I change my approach and display a jquery waiting dialog until file transfer is finished.
File download dialog
<%--Confirmation Box--%>
<script type="text/javascript" language="javascript">
function alertbox() {
if (confirm("Are you sure?") == true)
{
document.getElementById('<%= hdnYesNo.ClientID %>').value = "YES";
}
else
{
document.getElementById('<%= hdnYesNo.ClientID %>').value = "NO";
}
}
</script>
How to rewrite this code in C# as codebehind? I would like have a confirm box with yes or no buttons.
protected void Page_Load(object sender, System.EventArgs e)
{
string csName = "PopupScript";
Type csType = this.GetType();
ClientScriptManager csm = Page.ClientScript;
if (!csm.IsStartupScriptRegistered(csType, csName)) {
StringBuilder sb = new StringBuilder();
sb.Append("<script>");
sb.Append("function alertbox() {");
sb.Append("if (confirm('Are you sure?') == true) ");
sb.Append("{");
sb.Append("document.getElementById('" + hdnYesNo.ClientID + "').value = 'YES';");
sb.Append("}");
sb.Append("else");
sb.Append("{");
sb.Append("document.getElementById('" + hdnYesNo.ClientID + "').value = 'NO';");
sb.Append("}");
sb.Append("</script>");
csm.RegisterStartupScript(csType, csName, sb.ToString());
}
}
you can use like this way
Page.ClientScript.RegisterStartupScript(this.GetType(), "Confi", "if(confirm('Are you sure?') == true){ document.getElementById('txtValue').value ='YES';}else{document.getElementById('txtValue').value ='NO';}", true);
You can use ClientScriptManager class and its methods, for example RegisterClientScriptBlock. Depends on when you want the javascript to execute.
See details here:
http://msdn.microsoft.com/en-us/library/System.Web.UI.ClientScriptManager_methods.aspx
You need javascript for this, it's not possible in code behind. Code behind is run on the server before the page is sent to the user, javascript is run on the user's computer.
If you want to get access to their answer in code behind (possible and straightforward), you can use ajax or you can postback.
If you want to have this popup to come up when you press on a .Net asp:button control, then you can put a javascript function in the "OnClientClick" attribute of the control.
EDIT: If you need help with any of the above, let us know and help will be provided :).
EDIT2: Due to the discussion below, I guess I should clarify: You can (obviously) construct javascript on the server side before passing it to the client, but the example you gave is NOT a case where you should be doing that (an example of where this might be a good idea would be a script that has variables read from a database or something similar that doesn't need to be dynamic between page loads).
another option is to create the script in the /View folder and user razor for generating the script.
then you could point to the page in the tag like
<script src="~/ScriptGenerator/MyScript" />
for pointing the controller ScriptGeneratorController that expose the action MyScript
I have a web application project to support file transfer operations to vendor product backend. It's composed of 2 HTTPHandler files compiled into a website on a Win2003 server with IIS 6.0:
UploadHandler.ashx
DownloadHandler.ashx
These files get "POSTed to" from a ColdFusion website that exposes the user interface. In a way, my job is done because these handlers work and have to be called from ColdFusion.
Yet, I am very frustrated with my inability to get my own "test UI" (default.aspx) to use in my testing/refinement independent of ColdFusion.
<asp:Button ID="DownloadButton" PostBackUrl="~/DownloadHandler.ashx" runat="server" Text="Download"/>
Using a PostBackUrl for Download works nicely - when the DownloadHandler.ashx is entered, it finds its key input value in context.Request.Form["txtRecordNumber"];
But I cannot use this technique for Upload because I have to do some processing (somehow read the bytes from the chosen fileupload1.postedfile into a FORM variable so my UploadHandler.ashx file can obtain its input from Request.Form as with Download).
My first approach tried using HTTPWebRequest which seemed overly complex and I could never get to work. Symptoms began with a HTTP 401 status code and then morphed into a 302 status code so I researched other ideas.
Here is my latest code snippet from my default.aspx:
protected void UploadHandlerButton_Click(object sender, EventArgs e)
{
if (FileUpload1.HasFile)
{
try
{
BuildFormData();
//Server.Transfer("UploadHandler.ashx", true);
Response.Redirect("~/UploadHandler.ashx");
}
catch (Exception someError)
{
LogText("FAILURE: " + someError.Message);
}
}
}
protected void BuildFormData()
{
BinaryReader b = new BinaryReader(FileUpload1.PostedFile.InputStream);
int numBytes = FileUpload1.PostedFile.ContentLength;
byte[] fileContent = b.ReadBytes(numBytes);
objBinaryData.Text = System.Text.Encoding.UTF8.GetString(fileContent);
b64fileName.Text = FileUpload1.PostedFile.FileName;
// create arbitrary MetaData in a string
strMetaData.Text = "recAuthorLoc=anyname1~udf:OPEAnalyst=anyname2~udf:Grant Number=0102030405";
}
Attempts to use Server.Transfer (above) to my .ashx file result in an error:
error executing child request for UploadHandler.ashx
Attempts to use Response.Redirect (above) to my .ashx file result in GET (not POST) and Trace.axd of course shows nothing in the Form collection so that seems wrong too.
I even tried clone-ing my .ashx file and created UploadPage.aspx (a webform with no HTML elements) and then tried:
Server.Transfer("UploadPage.aspx", true);
//Response.Redirect("~/UploadPage.aspx");
Neither of those allow me to see the form data I need to see in Request.Form within my code that processes the Upload request. I am clearly missing something here...thanks in advance for helping.
EDIT-UPDATE:
I think I can clarify my problem. When the UploadHandler.ashx is posted from ColdFusion, all of the input it needs is available in the FORM collection (e.g. Request.Form["fileData"] etc.)
But when I use this control it generates a postback to my launching web page (i.e. default.aspx). This enables me to refer to the content by means of FileUpload1.PostedFile as in:
protected void BuildFormData()
{
BinaryReader b = new BinaryReader(FileUpload1.PostedFile.InputStream);
int numBytes = FileUpload1.PostedFile.ContentLength;
byte[] fileContent = b.ReadBytes(numBytes);
objBinaryData.Text = System.Text.Encoding.UTF8.GetString(fileContent);
b64fileName.Text = FileUpload1.PostedFile.FileName;
}
Yet I am not using the FileUpload1.PostedFile.SaveAs method to save the file somewhere on my web server. I need to somehow - forgive the language here - "re-post" this data to an entirely different file - namely, my UploadHandler.ashx handler. All the goofy techniques I've tried above fail to accomplish what I need.
EDIT-UPDATE (20 Aug 2009) - my final SOLUTION using Javascript:
protected void UploadHandlerButton_Click(object sender, EventArgs e)
{
if (FileUpload1.HasFile)
{
try
{
ctlForm.Text = BuildFormData();
String strJS = InjectJS("_xclick");
ctlPostScript.Text = strJS;
}
catch (Exception someError)
{
LogText("FAILURE: " + someError.Message);
}
}
}
private String InjectJS(String strFormId)
{
StringBuilder strScript = new StringBuilder();
strScript.Append("<script language='javascript'>");
strScript.Append("var ctlForm1 = document.forms.namedItem('{0}');");
strScript.Append("ctlForm1.submit();");
strScript.Append("</script>");
return String.Format(strScript.ToString(), strFormId);
}
protected string BuildFormData()
{
BinaryReader b = new BinaryReader(FileUpload1.PostedFile.InputStream);
int numBytes = FileUpload1.PostedFile.ContentLength;
byte[] fileContent = b.ReadBytes(numBytes);
// Convert the binary input into Base64 UUEncoded output.
string base64String;
base64String =
System.Convert.ToBase64String(fileContent,
0,
fileContent.Length);
objBinaryData.Text = base64String;
b64fileName.Text = FileUpload1.PostedFile.FileName;
// create arbitrary MetaData in a string
strMetaData.Text = "recAuthorLoc=Patterson, Fred~udf:OPEAnalyst=Tiger Woods~udf:Grant Number=0102030405";
StringBuilder strForm = new StringBuilder();
strForm.Append("<form id=\"_xclick\" name=\"_xclick\" target=\"_self\" action=\"http://localhost/HTTPHandleTRIM/UploadHandler.ashx\" method=\"post\">");
strForm.Append("<input type=\"hidden\" name=\"strTrimURL\" value=\"{0}\" />");
strForm.Append("<input type=\"hidden\" name=\"objBinaryData\" value=\"{1}\" />");
strForm.Append("<input type=\"hidden\" name=\"b64fileName\" value=\"{2}\" />");
strForm.Append("<input type=\"hidden\" name=\"strDocument\" value=\"{3}\" />");
strForm.Append("<input type=\"hidden\" name=\"strMetaData\" value=\"{4}\" />");
strForm.Append("</form>");
return String.Format(strForm.ToString()
, txtTrimURL.Text
, objBinaryData.Text
, b64fileName.Text
, txtTrimRecordType.Text
, strMetaData.Text);
}
Sorry if I'm missing something, but can't you simply use a plain HTML form to upload files to your handler:
<form action="UploadHandler.ashx" method="post" enctype="multipart/form-data">
Choose file to upload:
<input name="file" type="file" size="50">
</form>
What worked for me was to inject a new FORM and some Javascript to submit the FORM to the UploadHandler.ashx. This (for me) was easier to grasp than the HTTPWebRequest technique.
John Galt,
The only way to do what you want is using HttpWebRequest.
Here is good example of a Class that do what you want. I've made to send image and form values to picassa serve sometime ago (I know I could use Picassa API, but I did it for fun).
You only need to pay attention to the 'SendPhoto' function to get hints on what you have to do to make HttpWebRequest to do the work.
I found a good way to check if a file exists and read the contents if it does, but for some reason I can't create a method out of it.
Here's what I have so far:
<script runat="server">
void Page_Load(Object s, EventArgs e) {
lblFunction.Text = mwbInclude("test.txt");
}
string mwbInclude(string fileName) {
string inc = Server.MapPath("/extra/include/" + Request["game"] + "/" + fileName);
string valinc;
if(System.IO.File.Exists(inc))
{
valinc = System.IO.File.ReadAllText(inc);
}
return valinc;
}
</script>
I wish I could provide more info, but the server this is on doesn't show any feedback on errors, just a 404 page.
I think
valinc = Response.Write(System.IO.File.ReadAllText(inc));
should be
valinc = System.IO.File.ReadAllText(inc);
Why are you setting the Text property and calling Response.Write? Do you want to render the text as a label, or as the whole response?
If you're getting a 404, it's because your page isn't being found, not because there's a problem with the script itself. Have you tried ripping out all of the code and just sticking in some HTML tags as a sanity check?