500 internal server error on hidden __viewstate of asp.net page - c#

I am trying to post the data to cross domain. It works fine if the form is not using runat="server" and its giving 500 internal error while posting when the form is using runat="server".
Upon debugging, I identified that the problem is with auto generated __viewstate code on the page. Please find the below code.
Clientside HTML implementation:
<%# Page Language="C#" CodeFile="Sample.aspx.cs" Inherits="Sample" %>
<!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>
<meta charset="utf-8">
<title>Untitled Page</title>
<link href="FileUpload.css" rel="stylesheet" type="text/css" />
<script id="template-upload" type="text/x-tmpl">
</script>
<script id="template-download" type="text/x-tmpl">
</script>
<script src="../../test/FileUpload/jQueryv1.6.2.js"></script>
<script src="fileupload-js/jquery.ui.widget.js"></script>
<script src="fileupload-js/tmpl.min.js"></script>
<script src="fileupload-js/jquery.fileupload.js"></script>
<script src="fileupload-js/jquery.fileupload-ui.js"></script>
<script src="fileupload-js/locale.js"></script>
<script src="fileupload-js/main.js"></script>
</head>
<body>
<form id="fileupload" method="POST" runat="server">
<CCAB.Web:FileUpload runat="server"/>
</form>
</body>
</html>
Serverside code:
public partial class SaveFile : System.Web.UI.Page
{
private void Page_Load(object sender, System.EventArgs e)
{
Response.AddHeader("Access-Control-Allow-Origin", "*")
if (Request.HttpMethod == "GET" || Request.HttpMethod == "HEAD")
{
Response.Write("GET Success");
}
else
{
for (int i = 0; i < Request.Files.Count; i++)
{
string filename = Request.Files[i].FileName;
Request.Files[i].SaveAs(#"\\dev2\\share$\\Anna\\test\\" + filename);
Response.Write(filename);
Response.Write("Success");
}
}
}
}
Could you please help me in how to ignore the hidden viewstate code from client side or ignore the response viewstate in server side.
Many Thanks
Anna

Try disabling view state by adding a line of code to your unload handler:
Page.EnableViewState = false;
see this MSDN page

I have found the solution for this problem. Please find below
public class BasePage : Page
{
private static string[] aspNetFormElements = new string[]
{
"__EVENTTARGET",
"__EVENTARGUMENT",
"__VIEWSTATE",
"__EVENTVALIDATION",
"__VIEWSTATEENCRYPTED",
};
protected override void Render(HtmlTextWriter writer)
{
StringWriter stringWriter = new StringWriter();
HtmlTextWriter htmlWriter = new HtmlTextWriter(stringWriter);
base.Render(htmlWriter);
string html = stringWriter.ToString();
int formStart = html.IndexOf("<form");
int endForm = -1;
if (formStart >= 0)
endForm = html.IndexOf(">", formStart);
if (endForm >= 0)
{
StringBuilder viewStateBuilder = new StringBuilder();
foreach (string element in aspNetFormElements)
{
int startPoint = html.IndexOf("<input type=\"hidden\" name=\"" + element + "\"");
if (startPoint >= 0 && startPoint > endForm)
{
int endPoint = html.IndexOf("/>", startPoint);
if (endPoint >= 0)
{
endPoint += 2;
string viewStateInput = html.Substring(startPoint, endPoint - startPoint);
html = html.Remove(startPoint, endPoint - startPoint);
viewStateBuilder.Append(viewStateInput).Append("\r\n");
}
}
}
if (viewStateBuilder.Length > 0)
{
viewStateBuilder.Insert(0, "\r\n");
html = html.Insert(endForm + 1, viewStateBuilder.ToString());
}
}
writer.Write(html);
}
}
Please find more info on this page : http://blogs.msdn.com/b/tom/archive/2008/03/14/validation-of-viewstate-mac-failed-error.aspx
Many Thanks
Anna

Related

How can I create and display a PDF file for a .net core MVC web application?

I have an asp application that has the ability to create and display PDF files. I need to copy the same functionality for a .net core application. I'm not too experienced in .net core MVC, so I don't know how this can be accomplished.
DisplayPDF.aspx.cs
public partial class DisplayPDF : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
// get application id from query string
string strFile = Request.QueryString["File"];
if (!string.IsNullOrEmpty(strFile))
{
string fileToOpen = string.Empty;
// get file path to requested application id's pdf file
string filePath = System.IO.Path.GetDirectoryName(Request.PhysicalApplicationPath) +
"\\Sessions\\" + Session.SessionID + "\\" + strFile;
fileToOpen = "sessions/" + Session.SessionID + "/" + strFile;
if (!System.IO.File.Exists(filePath))
{
LabelError.Visible = true;
LabelError.Text = "The pdf was not generated. Try the action again. If the problem persists contact website support.";
}
Response.Redirect(fileToOpen);
}
else
{
// need to have query string parameter
throw new ApplicationException("Query string parameter is missing");
}
}
}
DisplayPDF.aspx
<%# Page Language="C#" AutoEventWireup="true" CodeBehind="DisplayPDF.aspx.cs" Inherits="Test.WS.App.DisplayPDF" %>
<!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 id="Head1" runat="server">
<title>Display PDF</title>
<meta name="robots" content="noindex,nofollow" />
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:Label ID="LabelError" runat="server" Visible="false"></asp:Label>
</div>
</form>
</body>
</html>
Redirecting to the DisplayPDF page
if(System.IO.File.Exists(filePath)){
ScriptManager.RegisterClientScriptBlock(
Page,
Page.GetType(),
"ShowPDF",
"window.open('DisplayPDF.aspx?file=" + System.IO.GetFileName(filePath) + "?dt=" + DateTime.Now.Ticks.ToString() + "');",
true);
}
else
{
MessageBox.Show("Report was not generated.");
}
Based on this webform code , you can display pdf in core mvc as follows:
Note that my pdf files are placed under the 'wwwroot' folder of the core
project.
DisplayPDFController.cs:
public class DisplayPDFController : Controller
{
private IWebHostEnvironment _hostingEnvironment;
public DisplayPDFController(IWebHostEnvironment environment)
{
_hostingEnvironment = environment;
}
public IActionResult Index()
{
return View();
}
[HttpPost]
public string Index(string fileName)
{
string filePath = Path.Combine(_hostingEnvironment.WebRootPath, #"Files\" + fileName);
if (System.IO.File.Exists(filePath))
{
return filePath;
}
else
{
return "Report was not generated.";
}
}
public FileResult ShowPDF(string path)
{
var fileStream = new FileStream(path, FileMode.OpenOrCreate, FileAccess.Read);
return File(fileStream, "application/pdf");
}
}
Index.cshtml view:
#{
Layout = null;
}
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width" />
<title>Index</title>
<script src="~/lib/jquery/dist/jquery.js"></script>
<script>
$(function () {
$("#show").click(function () {
event.preventDefault();
$.ajax({
type: 'POST',
data: { fileName: $("#Text1").val() },
url: "/DisplayPDF/Index",
success: function (response) {
if (response == 'Report was not generated.') {
alert(response);
} else {
window.open("/DisplayPDF/ShowPDF?path=" + response, "_blank");
}
},
});
})
})
</script>
</head>
<body>
<form>
<input id="Text1" type="text" placeholder="FileName" />
<input id="show" type="submit" value="show pdf" />
</form>
</body>
</html>

