How to pass a variable to another namespace? - c#

I have to pass a count value to another namespace here. I have 2 classes Select.cs and Value.cs. Select.cs has the following code:
public bool Login(string UserName, string Password)
{
string strinvselect = string.Format("select * from newlog where
pass='{0}'", Password);
DataTable dtlog = ExecuteStatement(strinvselect);
if (dtlog.Rows.Count == 1)
{
string strvalue = string.Format("Select * FROM login WHERE uid=
'{0}'", UserName);
DataTable newlogin = ExecuteStatement(strvalue);
try
{
if (newlogin.Rows.Count == 1)
{
loginStatus = true;
}
}
catch (Exception ex)
{
loginStatus = false;
}
return loginStatus;
}
}
I have to create a count value if(newlogin.Rows.Count == 1), count=1 and this value should be available in Value.cs to check a functionality.
In Value.cs a function getdetails() is called. Here I need to check
if (count == 1)
{
getdetails();
}
else
{
// call another function
}

I found the answer:
Namespaces are not really relevant here, the issue is that you need to access the variable from a different class. The way you have "global" variables that are specific to the user is the Session, so store the value in a Session variable and have your other class access the Session variable.
HttpContext.Current.Session["myData"] = "somevalue";
Value function
string x;
if (Session["myData"] == null)
{
// handle the data not being set
}
else
{
x = (string)HttpContext.Current.Session["myData"].ToString(); ;
}

You can check for query for count outside Login ( basically wherever you need it ) then pass it as "username + count" (you will need to split it) to login first parameter as you can avoid checking count inside Login again.

Related

Is there a way that I can keep a user logged in throughout multiple forms after an initial login

I am fairly new to coding in C# and using windows forms applications and SQLite for databases, and I was wondering if there way that I can keep a user logged in and display said user's ID on different forms to show that they are logged in. The project itself is an ordering system and I wish for a customer to login to perform any purchases so that it can be logged as part of a management report. The code is below if it is of any help.
int charlengthusername= usernametextbox.Text.Length;
int charlengthpassword = passwordtextbox.Text.Length;
if (charlengthusername <= 4 || charlengthusername >= 6 || charlengthpassword >=13||String.IsNullOrEmpty(usernametextbox.Text)||String.IsNullOrEmpty(passwordtextbox.Text))
{
MessageBox.Show("Details Entered Don't Meet The Expected Character Length Requirements. Try Again.");
usernametextbox.Clear();
passwordtextbox.Clear();
}
//make another if for user and pass matching
//change else below to be inside of username and password match if statement so that it will only send to custmainmenu when username and password has been matched
else
{
sqlite_conn = new SQLiteConnection("Data Source=CustomerDatabase.db; Version = 3; New = True; Compress = True;");
sqlite_conn.Open();
SQLiteDataReader sqlite_datareader;
string user = usernametextbox.Text;
string pass = passwordtextbox.Text;
sqlite_cmd = sqlite_conn.CreateCommand();
sqlite_cmd.Connection = sqlite_conn;
sqlite_cmd.CommandText = "SELECT * FROM TblCustomer where CustRandID='" + usernametextbox.Text + "' AND CustPassword='" + passwordtextbox.Text + "'";
sqlite_datareader = sqlite_cmd.ExecuteReader();
if (sqlite_datareader.Read())
{
MessageBox.Show("Login Successful! ");
this.Hide();
var openmainmenu = new CustomerMainMenu();
openmainmenu.Closed += (t, args) => this.Close();
openmainmenu.Show();
}
else
{
MessageBox.Show("Incorrct Details! Try Again! ");
this.Hide();
var spenmainmenu = new CustomerLogin();
spenmainmenu.Closed += (s, args) => this.Close();
spenmainmenu.Show();
}
sqlite_conn.Close();
}
You can use static members in a class and reach them from any form.
class UserInfo {
public static String UserName ="";
public static bool IsLoggedIn = false;
}
You need to set values inside of login successful block like that:
UserInfo.IsLoggedIn = true;
UserInfo.UserName = "Uday Patel";
The simplest approach would be to just store the validated username/password in a public static property in a static class.
public static class AppInfo {
public static string Username = "";
}
// ...
MessageBox.Show("Login Successful! ");
AppInfo.Username = user;
You can then access that Username (and any other global data your app might need) from AppInfo (which you could name something else, of course).

An object reference is required for the non-static field, method, or property 'System.Web.UI.Page.RouteData.get'

I am working on asp.net application. In this application i have used Url rewrinting method to show pages in the browser. Whenever any wants to edit any record i have checked whether the 'ID' to be edit is null or not as:
if (Page.RouteData.Values["ID"] != null)
{
}
If this condition will be true then it means the wants to edit the record of id passed through
Page.RouteData.Values["ID"]
from the form all the data is being displayed. and user select any one of them.the above "if" condition works fine when it is not used in any webMethod but it is used in the webmethod the error comes.
My webMethod is
[System.Web.Script.Services.ScriptMethod()]
[System.Web.Services.WebMethod(e)]
public static string SaveData(string Category,string SubCategory,string ProductType)
{
try
{
ProductBrand objBrand = new ProductBrand();
DataTable dt = new DataTable();
ProductType objProductType = new ProductType();
objProductType.SubCategoryID = Convert.ToInt64(SubCategory);
objProductType.ProductTypeName = ProductType;
if (Page.RouteData.Values["ID"] != null)
{
objProductType.TypeID = Convert.ToInt64(Page.RouteData.Values["ID"].ToString());
objProductType.Flag = "U";
else
{
dt = new ProductType().SelectByCategory(objProductType.SubCategoryID, objProductType.ProductTypeName);
if (dt.Rows.Count > 0)
{
objProductType.Flag = "D";
}
else
{
objProductType.Flag = "I";
}
}
if (objProductType.Flag.Equals("D"))
{
objBrand.BrandID = 2;
}
else
{
int retval = new ProductType().Insert(objProductType);
if (retval > 0)
{
objBrand.BrandID = 1;
}
else
{
objBrand.BrandID = 0;
}
}
return objBrand.BrandID.ToString();
}
catch (Exception ex)
{
throw (ex);
}
}
The above webmethod has been written to insert data into datbase using jquery. In the above webmethod in the statement "if (Page.RouteData.Values["ID"] != null)" the error is showing as
An object reference is required for the non-static field, method, or property 'System.Web.UI.Page.RouteData.get'
But when i use the above condition outside of webmethod this error is not coming. Please help me someone here.
try remove "static" in function SaveData and call like instance
var xx = new YOURCLASS();
xx.SaveData(xx,yy,zz);
How do I call a non-static method from a static method in C#?

Variable always returning true

I have this in my button click event:
protected void btn_login_Click(object sender, EventArgs e)
{
authentication auth = new authentication();
bool emailExists = auth.checkEmail(System.Convert.ToString(txt_email.Text));
if (emailExists == true)
{
btn_create.Text = "Email doesnt exist";
}
else
{
btn_create.Text = "Email exists";
}
}
It sends the email to my checkEmail method which is in my authentication class:
public bool checkEmail(string email)
{
bool emailExists = false;
usersTableAdapters.UsersTableAdapter user = new usersTableAdapters.UsersTableAdapter();
users.UsersDataTable userDataTable = user.checkEmail(email);
if (userDataTable.Rows.Count == 0)
{
emailExists = false;
}
else
{
emailExists = true;
}
return emailExists;
}
The checkEmail query is "SELECT COUNT(email) AS email FROM People WHERE (email = ?)"
However when I debug, it always falls through the if(emailExists == true) statement even when the email already exists in my DB, does anyone know why?
your query you entered will always have 1 result. If you want to continue using that query, you should check the first column ("email") of the first result and check to see if that is == 0 or not.
can't add code markup in comments, so reposting how I would rewrite the checkEmail method: (assuming the how the UsersTableAdapter type is setup)
public bool checkEmail(string email)
{
usersTableAdapters.UsersTableAdapter user = new usersTableAdapters.UsersTableAdapter();
users.UsersDataTable userDataTable = user.checkEmail(email);
return userDataTable.Rows[0][0] > 0;
}
I figured out I would have to check the index of the row which in this case is 0 and then retrieve and store the value from the email column into an int
DataRow row = userDataTable.Rows[0];
int rowValue = System.Convert.ToInt16(row["email"]);

Method for querystring not returning value

I am passing some value from one page to another page via query string, it passes the values correctly and then passes to the stored procedure succesfully but typing the Request.QueryString["something"] again and again is very irritating, so I created a method for it, but the method does not return/passes any value and the nullreference exception is thrown.
protected void Page_Load(object sender, EventArgs e)
{
try
{
using (Property_dbDataContext context = new Property_dbDataContext())
{
_errMsg.Enabled = false;
_errMsg.Visible = false;
var find_prop = context.find_property(val("city"), val("type"), val("subtype"), val("bedrooms"), val("size_unit"), Convert.ToInt32(val("area_from")), Convert.ToInt32(val("areato")), Convert.ToInt32(val("pricefrom")), Convert.ToInt32(val("priceto"))).ToList();
//code above does not return any value
//var find_prop = context.find_property(Request.QueryString["city"], Request.QueryString["type"], Request.QueryString["subtype"], Request.QueryString["bedrooms"], Request.QueryString["size_unit"], Convert.ToInt32(Request.QueryString["area_from"]), Convert.ToInt32(Request.QueryString["areato"]), Convert.ToInt32(Request.QueryString["pricefrom"]), Convert.ToInt32(Request.QueryString["priceto"])).ToList();
//code above return value from the database but its a long procedure
rptr_properties.DataSource = find_prop;
rptr_properties.DataBind();
}
}
catch(Exception ex)
{
_errMsg.Enabled = true;
_errMsg.Visible = true;
_errMsg.Text = "Sorry! Property not found." + ex;
}
}
public string val(string a)
{
return Request.QueryString["" + a + ""].ToString();
}
You need to make sure the item exists before trying to access it:
public string val(string a)
{
if(Request.QueryString[a] != null)
return Request.QueryString[a].ToString();
return string.Empty;
}
In reference to your comment; this in particular:
Convert.ToInt32(val("area_from"))
Is going to cause a problem because the default value is an empty string.
Something like this should work for now though:
public string ValToString(string a)
{
if(Request.QueryString[a] != null)
return Request.QueryString[a].ToString();
return string.Empty;
}
public int ValToInt32(string a)
{
if(Request.QueryString[a] != null)
return Convert.ToInt32(Request.QueryString[a]);
return 0;
}
You would then modify your find code:
var find_prop = context.find_property(ValToString("city"), ValToString("type"), ValToString("subtype"), ValToString("bedrooms"), ValToString("size_unit"), Convert.ToInt32(val("area_from")), Convert.ToInt32(val("areato")), ValToInt32("pricefrom"), ValToInt32("priceto")).ToList();
This will work
public string val(string a)
{
return Request.QueryString[a];
}
Better method for converting a querystring value to an int(32):
public int GetIntFromQueryString(string key)
{
int result = int.MinValue;
if(Request.QueryString[key] != null)
{
int.TryParse(Request.QueryString[key].ToString(), out result);
}
return result;
}
If TryParse fails to convert the value the method will return 'int.MinValue', you can then check the returned value does not equal 'int.MinValue' and go from there.

Not all code paths return a value

I get an error not all code paths return a value?
public string Authentication(string studentID, string password) // this line?
{
var result = students.FirstOrDefault(n => n.StudentID == studentID);
//find the StudentID that matches the string studentID
if (result != null)
//if result matches then do this
{
//----------------------------------------------------------------------------
byte[] passwordHash = Hash(password, result.Salt);
string HashedPassword = Convert.ToBase64String(passwordHash);
//----------------------------------------------------------------------------
// take the specific students salt and generate hash/salt for string password (same way student.Passowrd was created)
if (HashedPassword == result.Password)
//check if the HashedPassword (string password) matches the stored student.Password
{
return result.StudentID;
// if it does return the Students ID
}
}
else
//else return a message saying login failed
{
return "Login Failed";
}
}
if the result is not null but the result.Password != HashedPassword you're not returning anything.
You should change to something like:
...
if (HashedPassword == result.Password)
{
return result.StudentID;
// if it does return the Students ID
}
return "Invalid Password";
...
The problem is that your first if statement doesn't ensure the returning of a value, due to the nested if statement. Imagine you have result set to a value (not null) and your hashed password and supplied password do not match, if you follow that logic through you will fail to hit a return statement.
You should either add an else clause to your nested if statement like so:
if (HashedPassword == result.Password)
//check if the HashedPassword (string password) matches the stored student.Password
{
return result.StudentID;
// if it does return the Students ID
}
else
{
return "Login Failed";
}
or more desirably, remove the else statement you already have so the function ends with returning the login failed:
if (result != null)
{
//....
}
return "Login Failed";
...with this second approach you do no need to worry about using the else because if all your other conditions are satisfied, the nested return statement will end the function anyway. Try to think of this final return as the default action if any of the authentication steps fail
Another note to make on your code is that it is not ideal practise to be returning a mix of data in such a way. i.e. the result could be a student ID or it could be an error message. Consider creating a dedicated result class with multiple properties that the calling code can check to see the status of the logic validation. A class something like the following would be a good start:
public class LoginResult
{
//determines if the login was successful
public bool Success {get;set;}
//the ID of the student, perhaps an int datatype would be better?
public string StudentID {get;set;}
//the error message (provided the login failed)
public string ErrorMessage {get;set;}
}
(saying all that though, your calling code already appears to be aware of the studentID anyway)
remove the else. Just do
if(result != null) {
...
}
return "Login Failed";
you should also return something in case of:
if (HashedPassword != result.Password)
put an else in the inner if
i have made some changes in your code. try it.
public string Authentication(string studentID, string password)
{
var result = students.FirstOrDefault(n => n.StudentID == studentID);
var yourVar;
if (result != null)
{
byte[] passwordHash = Hash(password, result.Salt);
string HashedPassword = Convert.ToBase64String(passwordHash);
if (HashedPassword == result.Password)
{
//return result.StudentID;
yourVar = result.StudenID;
// if it does return the Students ID
}
}
else
//else return a message saying login failed
{
yourVar = "Login Failed";
}
return yourVar;
}

Categories