Problem in insert (UniqueIdentifier) in Table - asp.net

Greeting,
I created my own database and used this method by Ankush Agnihotri (Create And Install ASP.NET Membership Database)to create users asnd membership and roles in my web application projects. See link below which method I used:
https://www.c-sharpcorner.com/blogs/create-install-asp-net-membership-database
I designed form to admin site to create an employee account in three steps :
First step :create employee account by (Registration tool) to create user account which will store employee account in Users Table.
Second Step: redirect admin to next page to complete an employee form information.
Until this moment a last two steps working correctly.
Third step: an confirmation appears to admin to catch a ROLE ID and USER ID which represented as (UniqueIdentifier) value to store its in USERSINROLE table as figures below:
A last two steps (one and two) working correctly, but a confirmation catch this problem:
My C# code behind to insert a two parameters in table, I tried in many ways from 1 to 5 but no ways to store a UniqueIdentifier value.
protected void Button1_Command(object sender, CommandEventArgs e)
{
using (SqlConnection sqlcon = new SqlConnection(connString))
{
sqlcon.Open();
string query = "INSERT INTO UsersInRoles(UserId,RoleId) VALUES (#UserId,#RoleId)";
SqlCommand sqlcmd = new SqlCommand(query, sqlcon);
//Try NO.1
//sqlcmd.Parameters.AddWithValue("#UserId",(FormView1.FindControl("l1") as Label).Text);
//sqlcmd.Parameters.AddWithValue("#RoleId", (FormView1.FindControl("L2") as Label).Text);
//Try NO.2
//sqlcmd.Parameters.Add("#UserId", SqlDbType.UniqueIdentifier).Value=(FormView1.FindControl("l1") as Label).Text;
// sqlcmd.Parameters.Add("#RoleId", SqlDbType.UniqueIdentifier).Value=(FormView1.FindControl("L2") as Label).Text;
//Try NO.3
//sqlcmd.Parameters.Add("#UserId", SqlDbType.UniqueIdentifier).Value = new System.Data.SqlTypes.SqlGuid((FormView1.FindControl("l1") as Label).Text);
//sqlcmd.Parameters.Add("#RoleId", SqlDbType.UniqueIdentifier).Value = new System.Data.SqlTypes.SqlGuid((FormView1.FindControl("L2") as Label).Text);
//Try NO.4
//sqlcmd.Parameters.AddWithValue("#UserId",new Guid(Convert.ToString((FormView1.FindControl("l1") as Label).Text)));
//sqlcmd.Parameters.AddWithValue("#RoleId", new Guid(Convert.ToString((FormView1.FindControl("L2") as Label).Text)));
//Try NO.5
//sqlcmd.Parameters.Add("#UserId", SqlDbType.UniqueIdentifier).Value = new Guid(Convert.ToString((FormView1.FindControl("l1") as Label).Text));
//sqlcmd.Parameters.Add("#RoleId", SqlDbType.UniqueIdentifier).Value = new Guid(Convert.ToString((FormView1.FindControl("L2") as Label).Text));
//Try NO.6
sqlcmd.Parameters.Add("#UserId", SqlDbType.UniqueIdentifier,32).Value =(FormView1.FindControl("l1") as Label).Text;
sqlcmd.Parameters.Add("#RoleId", SqlDbType.UniqueIdentifier, 32).Value = ((FormView1.FindControl("L2") as Label).Text);
sqlcmd.ExecuteNonQuery();
FormView1.DataBind();
sqlcmd.Connection.Close();
}
So anyone able to help me. Thanks

Related

How to Edit / change a File Uploaded with another Uploaded File in asp.net Webforms?

net webforms CRUD project where I've created textboxes, dropdown menu and a File upload for people to enter their details & I'm using them in a Grid-View, only doc docx and pdf are allowed, and I've created an edit button on the same Grid-View along with the delete button when I Press on Edit Button it opens up the edit menu for making changes in their details and they can also choose items from dropdown and can upload new file as well.
I'm trying to catch the files name to store it into db using a sp but I'm not getting any details its showing this error :-
enter image
protected void custgrid_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
using (SqlConnection con = new SqlConnection(cs))
{
int id = Convert.ToInt32(custgrid.DataKeys[e.RowIndex].Value);
SqlCommand cmd = new SqlCommand("sp_update", con);
string fname = (custgrid.Rows[e.RowIndex].FindControl("txtFname") as TextBox).Text;
string num = (custgrid.Rows[e.RowIndex].FindControl("txtNum") as TextBox).Text;
string cv = (custgrid.Rows[e.RowIndex].FindControl("cvv") as TextBox).Text;
string qual = (custgrid.Rows[e.RowIndex].FindControl("ddlQual") as TextBox).Text;
cmd.CommandType = System.Data.CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("#fname", fname);
cmd.Parameters.AddWithValue("#cv", cv);
cmd.Parameters.AddWithValue("#qual", qual);
cmd.Parameters.AddWithValue("#number", num);
cmd.Parameters.AddWithValue("#id", id);
con.Open();
cmd.ExecuteNonQuery();
con.Close();
Read();
}
}
here's my code, am I doing something wrong? Please Tell me how can I fix it.
I'm trying to make it possible for other to be able to upload new files when in edit mode. But it's showing the error mentioned the the question above.

