Enabled/Disabled Button based on User Permission [C# MySQL] - c#

I'm trying with some code to disable/enable button based on user permission.
However, the code seem like nothing change to the system.
Anyone can advice/guide me on these? Thanks in advance.
public partial class frmTest : Form
{
public string UserID;}
private void frmTest_Load(object sender, EventArgs e)
{
RefreshActivate();
private void RefreshActivate()
{
DataSet ds = new DataSet();
MySQLClass.query(ds, "SELECT * FROM users WHERE username = '" + UserID + "'");
string strPermission = ds.Tables[0].Columns["permission"].ToString();
if (strPermission == "Admin")
{
btnActivate.Enabled = true;
}
else if (strPermission == "ReadOnly")
{
btnActivate.Enabled = false;
}
else
{
btnActivate.Enabled = false;
}
}}
Picture: https://i.stack.imgur.com/BevH8.png

Try to check first the permission if not null
if(!strPermission.Equals(null)//or ""
{
if (strPermission == "Admin")
{
btnActivate.Enabled = true;
}
else if (strPermission == "ReadOnly")
{
btnActivate.Enabled = false;
}
}else{
//value of permision is empty
MessageBox.Show("Permission is empty");
}
Now if the permission is empty it is something to do or fix when retrieving the data

Related

Disable Right Click in Popup Window

how should I disable the right click in Popup Window. I dont want the user to save or print the document in the Popup Window. Here is my interface Interface
Here is my aspx.cs code under TreeView1_SelectedNodeChanged
protected void TreeView1_SelectedNodeChanged(object sender, EventArgs e)
{
if (Session["loggedUserID"] == null && Session["loggedRoleID"] == null)
{
Response.Redirect("~/Login.aspx");
}
else
{
if (TreeView1.SelectedNode.Parent == null)
{
ltEmbed.Visible = false;
}
else
{
ltEmbed.Visible = true;
string Text = TreeView1.SelectedNode.Text.ToString();
int loggedUserID = Convert.ToInt32(Session["loggedUserID"]);
List<BOL.UserInfo> userslist = new UserInfos().List();
BOL.UserInfo loggeduser = userslist.Where(x => x.UserID == loggedUserID).FirstOrDefault();
BOL.DMS getdetail = new DMSS().GET_FILE(loggeduser.SUBSIDIARY_CD, Text);
string FILE_NAME = getdetail.F_NAME;
string FILE_PATH = getdetail.MAIN;
string url = String.Format(ResolveUrl(FILE_PATH));
string script = "window.open('" + url + "', '_blank','popup_window','width=700,height=600,left=100,top=100,resizable=false,oncontextmenu= return false');";
ClientScript.RegisterStartupScript(this.GetType(), "popUp", script, true);
}
}
}
Thank you.

Error: "Input string was not in a correct format" on false statement

My code is working fine if the statement (numtickets > tickav) is true (if tickets available is greater than tickets ordered) But if other wise, it throws in this error "FormatException was unhandled by user code, Input string was not in a correct format" on int numTick = Convert.ToInt32(txtNumberOfTickets.Text);
I do know that somehow I can use tryparse, i need help putting it in the code.
Any help would be appreciated, thank you
namespace TicketsApp
{
public partial class TicketOrder : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (Session["description"] != null && Session["EventID"] != null && Session["numtickets"] != null && Session["ticketcost"] != null
&& Session["State"] != null && Session["Section"] != null && Session["Row"] != null && Session["date"] != null)
{
if (!IsPostBack)
{
try
{
txtEventDescription.Text = Session["description"].ToString();
txtEventID.Text = Session["EventID"].ToString();
txtTicketsAvailable.Text = Session["numtickets"].ToString();
txtTicketCost.Text = Session["ticketcost"].ToString();
txtState.Text = Session["State"].ToString();
txtSectionNumber.Text = Session["Section"].ToString();
txtRowNumber.Text = Session["Row"].ToString();
txtNumberOfTickets.Focus();
lblOutput.Visible = false;
}
catch
{
lblError.Text = "Please Search for Tickets First!";
lblError.Visible = true;
btnOrderTickets.Visible = false;
Response.Redirect("TicketSearch.aspx");
return;
}
}
}
}
protected void btnOrderTickets_Click(object sender, EventArgs e)
{
TicketsDataAccessDataContext NewOrder = new TicketsDataAccessDataContext();
int numTick = Convert.ToInt32(txtNumberOfTickets.Text);
string s = txtTotalCost.Text.Substring(1);
int totc = Convert.ToInt32(s);
int id = Convert.ToInt32(txtEventID.Text);
DateTime dt = Convert.ToDateTime(Session["date"]);
int returnedValue = NewOrder.PlaceOrderFull(id, txtEventDescription.Text, dt, Session["State"].ToString(), Session["section"].ToString(), Session["Row"].ToString(), numTick, totc, "vfateev");
if (returnedValue != 0)
{
lblOutput.Text = "Error has occured. Please try again";
lblOutput.Visible = true;
btnOrderTickets.Visible = false;
}
else
{
lblOutput.Visible = true;
lblOutput.Text = "Thank you";
btnOrderTickets.Visible = false;
}
}
protected void txtNumberOfTickets_TextChanged1(object sender, EventArgs e)
{
int cos = Convert.ToInt32(txtTicketCost.Text);
int numtickets = Convert.ToInt32(txtNumberOfTickets.Text);
int tickav = Convert.ToInt32(txtTicketsAvailable.Text);
if (numtickets > tickav)
{
lblError.Text = "Please Enter a valid ticket quantity";
lblError.Visible = true;
lblOutput.Text = "";
txtNumberOfTickets.Text = "";
}
else
{
int cost = cos * numtickets + 5;
txtTotalCost.Text = "$" + cost.ToString();
lblOutput.Visible = false;
lblFee.Text = "There is a $5 shipping fee";
lblFee.Visible = true;
lblError.Text = "";}
}
}
}
You can use int.TryParse which returns a boolean and does not throw an exception.
int numTick = 0;
bool result = int.TryParse(txtNumberOfTickets.Text, out numTick );
You can also do some client side validation to ensure that the field is filled in and contains a number.
Here is one of your methods rewritten using Int32.TryParse. I assumed you're doing txtTotalCost.Substring(1) to trim off the currency symbol. There are probably safe ways to do this, I'm just going to trim "$" for this example.
protected void btnOrderTickets_Click(object sender, EventArgs e)
{
int numberOfTickets, ticketCost, eventId;
if(Int32.TryParse(txtNumberOfTickets.Text, out numberOfTickets) &&
Int32.TryParse(txtTotalCost.Text.TrimStart('$'), out ticketCost) &&
Int32.TryParse(txtEventID.Text, out eventId))
{
DateTime dt = Convert.ToDateTime(Session["date"]);
TicketsDataAccessDataContext NewOrder = new TicketsDataAccessDataContext();
int returnedValue = NewOrder.PlaceOrderFull(eventId, txtEventDescription.Text, dt, Session["State"].ToString(), Session["section"].ToString(), Session["Row"].ToString(), numberOfTickets, ticketCost, "vfateev");
if (returnedValue != 0)
{
lblOutput.Text = "Error has occured. Please try again";
lblOutput.Visible = true;
btnOrderTickets.Visible = false;
}
else
{
lblOutput.Visible = true;
lblOutput.Text = "Thank you";
btnOrderTickets.Visible = false;
}
}
else
{
lblOutput.Visible = true;
lblOutput.Text = "Some validation error message here...";
}
}
You will need to make similar modifications to txtNumberOfTickets_TextChanged1 to ensure the user has entered valid text.
simply use something like
To use IsNumeric in C#, add a reference to Microsoft.VisualBasic.dll then
if (Information.IsNumeric(value))
{
DoSomthing();
}
else
{
DoSomethingElse();
}
UPDATE
OPEN VISUAL STUDIO ==> YOUR PROJECT
Click on solution and add reference, choose Microsoft.VisualBasic.dll confrim the new reference will be add to your references into the project.
Go at the top of your page and declare the import statemnet for Microsoft.VisualBasic.dll alias
using Microsoft.VisualBasic.dll;
then where you need to check the value of your textbox
if (Information.IsNumeric(yourtextbox.text.trim()))
{
//case true alias your value is numeric
//do what you need here like assing value to a var or any
//else
}
else
{
//put your logic here in case result is false and value
//is not numeric
}

