I am new to C#. Can not understand whats this error means:
I am just following simple examples from
http://csharp-video-tutorials.blogspot.com/2012/10/calling-stored-procedure-with-output.html
this is my .aspx file
<!DOCTYPE html>
<table style="border: 1px solid black; font-family:Arial">
<tr>
<td>
Employee Name
</td>
<td>
<asp:TextBox ID="txtEmployeeName" runat="server"></asp:TextBox>
</td>
</tr>
<tr>
<td>
Gender
</td>
<td>
<asp:DropDownList ID="ddlGender" runat="server">
<asp:ListItem>Male</asp:ListItem>
<asp:ListItem>Female</asp:ListItem>
</asp:DropDownList>
</td>
</tr>
<tr>
<td>
Salary
</td>
<td>
<asp:TextBox ID="txtSalary" runat="server"></asp:TextBox>
</td>
</tr>
<tr>
<td colspan="2">
<asp:Button ID="btnSubmit" runat="server" Text="Submit"
onclick="btnSubmit_Click" />
</td>
</tr>
<tr>
<td colspan="2">
<asp:Label ID="lblMessage" runat="server"></asp:Label>
</td>
</tr>
</table>
This is aspx.cs file
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data.SqlClient;
using System.Configuration;
namespace adoDemo
{
public partial class WebForm2 : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{ }
protected void btnSubmit_Click(object sender, EventArgs e)
{
//Read the connection string from Web.Config file
string ConnectionString = ConfigurationManager.ConnectionStrings["DBCS"].ConnectionString;
using (SqlConnection con = new SqlConnection(ConnectionString))
{
//Create the SqlCommand object
SqlCommand cmd = new SqlCommand("spAddEmployee", con);
//Specify that the SqlCommand is a stored procedure
cmd.CommandType = System.Data.CommandType.StoredProcedure;
//Add the input parameters to the command object
cmd.Parameters.AddWithValue("#Name", txtEmployeeName.Text);
cmd.Parameters.AddWithValue("#Gender", ddlGender.SelectedValue);
cmd.Parameters.AddWithValue("#Salary", txtSalary.Text);
//Add the output parameter to the command object
SqlParameter outPutParameter = new SqlParameter();
outPutParameter.ParameterName = "#EmployeeId";
outPutParameter.SqlDbType = System.Data.SqlDbType.Int;
outPutParameter.Direction = System.Data.ParameterDirection.Output;
cmd.Parameters.Add(outPutParameter);
//Open the connection and execute the query
con.Open();
cmd.ExecuteNonQuery();
//Retrieve the value of the output parameter
string EmployeeId = outPutParameter.Value.ToString();
lblMessage.Text = "Employee Id = " + EmployeeId;
}
}
}
}
If i place this directive (I guess that is what it calls) on a top of .aspx
<%# Page Language="C#" AutoEventWireup="true" CodeBehind="WebForm2.aspx.cs" Inherits="adoDemo.WebForm2" %>
then I get another error:
System.Web.HttpException: Control 'txtEmployeeName' of type 'TextBox' must be placed inside a form tag with runat=server.
What is it that I am missing?
Your two pages are not communicating. You have not told the front-end who the backend is.
the # Page directive in the code-behind model contains attributes that
reference an external file and a class. These attributes link the .aspx page to its code.
https://msdn.microsoft.com/en-us/library/015103yb.aspx
Once you have added the attributres, you need to surround your markup with a <form></form> that has a runat="server" attribute.
User George Stocker gives an explanation on the runat="server" attribute.
<%# Page Language="C#" AutoEventWireup="true" CodeFile="WebForm2.aspx.cs" Inherits="WebForm2" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<table style="border: 1px solid black; font-family:Arial">
<tr>
<td>
Employee Name
</td>
<td>
<asp:TextBox ID="txtEmployeeName" runat="server"></asp:TextBox>
</td>
</tr>
<tr>
<td>
Gender
</td>
<td>
<asp:DropDownList ID="ddlGender" runat="server">
<asp:ListItem>Male</asp:ListItem>
<asp:ListItem>Female</asp:ListItem>
</asp:DropDownList>
</td>
</tr>
<tr>
<td>
Salary
</td>
<td>
<asp:TextBox ID="txtSalary" runat="server"></asp:TextBox>
</td>
</tr>
<tr>
<td colspan="2">
<asp:Button ID="btnSubmit" runat="server" Text="Submit" onclick="btnSubmit_Click" />
</td>
</tr>
<tr>
<td colspan="2">
<asp:Label ID="lblMessage" runat="server"></asp:Label>
</td>
</tr>
</table>
</form>
</body>
</html>
Related
What is wrong with this code? I have tried a lot of methods. But it always show login failed. No Build Errors though. I have a database named honeypot and a table called register in it,with username row and password row as varchars. I'm using built in login control. Can anyone help? I'm using Visual studio 2013.
home.aspx.cs
enter code here
using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using System.Data.SqlClient;
namespace CodeInjection4
{
public partial class Home : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
}
}
private static int count = 0;
protected void log1_Authenticate(object sender, AuthenticateEventArgs e)
{
if (log1.UserName == "Admin" && log1.Password == "Admin")
{
Response.Redirect("Adminhome.aspx");
}
else if (YourValidationFunction(log1.UserName, log1.Password))
{
Session["User"] = log1.UserName;
e.Authenticated = true;
Response.Redirect("userhome.aspx");
log1.TitleText = "Successfully Logged In";
}
else
{
e.Authenticated = false;
count++;
if (count >= 3)
{
count = 0;
Session["User"] = log1.UserName;
Server.Transfer("MainPage.aspx");
}
}
}
private SqlConnection strConnection = new
SqlConnection("server=.\\SQLEXPRESS;database=honeypot;integrated security=true;");
private bool YourValidationFunction(string UserName, string Password)
{
bool boolReturnValue = false;
String SQLQuery = "SELECT UserName, Password FROM Register";
SqlCommand command = new SqlCommand(SQLQuery, strConnection);
SqlDataReader Dr;
try
{
strConnection.Open();
Dr = command.ExecuteReader();
while (Dr.Read())
{
if ((UserName == Dr["UserName"].ToString()) & (Password == Dr["Password"].ToString()))
{
boolReturnValue = true;
}
}
Dr.Close();
}
catch
{
}
return boolReturnValue;
}
protected void lnkRegis_Click(object sender, EventArgs e)
{
Response.Redirect("AdUserAcc.aspx");
}
}
}
Home.aspx
enter code here
<%# Page Language="C#" AutoEventWireup="true" CodeBehind="Home.aspx.cs" Inherits="CodeInjection4.Home" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
<script runat="server">
</script>
<style type="text/css">
#form1 {
text-align: center;
}
.auto-style1 {
width: 981px;
text-align: left;
}
.auto-style2 {
width: 961px;
}
</style>
</head>
<body>
<form id="form1" runat="server">
<div>
Forestalling Code Injection</div>
<asp:Login ID="log1" OnAuthenticate="log1_Authenticate" runat="server" Width="1062px">
<LayoutTemplate>
<table cellpadding="1" cellspacing="0" style="border-collapse:collapse;">
<tr>
<td>
<table cellpadding="0">
<tr>
<td align="center" colspan="2">Log In</td>
</tr>
<tr>
<td align="right" class="auto-style2">
<asp:Label ID="UserNameLabel" runat="server" AssociatedControlID="UserName">User Name:</asp:Label>
</td>
<td class="auto-style1">
<asp:TextBox ID="UserName" runat="server"></asp:TextBox>
<asp:RequiredFieldValidator ID="UserNameRequired" runat="server" ControlToValidate="UserName" ErrorMessage="User Name is required." ToolTip="User Name is required." ValidationGroup="log1">*</asp:RequiredFieldValidator>
</td>
</tr>
<tr>
<td align="right" class="auto-style2">
<asp:Label ID="PasswordLabel" runat="server" AssociatedControlID="Password">Password:</asp:Label>
</td>
<td class="auto-style1">
<asp:TextBox ID="Password" runat="server" TextMode="Password"></asp:TextBox>
<asp:RequiredFieldValidator ID="PasswordRequired" runat="server" ControlToValidate="Password" ErrorMessage="Password is required." ToolTip="Password is required." ValidationGroup="log1">*</asp:RequiredFieldValidator>
</td>
</tr>
<tr>
<td colspan="2">
<asp:CheckBox ID="RememberMe" runat="server" Text="Remember me next time." />
</td>
</tr>
<tr>
<td align="center" colspan="2" style="color:Red;">
<asp:Literal ID="FailureText" runat="server" EnableViewState="False"></asp:Literal>
</td>
</tr>
<tr>
<td align="right" colspan="2" style="text-align: center">
<asp:Button ID="LoginButton" runat="server" CommandName="Login" Text="Log In" ValidationGroup="log1" />
</td>
</tr>
</table>
</td>
</tr>
</table>
</LayoutTemplate>
</asp:Login>
<br />
<asp:Button ID="Button1" runat="server" Text="Register" PostBackUrl="~/AdUserAcc.aspx" />
</form>
</body>
</html>
You are selecting all the users and looping through them. You have break out of the loop if you find a matching username and password such as
if ((UserName == Dr["UserName"].ToString()) & (Password == Dr["Password"].ToString()))
{
boolReturnValue = true;
break;
}
Othwerwise the next user will set it back to false.
A couple of notes:
Selecting all users and iterating through them is not scalable and wouldn't perform well. Instead you can pass in the username and password in WHERE clause. If you get a match then the login info is correct.
I'd recommend using logical-AND operator (&&) instead of bitwise-AND (&). Here's a SO thread with related discussion: Usage & versus &&
Consider using salted password hashes as opposed to plaintext passwords.
so I have this code in asp .net
Default.aspx
<%# Page Language="C#" AutoEventWireup="true" CodeFile="Default2.aspx.cs" Inherits="Default2" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
<style type="text/css">
.auto-style1 {
width: 248px;
}
.auto-style2 {
width: 253px;
}
</style>
</head>
<body>
<form id="form1" runat="server">
<asp:ScriptManager ID="ScriptManager1" runat="server" />
<div>
<table style="width:100%;">
<tr>
<td class="auto-style2">
</td>
<td>
<asp:SqlDataSource ID="Artikujt" runat="server" ConnectionString="<%$ ConnectionStrings:ChipString %>" SelectCommand="SELECT * FROM [Artikujt]"></asp:SqlDataSource>
</td>
</tr>
<tr>
<td class="auto-style1"> </td>
<td class="auto-style2">
<asp:TextBox ID="TextBox1" runat="server" AutoPostBack="True" ></asp:TextBox>
</td>
<td> </td>
</tr>
<tr>
<td class="auto-style1"> </td>
<td class="auto-style2">
<asp:PlaceHolder ID="PlaceHolder1" runat="server"></asp:PlaceHolder>
</td>
<td> </td>
</tr>
<tr>
<td class="auto-style1"> </td>
<td class="auto-style2">
<asp:PlaceHolder ID="PlaceHolder2" runat="server"></asp:PlaceHolder>
</td>
<td> </td>
</tr>
<tr>
<td class="auto-style1"> </td>
<td class="auto-style2">
<asp:PlaceHolder ID="PlaceHolder3" runat="server"></asp:PlaceHolder>
</td>
<td> </td>
</tr>
<tr>
<td class="auto-style1"> </td>
<td class="auto-style2">
<asp:PlaceHolder ID="PlaceHolder4" runat="server"></asp:PlaceHolder>
</td>
<td> </td>
</tr>
<tr>
<td class="auto-style1"> </td>
<td class="auto-style2">
<asp:PlaceHolder ID="PlaceHolder5" runat="server"></asp:PlaceHolder>
</td>
<td> </td>
</tr>
<tr>
<td class="auto-style1"> </td>
<td class="auto-style2">
<asp:Label ID="Label1" runat="server" Text="Label"></asp:Label>
</td>
<td> </td>
</tr>
</table>
<br />
</div>
</form>
</body>
</html>
Default.aspx.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data.SqlClient;
using System.Configuration;
using System.Data;
public partial class Default2 : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (IsPostBack)
{
AddItems();
}
}
DropDownList artikulli;
TextBox cmimi;
Label tregoCmimi;
TextBox sasia;
Label cmimiGjithsej;
protected void AddItems()
{
if (!string.IsNullOrEmpty(TextBox1.Text))
{
int a = int.Parse(TextBox1.Text);
for (int j = 1; j <= a; j++)
{
artikulli = new DropDownList();
cmimi = new TextBox();
tregoCmimi = new Label();
sasia = new TextBox();
cmimiGjithsej = new Label();
//artikulli.ID = j.ToString(IDUnik.ToString("N").Substring(31));
artikulli.ID = "artikulli_" + j.ToString();
artikulli.AutoPostBack = true;
cmimi.ID = "cmimi_" + j.ToString();
cmimi.AutoPostBack = true;
tregoCmimi.ID = "tregoCmimi_" + j.ToString();
sasia.ID = "sasia_" + j.ToString();
sasia.AutoPostBack = true;
cmimiGjithsej.ID = "cmimiGjithsej_" + j.ToString();
PlaceHolder1.Controls.Add(artikulli);
PlaceHolder2.Controls.Add(cmimi);
PlaceHolder3.Controls.Add(tregoCmimi);
PlaceHolder4.Controls.Add(sasia);
PlaceHolder5.Controls.Add(cmimiGjithsej);
DataTable listaArtikujt = new DataTable();
using (SqlConnection lidhje = new SqlConnection(ConfigurationManager.ConnectionStrings["ChipString"].ConnectionString))
{
try
{
SqlDataAdapter adapter = new SqlDataAdapter("SELECT [Artikulli] FROM [Artikujt]", lidhje);
adapter.Fill(listaArtikujt);
artikulli.DataSource = listaArtikujt;
artikulli.DataTextField = "Artikulli";
artikulli.DataBind();
}
catch (Exception ex)
{
Response.Write("Gabim:" + ex.ToString());
}
}
}
}
}
}
What I want to do is, after PostBack, after I have added number 2 it will show 2 DropDownlist, 2 Textboxes, 2 Labels, 2 Textboxes again and 2 other Labels.
I am trying to do after Post back, after I enter a number in TextBox cmimi = new TextBox(); it will automatically be added in the label below. I am trying to do but no luck.
I hope you understood my explanation.
Thank you. :)
I have an asp.net page where clients can insert inputs in text fields:
<table>
<tr>
<td style="width: 56px"><asp:Label ID="Label1" runat="server" Text="Name"></asp:Label></td>
<td style="width: 148px"><asp:TextBox ID="name" runat="server" Width="272px"></asp:TextBox></td>
</tr>
<tr>
<td style="width: 56px"><asp:Label ID="Label2" runat="server" Text="Email"></asp:Label></td>
<td style="width: 148px"><asp:TextBox ID="email" runat="server" Width="272px"></asp:TextBox></td>
</tr>
<tr>
<td style="width: 56px"><asp:Label ID="Label3" runat="server" Text="Subject"></asp:Label></td>
<td style="width: 148px"><asp:TextBox ID="sub" runat="server" Width="272px"></asp:TextBox></td>
</tr>
<tr>
<td style="width: 56px"><asp:Label ID="Label4" runat="server" Text="Message"></asp:Label></td>
<td style="width: 148px">
<asp:TextBox ID="message" runat="server" Width="272px"></asp:TextBox>
<!--<textarea id="message"; cols="1"; rows="1"; style="width: 272px; height: 152px;"></textarea>-->
</td>
</tr>
<tr></tr>
<tr>
<td style="width: 56px; height: 36px;"></td>
<td style="width: 148px; height: 36px;"><asp:Button ID="Button1" runat="server" Text="Submit" Style="float:left" OnClick="Button1_Click" />
<asp:Button ID="Button2" runat="server" Text="Reset" />
<asp:button id="btnTest" runat="server" onclick="btnTest_Click" text="Test Database Connection" />
</td>
</tr>
</table> "
I have a method that tries to add my values into the database:
protected void Button1_Click(object sender, EventArgs e)
{
using (SqlConnection conn1 = new SqlConnection(ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString))
{
//Check if the same request is already submitted.
SqlCommand cmd1 = new SqlCommand();
cmd1.CommandType = System.Data.CommandType.StoredProcedure;
cmd1.CommandText = "dbo.Procedure";
cmd1.Parameters.Add("#name", System.Data.SqlDbType.VarChar).Value = name.Text;
cmd1.Parameters.Add("#email", System.Data.SqlDbType.VarChar).Value = email.Text;
cmd1.Parameters.Add("#sub", System.Data.SqlDbType.VarChar).Value = sub.Text;
cmd1.Parameters.Add("#message", System.Data.SqlDbType.VarChar).Value = message.Text;
cmd1.Connection = conn1;
conn1.Open();
cmd1.ExecuteNonQuery();
conn1.Close();
}
Response.Redirect("~/Default.aspx");
}
But now I am getting error like "The name 'name'/'email'/'sub'/'message' does not exist in the current context". I am a new one into .net framework and C#. Please help.
My start page is Default.aspx and submit button is on Contact.aspx page. But when I press the Submit button in the design mode, then the method created in the code behind of Default.aspx.cs. Could it be an issue?
To me it looks like code behind cannot locate TextBoxes with ids (email, name...). If you are using web application project, check your .aspx.designer.cs file to make sure it is initialised properly. Also your code Behind partial class name and namespace must match your Inherits="xxx" attribute in <%# Page ... %> directive in your aspx page. However, you might also have this issue because your table is inside some databound or dynamic control, in this case you would have to find your control references in code.
I’m currently working on an asp.net page using C#. This page contains a button and once you click you will get a small HTML table with a name of person, cell phone number and email address. What I want to do is in code behind capture this HTML table along with its data in memory stream or other type of streams in order to do some operations. Here's my code
<table id="tb" runat="server">
<tr>
<td> Name </td>
<td> <asp:Label ID="lblName" runat="server" ></asp:Label> </td>
</tr>
<tr>
<td> Phone </td>
<td> <asp:Label ID="lblPhone" runat="server" ></asp:Label> </td>
</tr>
<tr>
<td> Email </td>
<td> <asp:Label ID="lblEmail" runat="server" ></asp:Label> </td>
</tr>
</table>
So please, if anyone could help of how to accomplish this process and I will be so thankful
Well although I don't really understand why do you want to do that, you can do this pretty simply, you have to put id and runat server tag at your table, and you already have that,
and then render this control to string :
markup:
<form id="form1" runat="server">
<table id="tb" runat="server">
<tr>
<td> Name </td>
<td> <asp:Label ID="lblName" runat="server" ></asp:Label> </td>
</tr>
<tr>
<td> Phone </td>
<td> <asp:Label ID="lblPhone" runat="server" ></asp:Label> </td>
</tr>
<tr>
<td> Email </td>
<td> <asp:Label ID="lblEmail" runat="server" ></asp:Label> </td>
</tr>
</table>
<hr />
Rendered table :
<hr />
<asp:Label ID="lblRenderedTable" runat="server"></asp:Label>
<hr />
</form>
code behind:
protected void Page_Load(object sender, EventArgs e)
{
lblName.Text = "User Name";
lblEmail.Text = "user#domain.com";
lblPhone.Text = "555-4214";
StringBuilder sb = new StringBuilder();
StringWriter tw = new StringWriter(sb);
HtmlTextWriter hw = new HtmlTextWriter(tw);
tb.RenderControl(hw);
string tableContents = sb.ToString();
lblRenderedTable.Text = tableContents;
}
I need to add a check for form variables that are passed to my adfs login page but when I add anything to the built-in Page_Load function it breaks.
FormsSignIn.aspx
<%# Page Language="C#" MasterPageFile="~/MasterPages/MasterPage.master" AutoEventWireup="true" ValidateRequest="false"
CodeFile="FormsSignIn.aspx.cs" Inherits="FormsSignIn" Title="<%$ Resources:CommonResources, FormsSignInPageTitle%>"
EnableViewState="false" runat="server"%>
<%# OutputCache Location="None" %>
<asp:Content ID="FormsSignInContent" ContentPlaceHolderID="ContentPlaceHolder1" runat="server">
<div class="GroupXLargeMargin"><asp:Label Text="<%$ Resources:CommonResources, FormsSignInHeader%>" runat="server" /></div>
<h3>*******I Want lbl1.Text to output here from the codefile.</h3>
<table class="UsernamePasswordTable">
<tr>
<td>
<span class="Label"><asp:Label Text="<%$ Resources:CommonResources, UsernameLabel%>" runat="server" /></span>
</td>
<td>
<asp:TextBox runat="server" ID="UsernameTextBox" ></asp:TextBox>
</td>
<td class="TextColorSecondary TextSizeSmall">
<asp:Label Text="<%$ Resources:CommonResources, UsernameExample%>" runat="server" />
</td>
</tr>
<tr>
<td>
<span class="Label"><asp:Label Text="<%$ Resources:CommonResources, PasswordLabel%>" runat="server" /></span>
</td>
<td>
<asp:TextBox runat="server" ID="PasswordTextBox" TextMode="Password" ></asp:TextBox>
</td>
<td> </td>
</tr>
<tr>
<td></td>
<td colspan="2" class="TextSizeSmall TextColorError">
<asp:Label ID="ErrorTextLabel" runat="server" Text="" Visible="False"></asp:Label>
</td>
</tr>
<tr>
<td colspan="2">
<div class="RightAlign GroupXLargeMargin">
<asp:Button ID="SubmitButton" runat="server" Text="<%$ Resources:CommonResources, FormsSignInButtonText%>" OnClick="SubmitButton_Click" CssClass="Resizable"/>
</div>
</td>
<td> </td>
</tr>
</table>
</asp:Content>
FormsSignIn.Aspx.cs
using System;
using Microsoft.IdentityServer.Web;
using Microsoft.IdentityServer.Web.UI;
public partial class FormsSignIn : FormsLoginPage
{
protected void Page_Load( object sender, EventArgs e )
{
//Uncommented, this breaks!!!!!!!!!!!!!!
/* if ( !string.IsNullOrEmpty(Page.Request.Form["foo"]) ) {
lbl1.Text = Page.Request.Form["foo"].Trim();
} else {
lbl1.Text = "not found";
} */
}
protected void HandleError( string message )
{
ErrorTextLabel.Visible = true;
ErrorTextLabel.Text = Resources.CommonResources.IncorrectUsernameText;
}
protected void SubmitButton_Click( object sender, EventArgs e )
{
try
{
SignIn( UsernameTextBox.Text, PasswordTextBox.Text );
}
catch ( AuthenticationFailedException ex )
{
HandleError( ex.Message );
}
}
}
You haven't mentioned how you added the code or how it breaks but, in general, I have found problems when I modify the files directly.
Given that ADFS is just another IIS application, I have more joy following this approach:
Modifying and Securing the ADFS 2 Web Application