ASPX c# attempt - asp.net

This fun.aspx page gives me errors:
I want to code in APSX like as in PHP
<%# Page Language="C#"%>
<html>
<body>
<%
int add1(int i) {
return 1+i;
}
int x = 555;
try {
Response.Write(add1(5));
throw new Exception("error here1<br>\n");
} catch(Exception ex) {
Response.Write("error detected");
}
%>
<h3>Lower</h3>
</body>
</html>

You still to use runat=server.
<%# Page Language="C#"%>
<script runat=server>
protected int add1(int i)
{
return 1+i;
}
</script>
<html>
<body>
<form id="form1" runat="server">
<% { Response.Write(add1(5)); } %>
</form>
</body>
</html>

Joel's comments are very helpful. To do things the ASP.NET way, you should take a look at the ASP.NET website tutorials. Get to know just the basics of Web Forms and MVC because sooner or later you might have to opt for one over the other. I think at this stage, MVC would be a better time investment for you going forward as it will bring you to a closer understanding of HTTP and how the Web works.
With Web Forms, as with MVC, we should really aim to keep the code separate from the ASPX markup. Microsoft is pushing this in the Core version of MVC going forward with the use of MVC Razor Pages.
In the spirit of keeping presentation and functionality separate with Web Forms, you really should be using the code-behind file for the logic:
ASPX:
<asp:Label ID="totalLabel" runat="server"></asp:Label>
CS:
public partial class Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
int x = 555;
totalLabel.Text = AddInteger(x);
}
protected int AddInteger(int i)
{
return 1+i;
}
}

Related

CSRF markup fix

