what i have done is login and the username appears in my masterpage in a label. what i need to do is if the logged in user has admin permission make visible controls on several child pages (including a gridview deletecontrol that is there on one child page). have be struggling to figure it out. just want to learn.
Is there a way to class all the controls under a class call admin and call from masterpage on checking user permission?
Loginpage code behind
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.Adapters;
public partial class login1 : System.Web.UI.Page
{
public void Page_Load(object sender, EventArgs e)
{
}
protected void LoginButton_Click(object sender, EventArgs e)
{
DataSet ds = new DataSet();
ds = WCGSQL.showdata("select * from Login where Username='" + UserName.Text + "' and Password='" + Password.Text + "'");
if (ds.Tables[0].Rows.Count != 0)
{
Session["Username"] = UserName.Text;
Response.Redirect("Home.aspx");
}
else
{
FailureText.Visible = true;
FailureText.Text = "Invalid Login";
}
}
}
App/code code behind
using System;
using System.Data;
using System.Configuration;
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;
public class WCGSQL
{
static SqlConnection con = new SqlConnection(#"Data Source=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|WCG.mdf;Integrated Security=True;User Instance=True");
static public Boolean savedata(string qurt)
{
try
{
SqlCommand cmd = new SqlCommand(qurt, con);
con.Open();
cmd.ExecuteNonQuery();
return true;
}
catch
{
return false;
}
finally
{
con.Close();
}
}
static public DataSet showdata(string qurt)
{
DataSet ds = new DataSet();
try
{
SqlDataAdapter adp = new SqlDataAdapter(qurt, con);
adp.Fill(ds);
return ds;
}
catch
{
return ds;
}
}
}
You want to use the LoginView control. See ASP.NET Login Controls Overview to learn about the entire suite.
Example from MSDN:
<%# Page Language="C#" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<script runat="server">
</script>
<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
<title>ASP.NET Example</title>
</head>
<body>
<form id="form1" runat="server">
<p>
<asp:LoginStatus id="LoginStatus1" runat="server"></asp:LoginStatus></p>
<p>
<asp:LoginView id="LoginView1" runat="server">
<AnonymousTemplate>
Please log in for personalized information.
</AnonymousTemplate>
<LoggedInTemplate>
Thanks for logging in
<asp:LoginName id="LoginName1" runat="Server"></asp:LoginName>.
</LoggedInTemplate>
<RoleGroups>
<asp:RoleGroup Roles="Admin">
<ContentTemplate>
<asp:LoginName id="LoginName2" runat="Server"></asp:LoginName>, you
are logged in as an administrator.
</ContentTemplate>
</asp:RoleGroup>
</RoleGroups>
</asp:LoginView></p>
</form>
</body>
</html>
if (HttpContext.Current.User.IsInRole("member"))
{
//enable/disable here
}
Hey i'd done one application like this. What you need to do is make separate web-pages (i.e. after login pages) for both admin and other users. Then you can easily authenticate admin through his credentials and redirected to the respective page. There you can placed some controls according to the need.
And if your concern is to create an application like control-access board where admin can give permissions to modules to what to show on child pages of other users then let me know through your reply.
Related
hi I am trying to make a log in page as well as sign up page in asp.net using 3 tier architecture by using sql server architecture. I am able to fetch data from sql server data base which I have manually inserted during table creation in database and I am able to use it in my log in page.
I have also created a sign up page but I am not able to get the values from sign up webform textbox to sqlserver database I am getting some error kindly help me with this.
I have given the connection string of sql server in web.config
my sql server table creation code
CREATE TABLE LOGINDETAILS
(USERID VARCHAR(50),
PASSWORD VARCHAR (50)
);
INSERT INTO LOGINDETAILS (USERID,PASSWORD) values( 'sam', 'pass');
web.config connection string code
<?xml version="1.0"?>
<!--
For more information on how to configure your ASP.NET application, please visit
http://go.microsoft.com/fwlink/?LinkId=169433
-->
<configuration>
<connectionStrings>
<add name="DBcon" connectionString="Data Source=P3A-B1YH882\SQLSERVER;Initial Catalog=master;Integrated Security=True" providerName="System.Data.SqlClient"/>
</connectionStrings>
<system.web>
<compilation debug="true" targetFramework="4.5" />
<httpRuntime targetFramework="4.5" />
</system.web>
</configuration>
my business layer /middle layer code
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Configuration;
using System.Data;
using DataAcess;
using System.Data.SqlClient;
using System.Data.Sql;
namespace middlelayer
{
public class UserBO
{
private string _UserName = " ";
public string UserName
{
get { return _UserName; }
set { _UserName = value; }
}
private string _Password = " ";
public string Password
{
get { return _Password; }
set { _Password = value; }
}
DataA da = new DataA();
public bool getUser()
{
if (da.IsValid(UserName, Password).Tables[0].Rows.Count == 0)
{
return false;
}
else
{
return true;
}
}
}
}
my datAccess layer code
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Configuration;
using System.Data;
using System.Data.SqlClient;
using System.Data.Sql;
namespace DataAcess
{
public class DataA
{
string conString = ConfigurationManager.ConnectionStrings["DBcon"].ToString();
public DataSet IsValid(string UserName, string Password)
{
SqlConnection con = new SqlConnection(conString);
con.Open();
SqlCommand cmd = new SqlCommand("SELECT * FROM LOGINDETAILS WHERE USERID ='" + UserName + "' and PASSWORD= '" + Password + "'", con);
DataSet ds = new DataSet();
SqlDataAdapter sda = new SqlDataAdapter(cmd);
sda.Fill(ds);
return ds;
}
}
}
MY LOGIN PAGE CODE
<%# Page Language="C#" AutoEventWireup="true" CodeBehind="login.aspx.cs" Inherits="WebApplication4.login" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body style="height: 277px">
<form id="form1" runat="server">
<div>
<asp:Label ID="lbluserid" runat="server" BackColor="#FFFF99" BorderStyle="Ridge" Height="17px" Text="User ID" Width="52px"></asp:Label>
<asp:TextBox ID="txtuserid" runat="server" BackColor="#99FFCC" style="margin-left: 122px"></asp:TextBox>
<br />
</div>
<p>
<asp:Label ID="lblpassword" runat="server" BackColor="#FFFF99" BorderStyle="Ridge" Text="Password"></asp:Label>
<asp:TextBox ID="txtpassword" TextMode="Password" runat="server" BackColor="#99FFCC" style="margin-left: 110px" ></asp:TextBox>
</p>
<p>
</p>
<asp:Button ID="btnlogin" runat="server" BackColor="#33CCFF" BorderStyle="Ridge" OnClick="btnlogin_Click" style="margin-left: 78px" Text="Login" Width="107px" />
<p>
</p>
<asp:Label ID="Label1" runat="server" Text="NOT REGISTERED ??"></asp:Label>
<asp:HyperLink ID="HyperLink1" runat="server" BorderStyle="Outset" NavigateUrl="~/sign_up.aspx">SIGN UP</asp:HyperLink>
</form>
</body>
</html>
* MY SIGN UP PAGE CODE*
<%# Page Language="C#" AutoEventWireup="true" CodeBehind="sign_up.aspx.cs" Inherits="WebApplication4.sign_up" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<div>
</div>
<asp:Label ID="lblssignup" runat="server" BackColor="#FF99CC" Text="SIGN UP"></asp:Label>
<br />
<br />
<p>
<asp:Label ID="lblsuserid" runat="server" Text="ENTER USER ID"></asp:Label>
<asp:TextBox ID="TextBox1" runat="server" style="margin-bottom: 0px"></asp:TextBox>
</p>
<asp:Label ID="lblspassword" runat="server" Text="ENTER PASSWORD"></asp:Label>
<asp:TextBox ID="TextBox2" runat="server"></asp:TextBox>
<p>
<asp:Button ID="Button1" runat="server" Text="Button" OnClick="Button1_Click" Width="66px" />
</p>
</form>
</body>
</html>
SIGN UP PAGE BUTTON CODE FOR ENTERING DATA INTO SQL SERVER DATABASE ON BUTTON CLICK
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Configuration;
using System.Data.SqlClient;
using System.Data;
using middlelayer;
namespace WebApplication4
{
public partial class sign_up : System.Web.UI.Page
{
string conString = ConfigurationManager.ConnectionStrings["DBcon"].ToString();
protected void Page_Load(object sender, EventArgs e)
{
}
protected void Button1_Click(object sender, EventArgs e)
{
SqlConnection con = new SqlConnection(conString);
con.Open();
string ins= "Insert into [LOGINDETAILS](USERID, PASSWORD) VALUES ('" +TextBox1.Text+ "' , '" +TextBox2.Text+ "')";
SqlCommand com = new SqlCommand(ins,con);
DataSet du = new DataSet();
SqlDataAdapter sdi = new SqlDataAdapter(com);
sdi.Fill(du);
con.Close();
}
}
}
I AM getting error in this last code only of sign up button it is not able to insert values of SIGN UP webform Textbox to sql server databse table and also not reflecting the real values which I want to add in sql server TABLE using sign up webform and also noty saving it. It is sending some error values . kindly help me with this.
BELOW ARE THE IMAGES OF LOG IN AS WELL AS SIGN UP PAGE FOR REFERENCE
LOGIN PAGE WEB FORM
SIGN UP PAGE WEBFORM
KINDLY HELP IN RESOLVING THIS ISSUE
Try this:
SqlConnection con = new SqlConnection(conString);
con.Open();
string ins= "Insert into [LOGINDETAILS](USERID, PASSWORD) VALUES (#param1 , #param2)";
SqlCommand cmd = new SqlCommand(ins,con);
cmd.Parameters.Add("#param1", SqlDbType.Varchar, 50).value = TextBox1.Text;
cmd.Parameters.Add("#param2", SqlDbType.Varchar, 50).value = TextBox2.Text;
cmd.CommandType = CommandType.Text;
cmd.ExecuteNonQuery();
con.Close()
When trying to register to my database I am receiving the "The name 'UName' does not exist in the current context" error.
Register.aspx:
<%# Page Language="C#" AutoEventWireup="true" CodeFile="Register.aspx.cs" Inherits="Register" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>Registration Page</title>
</head>
<body>
<p>This is the registration page</p>
Home | Register
<form id="form1" runat="server">
<div>
<p>Enter First Name :</p>
<p>
<asp:TextBox ID="UName" runat="server" Width="271px"></asp:TextBox>
</p>
<p>
<asp:Button ID="registerButton" runat="server" Text="REGISTER" OnClick="registerEventMethod" />
</p>
</div>
</form>
</body>
</html>
Register.aspx.cs:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
public partial class Register : System.Web.UI.Page
{
MySql.Data.MySqlClient.MySqlConnection conn;
MySql.Data.MySqlClient.MySqlCommand cmd;
String queryStr;
protected void Page_Load(object sender, EventArgs e)
{
}
protected void registerEventMethod(object sender, EventArgs e)
{
registerUser();
}
private void registerUser()
{
String connString = System.Configuration.ConfigurationManager.ConnectionStrings["WebAppConnString"].ToString();
conn = new MySql.Data.MySqlClient.MySqlConnection(connString);
conn.Open();
queryStr = "";
queryStr = "INSERT INTO jamieobr_obecarrentals.users (Forename)" +
"VALUES('" + UName.Text + "')";
cmd = new MySql.Data.MySqlClient.MySqlCommand(queryStr, conn);
cmd.ExecuteReader();
conn.Close();
}
}
why am I getting this error? I have tried several solutions and all failed.
So I solved my own issue, the first initial issue was that I tried copying the .aspx file into a new solution, however this did not copy along the .aspx.designer.cs file therefore causing the problem.
However after trying to re write a fresh version manually which had a designer file with it I forgot to include the .cs file into the namespace of my solution therefore then generating a new problem.
However after including the .cs file into the namespace, hey presto, it worked!
Im using Microsoft Visual Studio 2012 as platform and i have created Web Forms Project
i have created data base file "SimpleDB.mdf" inside his "Table" folder i added new table called "Table" which has two columns - id and Name(string).What im trying is to insert string data into Name column of this table while calling server side function from javascript function.
This is the aspx.cs code
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.Web.Services;
namespace ProjectWWW
{
public partial class WebForm1 : System.Web.UI.Page
{
[WebMethod]
public static string InsertData(string ID){
string source = "Data Source=(LocalDB)\v11.0;Integrated Security=True;Connect Timeout=30";
SqlConnection con = new SqlConnection(source);
{
SqlCommand cmd = new SqlCommand("Insert into Table(Name) values('" + ID + "')", con);
{
con.Open();
cmd.ExecuteNonQuery();
return "True";
}
}
}
}
and this is the aspx code
<%# Page Language="C#" AutoEventWireup="true" CodeBehind="WebForm1.aspx.cs" Inherits="ProjectWWW.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" />
<script>
function CallMethod() {
PageMethods.InsertData("hello", CallSuccess, CallError);
}
function CallSuccess(res) {
alert(res);
}
function CallError() {
alert('Error');
}
</script>
</head>
<body>
<header>
</header>
<div class="table" id="div1" > </div>
<form id="Form1" runat="server">
<asp:Button id="b1" Text="Submit" runat="server" onclientclick="CallMethod();return false;"/>
<asp:ScriptManager enablepagemethods="true" id="ScriptManager1" runat="server"></asp:ScriptManager>
</form>
</body>
</html>
So basically im expecting when the button submit is clicked the Table Column "Name" will be filled with "Hello" but nothing happens and the column stays empty(NULL)
Table is reserved word in T-SQL so i would suggest you to use [] square brackets to enclose the Table.
Try This:
SqlCommand cmd = new SqlCommand("Insert into [Table](Name)
values('" + ID + "')", con);
Suggestion: Your query is open to sql injection attacks.I would suggest you to use Parameterised Queries to avoid them.
Try This:
using(SqlConnection con = new SqlConnection(source))
{
using(SqlCommand cmd = new SqlCommand("Insert into [Table](Name)
values(#Name)", con))
{
con.Open();
cmd.Parameters.AddWithValue("#Name",ID);
cmd.ExecuteNonQuery();
return "True";
}
}
currently I have a web which loads excel spreadsheet data into SQL database. When the page loads, all the parameters are hard coded on the code behind, so I do not have 'browse for file' and 'upload' button. I would like to implement these 2 buttons but I am not sure how should I do it.
I am using C# language, Visual Studio 2005 and SQL Server 2005.
Below is the code which runs the import of excel data into the database:
importexcel.aspx.cs
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Data.OleDb;
using System.Data.Common;
using System.Data.SqlClient;
public partial class ImportExcel : System.Web.UI.Page
{
public static string path = #"c:\Documents and Settings\rhlim\My Documents\Visual Studio 2005\WebSites\insqlserver\studentsheet1.xls";
public static string connStr = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + path + ";Extended Properties=Excel 8.0;";
protected void Page_Load(object sender, EventArgs e)
{
// Create Connection to Excel Workbook
using (OleDbConnection connection =
new OleDbConnection(connStr))
{
OleDbCommand command = new OleDbCommand
("Select StudentName,RollNo,Course FROM [Sheet1$]", connection);
connection.Open();
// Create DbDataReader to Data Worksheet
using (DbDataReader dr = command.ExecuteReader())
{
// SQL Server Connection String
string sqlConnectionString = "Data Source=<IP>;Initial Catalog=<database>;User ID=<userid>;Password=<password>";
// Bulk Copy to SQL Server
using (SqlBulkCopy bulkCopy =
new SqlBulkCopy(sqlConnectionString))
{
bulkCopy.DestinationTableName = "tStudent";
bulkCopy.WriteToServer(dr);
}
}
}
}
}
Below is my code for the my current html:
importexcel.aspx
<%# Page Language="C#" AutoEventWireup="true" CodeFile="ImportExcel.aspx.cs" Inherits="ImportExcel" %>
<!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></title>
<script language="javascript" type="text/javascript">
</script>
</head>
<body>
<form id="form1" runat="server">
<div>
</div>
Please select a Excel spreadsheet to import:<br />
<asp:FileUpload ID="fupExcel" runat="server" />
<br />
<br />
<asp:Button ID="btnImport" runat="server"
Text="Import" onclick="btnImport_Click" />
<br />
<br />
<a href=http://localhost:1701/SoD>Click to go to main page</a>
</form>
</body>
</html>
I am not sure how do I attach the 2 buttons to my background code, someone teach me? Best if with sample code, thanks a lot!
First, the code in your page load needs to execute only if(IsPostBack) or on button click.
Second, (At leas modern) browsers won't let you change the value of the input file field, or click it.
You might try with some flash upload thing or so, but I don't expect much.
I have a web page with an empty div, id="PreAcquisitionDiv" runat="server"
In the C# code-behind, on Page_Load, I build up a table and set it to PreAcquisitionDiv.InnerHtml
My page displays OK. I cause a PostBack, intending to change the data in the table. In the code, the PreAcquisitionDiv.InnerHtml does change, but the table I put there the first time is still displayed on the page instead.
I have seen some warnings about using InnerHtml at all, but the examples of alternatives that I have seen are JavaScript.
I am using IE 8, but I observe the same behavior in Chrome.
Thank you for any suggestions!
For example, this code displays "SomeStuff" when it first displays the page; then still "SomeStuff" after the PostBack even though the InnerHtml was changed.
protected void Page_Load( object sender, EventArgs e )
{
StringBuilder html = new StringBuilder( #"<TABLE BORDER='1' WIDTH='100%'>" );
if( !IsPostBack )
{
html.Append(#"<TR><TD>SomeStuff</TD></TR>" );
}
else
{
html.Append( #"<TR><TD>Some New Stuff</TD></TR>" );
}
html.Append( #"</TABLE>" );
this.PreAcquisitionDiv.InnerHtml = html.ToString( );
}
If you are changing the HTML on post back are you running your function to set it on post back as well?
UPDATE: I copied and pasted your code and it works fine for me. Here is my entire code behind:
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.Text;
namespace Sandbox
{
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
StringBuilder html = new StringBuilder(#"<TABLE BORDER='1' WIDTH='100%'>");
if (!IsPostBack)
{
html.Append(#"<TR><TD>SomeStuff</TD></TR>");
}
else
{
html.Append(#"<TR><TD>Some New Stuff</TD></TR>");
}
html.Append(#"</TABLE>");
this.PreAcquisitionDiv.InnerHtml = html.ToString();
}
protected void btnTest_OnClick(object sender, EventArgs e)
{
}
}
}
And here is my entire ASPX page
<%# Page Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="Sandbox._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>Untitled Page</title>
</head>
<body>
<form id="form1" runat="server">
<div id="PreAcquisitionDiv" runat="server">
</div>
<asp:Button ID="btnTest" runat="server" OnClick="btnTest_OnClick" />
</form>
</body>
</html>