How to replace a placeholder with a control in code behind?

I want to enable my users to create templates with placeholders like ##CreateLink## which should be replaced in code-behind by controls.
I know how to create controls in runtime but I have no idea how to replace the placeholder with these dynamically created controls.
How can I achieve this?
This is my .aspx code
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
<title></title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:Literal ID="lit" runat="server" Text="This is my sample text. Here is my ##token## which should be replaced by my control in codebehind..."></asp:Literal>
</div>
</form>
</body>
</html>
And this is my codebehind:
public partial class WebForm1 : System.Web.UI.Page
{
private HyperLink lnk;
protected override void CreateChildControls()
{
base.CreateChildControls();
lnk = new HyperLink();
lnk.ID = "lnk";
lnk.NavigateUrl = "http://www.google.com";
}
protected void Page_Load(object sender, EventArgs e)
{
}
protected override void Render(HtmlTextWriter writer)
{
base.Render(writer);
}
}
Using another answer to guide me I worked out the following:
.aspx Markup
<%# Page Language="C#" AutoEventWireup="true" CodeBehind="WebForm1.aspx.cs" Inherits="WebApplication2.WebForm1" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
<title></title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:Literal ID="lit" runat="server" Text="This is my sample text. Here is my ##token## and my button ##button## which should be replaced by my control in codebehind..."></asp:Literal>
<p>this is a default button</p>
<asp:Button ID="btn2" runat="server" text="from asp.net" />
</div>
</form>
</body>
</html>
C# CodeBehind code
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
namespace WebApplication2
{
public partial class WebForm1 : System.Web.UI.Page
{
private HyperLink lnk;
private Button btn;
protected override void CreateChildControls()
{
base.CreateChildControls();
lnk = new HyperLink();
lnk.ID = "lnk";
lnk.Text = "<b>Sample Link</b>";
lnk.NavigateUrl = "http://www.google.com";
btn = new Button();
btn.ID = "btn";
btn.Text = "button text";
}
protected void Page_Load(object sender, EventArgs e)
{
}
protected override void Render(HtmlTextWriter writer)
{
StringBuilder sb = new StringBuilder();
HtmlTextWriter myWriter = new HtmlTextWriter(new System.IO.StringWriter(sb, System.Globalization.CultureInfo.InvariantCulture));
base.Render(myWriter);
myWriter.Flush();
string renderedHtml = sb.ToString();
renderedHtml = renderedHtml.Replace("##token##", RenderHTML(lnk));
renderedHtml = renderedHtml.Replace("##button##", RenderHTML(btn));
writer.Write(renderedHtml);
myWriter.Close();
sb.Clear();
}
private string RenderHTML(Control ctrl)
{
StringBuilder sb = new StringBuilder();
HtmlTextWriter myWriter = new HtmlTextWriter(new System.IO.StringWriter(sb, System.Globalization.CultureInfo.InvariantCulture));
ctrl.RenderControl(myWriter);
myWriter.Close();
return sb.ToString();
}
}
}
Use Render method
protected override void Render(HtmlTextWriter writer)
{
//Place replace logic
}
Update
protected override void Render(HtmlTextWriter writer)
{
MemoryStream stream = new MemoryStream();
StreamWriter memWriter = new StreamWriter(stream);
HtmlTextWriter myWriter = new HtmlTextWriter(memWriter);
base.Render(myWriter);
myWriter.Flush();
stream.Position = 0;
string renderedHtml = new StreamReader(stream).ReadToEnd();
renderedHtml = renderedHtml.Replace("##token##", "VALUE");
writer.Write(renderedHtml);
writer.Close();
myWriter.Close();
stream.Close();
}