I have a fortify result saying that the following line needs a secret to prevent CSRF
<form id ="form1test1" runat="server">
I have a random GUID being generated on Page Load, I want to compare it, when the form posts.
I have seen in classic asp putting the token in the action as a query string
I am trying:
<form "form1test1" runat="server"
action='<%# string.Concat(Eval("login.aspx/?Token="),"",Eval(Session["Token"].ToString()))%> '> >
Best I get is a print out of the text but not the values, not doing this in the code behind does not fix the finding in fortify
trying for something like
<form "form1test1" runat="server" action="login.aspx/?Token=12345DEF">
A better way to prevent CSRF attacks (it's working on my projects), is to implement it in your master pages, like this:
Add new Class that will handle the CSRF Validations for you:
public class CsrfHandler
{
public static void Validate(Page page, HiddenField forgeryToken)
{
if (!page.IsPostBack)
{
Guid antiforgeryToken = Guid.NewGuid();
page.Session["AntiforgeryToken"] = antiforgeryToken;
antiforgery.Value = antiforgeryToken.ToString();
}
else
{
Guid stored = (Guid)page.Session["AntiforgeryToken"];
Guid sent = new Guid(antiforgery.Value);
if (sent != stored)
{
// you can throw an exception, in my case I'm just logging the user out
page.Session.Abandon();
page.Response.Redirect("~/Default.aspx");
}
}
}
}
Then implement this in your master pages:
MyMasterPage.Master.cs:
protected void Page_Load(object sender, EventArgs e)
{
CsrfHandler.Validate(this.Page, forgeryToken);
...
}
MyMaster.Master:
<form id="form1" runat="server">
<asp:ScriptManager ID="ScriptManager1" runat="server"></asp:ScriptManager>
<asp:HiddenField ID="forgeryToken" runat="server"/>
...
</form>
Hope you'll find this useful.

Add a HtmlGenericControl to master page from server code

I'm creating a website which allows users to log in. After logging in successfully, user's name should be displayed across each page, for example, at the top right corner. I have a ContentPlaceHolder on Master Page. An h3 tag would then be created and added into this ContentPlaceHolder.
Master Page:
<asp:ContentPlaceHolder runat="server" ID="UserNamePlaceHolder">
</asp:ContentPlaceHolder>
Login Page:
<%# MasterType VirtualPath="~/Master" %>
Login Class:
protected void Login_LoggedIn(object sender, EventArgs e)
{
ContentPlaceHolder userNamePlaceHolder =
(ContentPlaceHolder)Master.FindControl("UserNamePlaceHolder");
var h3 = new HtmlGenericControl("h3");
h3.InnerHtml = login.UserName;
userNamePlaceHolder.Controls.Add(h3);
}
I did debugging step by step. Nothing went wrong: no null or empty value, each variable was created. However, the user name was not displayed at all. Does anyone have an idea?
A cleaner and better approach would be to create a public property on the Master page:
public string UserName
{
get
{
return Literal1.Text;
}
set
{
Literal1.Text = value;
}
}
That's it place the literal with ID Literal1 anywhere you want on the master page:
<asp:Literal runat="server" ID="Literal1" />
You are already adding Master directive for strongly typing Master class, so now your login class would look like this:
protected void Login_LoggedIn(object sender, EventArgs e)
{
Master.UserName = login.UserName;
userNamePlaceHolder.Controls.Add(h3);
}
Hope this helps.

passing variable from aspx JScript code behind to markup aspx file

I can't find a way to pass a variable declared in my code-behind aspx.js file to the corresponding code-behind.aspx markup file. The error I keep getting is this:
Parser Error Message: Code blocks are not allowed in this file.
My Code-Behind.aspx.js looks like this:
import System;
package Test {
class CodeBehind extends System.Web.UI.Page {
public var my_var;
public function Page_Load(sender, E:System.EventArgs) {
my_var = "This is my_var.";
}
}
}
I compile the code-behind file manually like this:
jsc.exe /t:library /out:bin\codebehind.dll codebehind.aspx.js
The Code-Behind.aspx looks like this:
<%# Page Language="JScript" Inherits="Test.CodeBehind" CompilationMode="Never" %>
<HTML>
<HEAD>
<TITLE>Hello World Test</TITLE>
</HEAD>
<BODY STYLE="font-size:12;font-family:arial,verdana,sans-serif;">
<FORM RUNAT="server">
<%= my_var %>
</FORM>
</BODY>
</HTML>
I know there are ASP.NET server controls such as asp:label and all that stuff but all I want is print out the contents of simple variables which serve as placeholders.
I don't want the website to compile everytime it is requested and I would like to keep the CompilationMode option set to "Never" and compile all code manually if possible.
Thanks!
Codebehind
protected string my_var { get; set; }
protected void Page_Load(object sender, EventArgs e)
{
my_var = "Hello";
}
html
<%= my_var %>

Creating website template which is independent from source code in asp.net webforms

Im working on an e-commerce platform which supports multiple stores on different domains. The backend is complete (for now) and I'm now starting the front-end part. Since the platform supports multiple stores I need some kind of templating system and I haven't quite figured out what's the best way to do this.
This are my requirements:
I don't want to rebuild my solution to add a new template
Templates are stored in /Templates/TemplateDirectoryName
I want to be able to use (predefined) usercontrols inside the templates.
I use URL routing and only have 1 Default.aspx page which controls which page template and additional code needs to be loaded.
This is what I came up with so far:
In my template directory i have templates created with master pages (A homepage master file, a default master file, and sub-master files referencing the default master file...for product detail, browse, search etc)
My Default.aspx page picks the right template based on routing values
While this way works I don't think it's very practical but the more I think about it the more I come to the conclusion that there are not so many other options to go around this. I think this is what I want to ask: Is there a way to use usercontrols in a template and have the template completely seperated from the application so users can create templates without having to worry about the site's namespace and structure?
Kind regards,
Mark
Since you are referencing a folder for templates, wouldn't it be possible to just change the .aspx files in the folder and asp.net shall pick up the template based on the url path that you've mentioned? I think that is possible in asp.net.
Also, Frameworks like DotNetNuke, Sharepoint, Joomla etc. have the similar concept. You can avail their features.
My proposed solution is below. It has a few constraints, like all master pages need to implement the same set of placeholder controls (not surprising). Take a look and let me know what you think.
I setup my folder structure like this:
Website -> Templates -> TemplateFolder (named same as the template)
Website -> Templates -> UserControls (User controls are stored in a non-template specific folder)
I defined a simple Template configuration class which we can store/save/load a basic template deffinition:
public class Template
{
public string TemplateName { get; set; }
public string UserControlName { get; set; }
public string MasterPageName { get; set; }
public string TemplateFolder
{
get
{
return GetTemplateFolder(TemplateName);
}
}
public string TemplateConfigFile { get { return GetTemplateConfigFile(TemplateName); } }
private static string GetTemplateFolder(string name)
{
return HttpContext.Current.Server.MapPath("~/Templates/" + name + "/");
}
private static string GetTemplateConfigFile(string name)
{
return GetTemplateFolder(name) + "/" + name + ".config";
}
public Template()
{
}
public void Save()
{
XmlSerializer xs = new XmlSerializer(typeof(Template));
if (!Directory.Exists(TemplateFolder)) Directory.CreateDirectory(TemplateFolder);
using (FileStream fs = File.OpenWrite(TemplateConfigFile))
{
xs.Serialize(fs, this);
}
}
public static Template Load(string name)
{
if(!File.Exists(GetTemplateConfigFile(name))) return null;
XmlSerializer xs = new XmlSerializer(typeof(Template));
using (FileStream fs = File.OpenRead(GetTemplateConfigFile(name)))
{
Template t = (Template)xs.Deserialize(fs);
return t;
}
}
}
You can build some bare xml code to get started with by running the code below:
Template t1 = new Template() { TemplateName = "Template1", MasterPageName = "Child1.master", UserControlName = "uc1.ascx" };
Template t2 = new Template() { TemplateName = "Template2", MasterPageName = "Child2.master", UserControlName = "uc2.ascx" };
t1.Save();
t2.Save();
I created a basic master page. This page will probably never be used except to give your default page the basic placeholders. All of your master pages should have the same set of placeholders as your base one so that your pages can use them all interchangably. Notice I left a placeholder for our user control.
<%# Master Language="C#" AutoEventWireup="true" CodeFile="BaseMaster.master.cs" Inherits="Templates_Masters_BaseMaster" %>
<!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>
<asp:ContentPlaceHolder id="head" runat="server">
</asp:ContentPlaceHolder>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:ContentPlaceHolder id="cphHeader" runat="server">
</asp:ContentPlaceHolder>
<asp:ContentPlaceHolder id="cpUserControl" runat="server">
</asp:ContentPlaceHolder>
<asp:ContentPlaceHolder id="cphFooter" runat="server">
</asp:ContentPlaceHolder>
</div>
</form>
</body>
</html>
Now I create a basic aspx web page that uses the above master page.
<%# Page Title="" Language="C#" MasterPageFile="~/Templates/Masters/BaseMaster.master" AutoEventWireup="true" CodeFile="DefaultTemplated.aspx.cs" Inherits="DefaultTemplated" %>
<asp:Content ID="Content1" ContentPlaceHolderID="head" Runat="Server">
</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="cphHeader" Runat="Server">
</asp:Content>
<asp:Content ID="Content3" ContentPlaceHolderID="cpUserControl" Runat="Server">
</asp:Content>
<asp:Content ID="Content4" ContentPlaceHolderID="cphFooter" Runat="Server">
</asp:Content>
In the codebehind we'll setup the basic templating. This sets the masterpage and adds a pre-defined user control to the content placeholder for user controls. If you wanted you could just make a panel or something and add it to that fixed control, but I thought you might appreciate seeing how to make it work with masterpages.
public partial class DefaultTemplated : System.Web.UI.Page
{
private Template PageTemplate
{
get
{
if (_tLoaded == null)
{
string template = Request.QueryString["template"];
if (string.IsNullOrEmpty(template)) return null;
Template t = Template.Load(template);
_tLoaded = t;
}
return _tLoaded;
}
}
private Template _tLoaded = null;
protected void Page_Load(object sender, EventArgs e)
{
if (PageTemplate != null)
{
//cpUserControl is the name of my usercontrol placeholder
((ContentPlaceHolder)Page.Form.FindControl("cpUserControl")).Controls.Add(
Page.LoadControl("~/Templates/UserControls/" + PageTemplate.UserControlName));
}
}
protected void Page_PreInit(object sender, EventArgs e)
{
if (PageTemplate == null) return;
this.MasterPageFile = "~/Templates/" + PageTemplate.TemplateName + "/" + PageTemplate.MasterPageName;
}
}
If you had a template named "Template1" you could use it by calling "Default.aspx?template=Template1". Since you are using URL rewriting you would use the rewriting to pass the template name as a parameter to the page.
Another option that could be combined with the above would be the use of Page.ParseControl. Using this you could store your raw asp.net designer code (designer only) in a database or raw text file. Then you could instantiate it load it like this:
//where pnl1 is a Panel on the page. Page.ParseControl just returns a control object, so use it anywhere.
pnl1.Controls.Add(Page.ParseControl("raw asp.net designer code here."));
One great thing about this is that nested controls work great too.
I don't know if I understand correctly:
If you don't want to rebuild, then I can tell a CMS concept is best suitable for you.
You can store your templates as an HTML in database and from DB you can fetch it back,
You can give an admin functionality with editor to edit your template online also.

ASP.NET :Show background process status to User

I have a web page where it will input an excel/CSV file from the user and read the data from it and import to DB.While inserting each record.I just want to show the details about the record being inserted to the user.(Ex : Client Details of A is adding...)
Try this... Set the output to unbuffered (Response.BufferOutput), and include some javascript in your page that updates the UI as you see appropriate. For example, it might update a SPAN with a percentage complete or the details of the record you are processing. Then in your server code, output <script> tags that call the Javascript function from the Render override. Make sure you call Flush() at the appropriate times, and also Flush the base code after it Renders... The JS function calls should get sent down at the appropriate times and executed on the client, resulting in an updating page.
For example... Your HTML page might look like this:
<%# Page Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="WebApplication1._Default" %>
<!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 type="text/javascript">
function UpdateScreen(t) {
document.getElementById('output').innerHTML = t;
}
</script>
</head>
<body>
<form id="form1" runat="server">
<div>
<div id='output'></div>
</div>
</form>
</body>
</html>
<script type="text/javascript">
UpdateScreen('hello');
</script>
and your codebehind will look like this:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Threading;
namespace WebApplication1
{
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected override void Render(HtmlTextWriter writer)
{
Response.BufferOutput = false;
base.Render(writer);
Response.Flush();
for (int i = 0; i < 10; i++)
{
Thread.Sleep(1000);
Response.Write(string.Format("<script type='text/javascript'>UpdateScreen('{0}');</script>", i * 10));
Response.Flush();
}
}
}
}
I know this is an old question, and the owner of it may have moved on a long time ago. Anyway:
The proposed solution will not work on ASP.NET MVC. And if you ask me, which you don't, I'll say this is not the cleanest solution to the problem:
Here's a jQuery one,
And here's an IFrame one.

Resources