How to access multiple tables from a SELECT FROM in ASP.NET with SQL Server?

I have this project I am working on for an assignment, and I have a question working with ASP.NET and SQL Server. I have a login page that kinda works, but there are two tables that I need to get data from - users (subscribers) and admin page but am unsure how to access both of them as I can only access one.
public void login(Object src,EventArgs e)
{
get_connection();
try
{
connection.Open();
command = new SqlCommand("SELECT * FROM subscribers WHERE Email = #Email AND Password = #Password", connection);
command.Parameters.AddWithValue("#Email", loginName.Text);
command.Parameters.AddWithValue("#Password", loginPass.Text);
//command = new SqlCommand("SELECT * FROM admin WHERE Email =#Email and Password = #Password", connection);
//command.Parameters.AddWithValue("#Email", loginName.Text);
//command.Parameters.AddWithValue("#Password", loginPass.Text);
reader = command.ExecuteReader();
I commented out the admin part because when I include it, only admin username and password is accepted and not subscribers. What would I need to do to fix this?
The "admin part" causes you to only get records from the admin table because you're destroying and recreating your SqlCommand object. You'll need to create a new command in a different variable and read from it separately. There are ways to get multiple recordsets in the same call but I don't recommend it in this case.
That out of the way... Normally I'd expect to see a single users table with permissions/roles granted elsewhere. Consider something like the out of the box ASP.NET membership provider to take care of these implementation details for you:
https://learn.microsoft.com/en-us/dotnet/framework/wcf/feature-details/how-to-use-the-aspnet-membership-provider

ASP.NET Impersonation design

This is my ASP.NET authentication operation.
private void LoginButton_Click(Object sender,
EventArgs e)
{
string userName = txtUserName.Value;
string password = txtUserPass.Value;
if (ValidateUser(txtUserName.Value, txtUserPass.Value))
{
FormsAuthenticationTicket tkt;
string cookiestr;
HttpCookie ck;
tkt = new FormsAuthenticationTicket(1, txtUserName.Value, DateTime.Now,
DateTime.Now.AddMinutes(3), chkPersistCookie.Checked,
userName + "#ticket");
cookiestr = FormsAuthentication.Encrypt(tkt);
ck = new HttpCookie(FormsAuthentication.FormsCookieName, cookiestr);
if (chkPersistCookie.Checked)
ck.Expires = tkt.Expiration;
ck.Path = FormsAuthentication.FormsCookiePath;
Response.Cookies.Add(ck);
string strRedirect;
strRedirect = Request["ReturnUrl"];
if (strRedirect == null)
strRedirect = "MyAccount.aspx";
Response.Redirect(strRedirect, true);
}
else
Response.Redirect("logon.aspx", true);
}
I have User table in my db where all credentials are saved. Using ValidateUser method I am doing credentials validation. Also I have three type of users: Member, Moderator and Administrator. Each type of members has unique functionality. Lets say I have A, B and C T-SQL stored inside in my db.
What should I to to let for:
Member execute only A query.
Moderator execute A and B.
Administrator execute A,B and C.
Of course, I can manage execution from Web app, but I am not sure how safe it is. Technically I can execute similar query outside of App, which gives access to all db data. I want somehow combine Web App login and Db access as well.
Thanks!
If these queries are going to come from the web app, I think you would want to manage the code side that invokes the procedures.. you could maintain a list of urls in your database, assign roles, and give these roles access to specific urls. These urls would dictate what queries a user could execute...
then in your code you could assign custom attributes to limit access to them....
http://msdn.microsoft.com/en-us/library/ff647396.aspx

Creating a Registration form: In asp.net

I'm new to Asp.net, and creating a online telephone bill payment form. A new user has to register to get a valid id,
In the SQL Server I created a table which has only two columns as Phone_number and User_name. I have set the Phone_number column as unique. Just to avoid re-registration of a user.
I have checked the form during runtime using asp.net web page but, i get some error in the code.
Also I have to display a message that "the phone number already exists."
my code is as follows. Is there a better way??
try
{
string s = " insert into new_user values(#Phone_number,#name)";
cmd = new SqlCommand(s, con);
cmd.Parameters.AddWithValue(#"Phone_number", TextBox1.Text);
cmd.Parameters.AddWithValue(#"Name", TextBox2.Text);
cmd.ExecuteNonQuery();
}
catch (SqlException ex)
{
Console.WriteLine(ex);
MessageBox.Show("Phone Number already exist, Enter a different phone number");
}
TextBox1.Text = TextBox2.Text = null;
Session["a"] = TextBox1.Text;
Response.Redirect("registration.aspx");
}
in the above code if I don't user the Console.Writeline(); I get an error in the ExecuteNonQuerry() part.
I suggest that First you check, Is there same phone no available in database?
Just use select query , If you get any record you can display a message and if not exist any record then use insert query.
If(select * from table where phone=#Phone)
insert command
else
message

Efficient way to create large number of Membership via Membership.CreateUser?

I just create Membership management program, this program can create user one by one and it can import data from text file as well. When I import data from text file, it can create around 30 user before timeout, after I debug it take nearly 1 sec for each CreateUser call.
I want to know, how can I improve performance when I create large number of aspnet user.
Solution1:
Get all data from user table into dataset ds in table "User"
Get all data from member table into table "Member" in the same dataset ds
Create a relationship between the two tables on field userid
Run a loop on each row of table User
For each user call Membership.CreateUser with UserName and Password as parameters
Get all child rows for the current user DataRow.GetChildRows
For each childrow returned, call Roles.AddUserToRole with username and rolename as parameters (add only if the role is active)
Taken from here.
Solution 2:
Download Peter Keller's Membership Editor
Create a SpreadSheet with these columns: UserName,password, and email.
Import this excel file to this database as table: yourUsers$
Create a Winforms application, Add a button to form and paste this code in its click event:
protected void batchInsertButton_Click(object sender, EventArgs e)
{
string strConn = ConfigurationManager.ConnectionStrings["1ConnectionString"].ConnectionString;
string strSQL = "SELECT * FROM yourUsers$";
SqlConnection myConnection = new SqlConnection(strConn);
myConnection.Open();
SqlCommand myCommand = new SqlCommand(strSQL,myConnection);
SqlDataReader myReader;
myReader = myCommand.ExecuteReader();
while (myReader.Read()) {
ObjectDataSourceMembershipUser.InsertParameters["UserName"].DefaultValue = myReader["UserName"].ToString();//TextBoxUserName.Text; ;
ObjectDataSourceMembershipUser.InsertParameters["password"].DefaultValue = myReader["password"].ToString();//TextBoxPassword.Text;
ObjectDataSourceMembershipUser.InsertParameters["passwordQuestion"].DefaultValue ="your qestion";//TextBoxPasswordQuestion.Text;
ObjectDataSourceMembershipUser.InsertParameters["passwordAnswer"].DefaultValue = "your answer";//TextBoxPasswordAnswer.Text;
ObjectDataSourceMembershipUser.InsertParameters["email"].DefaultValue = myReader["email"].ToString();//TextBoxEmail.Text;
ObjectDataSourceMembershipUser.InsertParameters["isApproved"].DefaultValue = "true";//CheckboxApproval.Checked == true ? "true" : "false";
ObjectDataSourceMembershipUser.Insert();
//hard code this user role
Roles.AddUserToRole(myReader["UserName"].ToString(), "NormalUser");
}
myConnection.Close();
GridViewMemberUser.DataBind();
GridViewRole.DataBind();
}
Taken from here.

Resources