Login Code works for admin and user , but did not show error when login with wrong id or pass

I am creating a program for my final project , i have set-up a database , everything works fine , but the only thing i couldn't finish is the Login system.
Both Users and admin will log through the same form.
When i enter an admin id , it will login and say "hello admin" , and user the same.
but when i enter a non-existent id , it wouldn't show the error..
here's my code -
private void button1_Click(object sender, EventArgs e)
{
try
{
string userNameText = txtUser.Text;
string passwordText = txtPass.Text;
string isAdmin = "yes";
string isNotAdmin = "no";
if (!(string.IsNullOrEmpty(txtUser.Text)) && !(string.IsNullOrEmpty(txtPass.Text)))
{
SqlConnection SCScon = new SqlConnection();
SCScon.ConnectionString = "Data Source=PEWPEWDIEPIE\\SQLEXPRESS;Initial Catalog=master;Integrated Security=True";
SqlCommand cmd = new SqlCommand("SELECT ISNULL(SCSID, '') AS SCSID, ISNULL(SCSPass,'') AS SCSPass, ISNULL(isAdmin,'') AS isAdmin FROM SCSID WHERE SCSID='" + txtUser.Text + "' and SCSPass='" + txtPass.Text + "'", SCScon);
SCScon.Open();
SqlDataReader dr = cmd.ExecuteReader();
while (dr.Read())
{
if (this.CompareStrings(dr["SCSID"].ToString(), txtUser.Text) &&
this.CompareStrings(dr["SCSPass"].ToString(), txtPass.Text) &&
this.CompareStrings(dr["isAdmin"].ToString(), isAdmin))
{
MessageBox.Show("Hello " +txtUser.Text , "Admin" , MessageBoxButtons.OK , MessageBoxIcon.Information);
_Adminform.Show();
this.Hide();
}
else if (this.CompareStrings(dr["SCSID"].ToString(), txtUser.Text) &&
this.CompareStrings(dr["SCSPass"].ToString(), txtPass.Text) &&
this.CompareStrings(dr["isAdmin"].ToString(), isNotAdmin))
{
MessageBox.Show("Welcome " + txtUser.Text , "User");
_userform.Show();
this.Hide();
}
else
{
MessageBox.Show("Wrong ID/Pass");
}
}'
}
}
catch (Exception ex)
{
MessageBox.Show("error2" + ex);
}
}
Problem : You are checking for invalid user inside the whle loop. loop enters when only required user is matched. so if invalid user credentials are given it will not enter the loop hence you could not see the Invalid User MessageBox.
Solution : you can check the dr.Read() return value, if it is true means it has row with the user (either admin or normal-user).
if(dr.Read())
{
if (this.CompareStrings(dr["SCSID"].ToString(), txtUser.Text) &&
this.CompareStrings(dr["SCSPass"].ToString(), txtPass.Text) &&
this.CompareStrings(dr["isAdmin"].ToString(), isAdmin))
{
MessageBox.Show("Hello " +txtUser.Text , "Admin" , MessageBoxButtons.OK , MessageBoxIcon.Information);
_Adminform.Show();
this.Hide();
}
else if (this.CompareStrings(dr["SCSID"].ToString(), txtUser.Text) &&
this.CompareStrings(dr["SCSPass"].ToString(), txtPass.Text) &&
this.CompareStrings(dr["isAdmin"].ToString(), isNotAdmin))
{
MessageBox.Show("Welcome " + txtUser.Text , "User");
_userform.Show();
this.Hide();
}
}
else
{
MessageBox.Show("Wrong ID/Pass");
}
if the User name and password does not match, the line SqlDataReader dr = cmd.ExecuteReader(); returns no rows, so it will not enter the while(dr.Read()) and hence, will not enter the else inside while(dr.Read()).
You will need to put the MessageBox.Show("Wrong ID/Pass"); outside the while loop.
This is the code inside the form:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Windows.Forms;
namespace LoginDialogForm
{
public partial class Login_Dialog_Form1 : Form
{
public Login_Dialog_Form1()
{
InitializeComponent();
}
private bool ValidateUsername()
{
//TODO: add code to validate User Name.
return true;
}
private bool ValidatePassword()
{
if (!ValidateUsername())
{
MessageBox.Show("Wrong Username", "Invalid Username", MessageBoxButtons.OK, MessageBoxIcon.Error);
return false;
}
else
{
//TODO: add code to validate password.
if (false)
{
MessageBox.Show("Wrong Password", "Invalid Password", MessageBoxButtons.OK, MessageBoxIcon.Error);
return false;
}
else
return true;
}
}
}
private void btnOk_Click(object sender, EventArgs e)
{
if (!ValidatePassword())
{
txtUserName.Clear();
txtPassword.Clear();
return;
}
else
{
this.DialogResult = DialogResult.OK;
this.Close();
}
}
private void btnCancel_Click(object sender, EventArgs e)
{
txtUserName.Clear();
txtPassword.Clear();
this.Close();
}
}
This the controls and their relevant properties:
//
// btnOk
//
Name = "btnOk";
Text = "&Ok";
btnOk.Click += new System.EventHandler(this.btnOk_Click);
//
// btnCancel
//
DialogResult = System.Windows.Forms.DialogResult.Cancel;
Name = "btnCancel";
Text = "&Cancel";
btnCancel.Click += new System.EventHandler(this.btnCancel_Click);
//
// txtUserName
//
Name = "txtUserName";
//
// txtPassword
//
PasswordChar = '*';
Name = "txtPassword";
//
// label1
//
Name = "label1";
Text = "Username";
//
// label2
//
Name = "label2";
Text = "Password";
//
// LogoPictureBox
//
LogoPictureBox.Name = "LogoPictureBox";
LogoPictureBox.TabStop = false;
//
// LoginForm1
//
AcceptButton = this.btnOk;
CancelButton = this.btnCancel;
ControlBox = false;
FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedDialog;
Name = "LoginForm1";
ShowInTaskbar = false;
StartPosition = System.Windows.Forms.FormStartPosition.CenterParent;
Text = "Login Form";
This the code to call the form:
private void Form1_Load(object sender, EventArgs e)
{
Login_Dialog_Form1 NewLogin = new Login_Dialog_Form1();
DialogResult Result = NewLogin.ShowDialog();
switch (Result)
{
case DialogResult.OK:
//do stuff
break;
case DialogResult.Cancel:
this.Close();
break;
}
}