Dynamically adding images using UpdatePanel

I'm trying to dynamically create images in a table but it seems like the UpdatePanel is not updating. I have the following code in my .aspx page.
<%# Page Language="C#" AutoEventWireup="true" CodeFile="ViewTile.aspx.cs" Inherits="ViewTile" %>
<!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 runat="server">
<form id="form1" runat="server">
<div>
<asp:Image ID="tileImg" runat="server"/>
<asp:ScriptManager ID="ScriptManager1" runat="server"/>
<table>
<asp:updatePanel ID="UpdatePanel1" runat="server">
<ContentTemplate>
<asp:PlaceHolder runat="server" ID="placeholder1"/>
</ContentTemplate>
</asp:updatePanel>
</table>
</div>
</form>
</body>
</html>
And then this this the aspx.cs page.
TableRow imageRow = new TableRow();
for (int rowItr = 0; rowItr < 3; rowItr++)
{
for (int colItr = 0; colItr < 4; colItr++)
{
System.Web.UI.WebControls.Image image = new System.Web.UI.WebControls.Image();
image.ImageUrl = "~/ShowTile.ashx?SheetId=" + SheetGUID + "&Scale=" + 3
+ "&XCoord=" + colItr + "&YCoord=" + rowItr;
placeholder1.Controls.Add(image);
TableCell imageCell = new TableCell();
imageCell.Controls.Add(image);
imageRow.Cells.Add(imageCell);
}
placeholder1.Controls.Add(imageRow);
imageRow.Cells.Clear();
}
I know for a fact that the image is being called correctly as I've outputted it manually using an image tag on the client. Any help would be great! Thanks
You need to add Table first, add rows to it and finally add table to placeholder1.Controls
Table tbl= new Table();
for (int rowItr = 0; rowItr < 3; rowItr++)
{
TableRow imageRow = new TableRow();
for (int colItr = 0; colItr < 4; colItr++)
{
System.Web.UI.WebControls.Image image = new System.Web.UI.WebControls.Image();
image.ImageUrl = "~/ShowTile.ashx?SheetId=" + SheetGUID + "&Scale=" + 3
+ "&XCoord=" + colItr + "&YCoord=" + rowItr;
TableCell imageCell = new TableCell();
imageRow.Cells.Add(imageCell);
}
tbl.Rows.Add(imageRow);
}
placeholder1.Controls.Add(tbl);
You Can Do this using javascript and Web Service.
Create a function that Call Web Service and fetch url of the image and append it into the update panel div

Finding dynamically added server control and use it's HTML

I'm trying to get Text from a dynamically craeted server textbox.
I'm just checking by getting the text into another textbox I placed in the aspx file, but all I get is always an empty string..
(I also tried another method that is enclosed in remark, but it doesn't work either)
Here's the code behind:
public partial class Product_list : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
create_table();
}
protected void create_table()
{
DBServices db1=new DBServices();
List<Product> list1 = db1.ReadProducts();
int id_number=1;
int id_numer2 = 7;
int id_number3 = 13;
Table tbl = new Table();
tbl.ID = "tbl1";
this.Controls.Add(tbl);
foreach (Product p1 in list1)
{
TableRow rw = new TableRow();
rw.ID = Convert.ToString(id_numer2);
TableCell cell1 = new TableCell();
cell1.Text = p1.Name;
TableCell cell2 = new TableCell();
Image img = new Image();
img.ImageUrl = p1.ImagePath;
img.Height = 50;
img.Width = 50;
cell2.Controls.Add(img);
TableCell cell3 = new TableCell();
cell3.ID = Convert.ToString(id_number3);
TextBox textbox1 = new TextBox();
textbox1.ID = Convert.ToString(id_number);
cell3.Controls.Add(textbox1);
rw.Controls.Add(cell1);
rw.Controls.Add(cell2);
rw.Controls.Add(cell3);
tbl.Controls.Add(rw);
id_number++;
id_numer2++;
id_number3++;
}
}
void save_list()
{
List<Product> Items_list = new List<Product>();
//TextBox aControl =Page.FindControl("1") as TextBox;
/var tbl1 = this.Page.FindControl("tbl1") as Table;
var tr = tbl1.FindControl("7") as TableRow;
var td = tr.FindControl("13") as TableCell;
var txt = td.FindControl("1") as TextBox;
txt1.Value = txt.Text;
}
protected void Button1_Click(object sender, EventArgs e)
{
save_list();
}
}
and here is the aspx code:
<%# Page Language="C#" AutoEventWireup="true" CodeFile="Product_list.aspx.cs" Inherits="Product_list" %>
<!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>
<script runat=server>
public override void VerifyRenderingInServerForm(Control control)
{
}
</script>
</head>
<body>
<form id="form1" runat="server">
<div id="header">
<h1>Items List</h1>
</div>
<div id="prod_table" runat="server"></div>
<div>
<input type="text" runat="server" id="txt1" />
<asp:Button ID="Button1" runat="server" Text="Button"
onclick="Button1_Click" />
</div>
</form>
</body>
</html>
You should understand that you recreate your table on every post to the server. So, you cannot rely on data from your dynamic table, because it would be lost after each posting. My suggestion is to keep this value in permanent input control with a type "hidden". Then on button click event just get this value and assign it to a textbox.

Problems with JavaScript for multi-upload

I'm trying to make a multi-file upload. with help from this blog, but is getting an error.
the code:
<%# Page Language="C#" AutoEventWireup="true" CodeBehind="default.aspx.cs" Inherits="Upload_Multiple_Files._default" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
<script language="javascript" type="text/javascript">
var selectedFiles = '';
function ReceiveServerData(response) {
alert(response);
}
function uploadFile() {
var fileList = document.getElementById("fileDivBox").getElementsByTagName("INPUT");
for (i = 0; i < fileList.length; i++) {
selectedFiles += fileList[i].value + "|";
}
CallServer(selectedFiles, '');
}
function attachFile() {
var fu = document.createElement("INPUT");
fu.type = "file";
var br = document.createElement("<BR>");
document.getElementById("fileDivBox").appendChild(fu);
document.getElementById("fileDivBox").appendChild(br);
}
</script>
</head>
<body>
<form id="form1" runat="server">
<div>
Attach a file
</div>
</form>
</body>
</html>
codebehind:
namespace Upload_Multiple_Files
{
public partial class _default : System.Web.UI.Page
{
public void RaiseCallbackEvent(string eventArgument)
{
string[] files = (eventArgument.TrimEnd('|')).Split('|');
WebClient client = new WebClient();
foreach (string file in files)
{
client.UploadFile("http://localhost:3850/FileServer.aspx", "POST", file);
}
}
protected void Page_Load(object sender, EventArgs e)
{
string path = #"C:\UploadedFiles\"; // server folder
string[] keys = Request.Files.AllKeys;
foreach (String key in keys)
{
HttpPostedFile file = Request.Files[key];
file.SaveAs(path + file.FileName);
}
}
}
}
the error occours in the line: br = document.createElement("<BR>");
where it says "unhandled exeption". I'm new to javascript thereby having no clue was wrong.
The document.CreateElement function will add the < > part of the tag for you. What your code is attempting to do is create an element of <<br>>, which is invalid. Call the method with just the tag name of BR:
br = document.CreateElement("BR");
This will create a <br> tag for you as you expect.

Categories