If Statement true then Redirect

Hello im learning c# at the moment and wish to If a statement is true then redirect to another ASpage so far with no luck.
My attempt is below, what the code does is check the text boxes to see if they have a value and if they do then it will save that record in the database as a new user.The code works its just the redirect at the end that isn't working.
Any help would be great
protected void Button2_Click(object sender, EventArgs e)
{
if (!String.IsNullOrWhiteSpace(txtTitle.Text))
{
user.Title = txtTitle.Text;
}
if (!String.IsNullOrWhiteSpace(txtFirstName.Text))
{
user.Forename = txtFirstName.Text;
}
if (!String.IsNullOrWhiteSpace(txtSurname.Text))
{
user.Surname = txtSurname.Text;
}
if (!String.IsNullOrWhiteSpace(txtUsername.Text))
{
user.Username = txtUsername.Text;
}
// call save function at end of statements
if (!String.IsNullOrWhiteSpace(txtAddress.Text))
{
user.Address1 = txtAddress.Text;
}
if (!String.IsNullOrWhiteSpace(txtAddress2.Text))
{
user.Address2 = txtAddress.Text;
}
if (!String.IsNullOrWhiteSpace(txtPostcode.Text))
{
user.PostCode = txtPostcode.Text;
}
if (!String.IsNullOrWhiteSpace(txtCode.Text))
{
user.CountryCode = txtCode.Text;
}
if (!String.IsNullOrWhiteSpace(txtEmail.Text))
{
user.Email = txtEmail.Text;
}
//if (!string.IsNullOrWhiteSpace(txtDate.Text))
//{
// DateTime _entrydate;
// if (DateTime.TryParse(txtDate.Text, out _entrydate))
// {
// user.EntryDate = _entrydate;
// }
//}
user.CompanyID = AppSession.Company.ID;
user.Status = 1;
user.PasswordHash = "test";
user.EntryDate = DateTime.Now;
user.UpdateDate = DateTime.Now;
user.Deleted = false;
bool result = userDao.SaveNewUser(user);
if (result == true)
{
Response.Redirect("User/List/");
}
}
}
}
You need to Redirect to another ASPX page, not a directory.
Something like
Response.Redirect("User/List/UserList.aspx");
Private static string CheckValues(TextBox t)
{
if(!string.IsnullOrEmpty(t.Text.Trim())
{
return t.Text;
}
}
protected void Button2_Click(object sender, EventArgs e)
{
user.Title =CheckValues(txtTitle.Text);
user.Forename = CheckValues(txtFirstName.Text);
user.Surname = CheckValues(txtSurname.Text);
user.Username = CheckValues(txtUsername.Text);
user.Address1 = CheckValues(txtAddress.Text);
user.Address2 = CheckValues(txtAddress.Text);
user.PostCode = CheckValues(txtPostcode.Text);
user.CountryCode = CheckValues(txtCode.Text);
user.Email = CheckValues(txtEmail.Text);
if(CheckValues(txtDate.Text))
{
DateTime _entrydate;
if (DateTime.TryParse(txtDate.Text, out _entrydate))
{
user.EntryDate = _entrydate;
}
}
bool result = userDao.SaveNewUser(user);
if (result)
{
Response.Redirect("~/User/List/somepage"); //~ for root directory , if there is any page use that or use the exact url here.
}
}
Kindly note the above url format will only work if you have URL Rewriting/Routing in your app

How to correct my null exception?

I have created a contact form using c# and web services. I would like to get an alert message if the user hasn't filled his name or when his name is a number. This is my C# code:
public partial class Default2 : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void Button1_Click(object sender, EventArgs e)
{
Validation.WebService validate = new Validation.WebService();
bool ismail = validate.isEmail(TextBox2.Text);
if (!ismail)
{ Label1.Text = "your mail is wrong!!"; }
Validation.nameVal valid = new Validation.nameVal();
bool isname = valid.isName(TextBox1.Text);
if (!isname )
{ Label2.Text = "Your name is wrong!!"; }
else if (isname==null)
{ Label2.Text = "Please fill in your name"; }
if (isname && ismail)
{
{ Label1.Text = null; Label2.Text = null;
Label3.Text = "Your message has been send!";}
}
}
}
With this code, I have a null exception.
From your comment that the exception is on the line:
bool isname = valid.isName(TextBox1.Text);
then either valid or TextBox1 is null. Given that the line before is:
Validation.nameVal valid = new Validation.nameVal();
this points to it being the latter.
You need to check that TextBox1 isn't null before de-referencing it or make sure that it is initialised correctly.
Try changing the last bit of the code where you set Label1.Text and Label2.Text to null to:
Label1.Text = String.Empty; Label2.Text = String.Empty;
I am guessing that perhaps the validate is failing, or, possibly the setting of the label text to null is causing the issues. The code below should help
Validation.WebService validate = new Validation.WebService();
bool ismail = (!string.IsNullOrEmpty(Textbox2.Text)) && validate.isEmail(TextBox2.Text);
if (!ismail)
{
Label1.Text = "your mail is wrong!!";
}
Validation.nameVal valid = new Validation.nameVal();
bool isname = (!string.IsNullOrEmpty(Textbox1.Text)) && valid.isName(TextBox1.Text);
if (!isname)
{
Label2.Text = "Your name is wrong!!";
}
else if (string.IsNullOrEmpty(Textbox1.Text))
{
Label2.Text = "Please fill in your name";
}
if (isname && ismail)
{
{
Label1.Text = "";
Label2.Text = "";
Label3.Text = "Your message has been send!";
}
}
}

Categories

Resources