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"]);
Related
In my C# application I use 2 connection strings (application_cs, users_cs). To change these connection strings I use:
private static void SetProviderConnectionString(string connectionString)
{
var connectionStringFieldM =
Membership.Provider.GetType().GetField("_sqlConnectionString",
BindingFlags.Instance | BindingFlags.NonPublic);
var connectionStringFieldR = Roles.Provider.GetType().GetField("_sqlConnectionString",
BindingFlags.Instance | BindingFlags.NonPublic);
var connectionStringFieldP = ProfileManager.Provider.GetType().GetField("_sqlConnectionString",
BindingFlags.Instance | BindingFlags.NonPublic);
connectionStringFieldM.SetValue(Membership.Provider, connectionString);
connectionStringFieldR.SetValue(Roles.Provider, connectionString);
connectionStringFieldP.SetValue(ProfileManager.Provider, connectionString);
}
public static void SetProviderUsers()
{
SetProviderConnectionString(ConfigurationManager.ConnectionStrings["users_cs"].ConnectionString);
}
public static void SetProviderApp()
{
SetProviderConnectionString(ConfigurationManager.ConnectionStrings["application_cs"].ConnectionString);
}
So in my code whenever I want to add a user I do this:
public int CreateUser(int stid, int cid, int usrId, string email, string tel, string mob, string username,
bool create, bool prime)
{
int result = 0;
Guid userid = new Guid();
DALUsers.UserDBDataContext dc = new DALUsers.UserDBDataContext();
DAL.AppDataContext d = new DAL.AppDataContext();
BLL.Security.SetProviderUsers();
if (create) //create the user first
{
string question = "1";
string answer = "1";
bool isAproved = true;
string password = System.Web.Security.Membership.GeneratePassword(8, 2);
MembershipCreateStatus cs = new MembershipCreateStatus();
MembershipUser newUser = Membership.CreateUser(username, password, email, question, answer, isAproved, out cs);
Membership.UpdateUser(newUser);
Roles.AddUserToRole(username, "User_x");
if (cs == MembershipCreateStatus.Success)
{
result = 1;
}
else
X.MessageBox.Info("Error", "Cannot create user due to :" + cs.ToString(), UI.Danger).Show();
}
//at this point we have the user created either way.
// return userid;
var id = (from i in dc.aspnet_Users where i.UserName.CompareTo(username) == 0 select i.UserId);
if (id.Count() == 1)
{
userid = id.First();
bool contin = true;
var fulname = (from i in dc.Clients where i.id == usrId select i).First();
if (String.IsNullOrEmpty(fulname.Mobile)) fulname.Mobile = mob;
fulname.Email = email;
fulname.ModifiedBy = HttpContext.Current.User.Identity.Name;
fulname.ModifiedDate = DateTime.Now;
dc.SubmitChanges();
DateTime dt = DateTime.Now;
DALUsers.CIUser usr = new DALUsers.CIUser();
var existing = (from i in dc.CIUsers where i.UserName.CompareTo(username) == 0 && i.cid == cid select i);
if (existing.Count() > 0)
{
X.MessageBox.Info("Warning", "UserName already exists . Please try another!", UI.Warning).Show();
contin = false;
}
else
{
dc.CIUsers.InsertOnSubmit(usr);
dc.SubmitChanges();
}
if (contin)
{
DALUsers.CIUser usrNew = new DALUsers.CIUser();
var approved = (from k in dc.aspnet_Memberships //if user is not approved
where k.UserId == userid
select k).FirstOrDefault();
if (approved.IsApproved == false)
{
approved.IsApproved = true;
}
ProfileBase profile = ProfileBase.Create(username);
profile.SetPropertyValue("Mobile", mob);
profile.SetPropertyValue("Email", email);
profile.Save();
usrNew.UserId = usrId;
usrNew.cid = cid;
usrNew.FullName = fulname.LastName + " " + fulname.FirstName;
usrNew.Role = "User_x";
usrNew.SignRights = prime;
usrNew.IsPrime = prime;
usrNew.stid = stid;
usrNew.UserName = username;
usrNew.UserId = userid;
usrNew.CreatedDate = DateTime.Now;
usrNew.CreatedBy = HttpContext.Current.User.Identity.Name;
dc.CIUsers.InsertOnSubmit(usrNew);
dc.SubmitChanges();
result = 1;
X.MessageBox.Info("Success", "The user has been successfully added", UI.Success).Show();
}
}
else
X.MessageBox.Info("Error", "Could not find the user", UI.Danger).Show();
BLL.Security.SetProviderApp();
return result;
}
EDIT
I just saw that in my code there is this line:
DALUsers.aspnet_User user = new DALUsers.aspnet_User();
But the variable user is not used anywhere else in the code. Probably it has been left there... And its the only variable named user in my code. Is that causing the issue? But then why only on the production server?
EDIT
The weird part is that when I run my application from visual studio locally it works as a charm. But when I am adding a user in the application running on the production server when I am trying to add the second user it fails and I receive this error:
Value cannot be null. Parameter name: user
And if I try to login to my application after that it fails. I have to restart my website from iis to be able to login again.
Any ideas?
Well I cant find the error in your code but if you say that this error occurs only in server and that you are sure that your files are synched between server and your local machine, then probably the error lies in your web.config. Take a look
I am currently having trouble with a piece of code I have been writing lately. The aim of the code is to read a text file with user details, check their login information and then allow them to login. However I am having trouble and when I execute the code. Only the last row in the text file is "working". The program can register that there is more tahn one username, however it always thinks the password is incorrect. I dont know how to better explain this. If you have any questions please ask and thanks for helping.
This is my code
private void button1_Click_1(object sender, EventArgs e)
{
string UserList;
string UsernameString;
UserList = File.ReadAllText(#"C:\Users\dagostinom18\Documents\Visual Studio 2015\Projects\Assignment\Assignment\users.txt");
int iLength = UserList.Length;
string[,] users = new string[iLength, iLength];
foreach (var row in UserList.Split('\n'))
{
int y = 0;
foreach (var col in row.Trim().Split(','))
{
int x = 0;
users[x, y] = col.Trim();
if (users[x, y] == Username.Text)
{
UsernameCheck = true;
UsernameString = Username.Text;
RowNumber = x;
}
y++;
}
}
if (UsernameCheck == false)
{
LoginError.Text = "No such username";
}
else
{
if (Password.Text == users[RowNumber, 1])
{
Main f3 = new Assignment.Main();
Form1 f4 = new Assignment.Form1();
f3.Show();
MessageBox.Show("Welcome ");
}
else
{
LoginError.Text = "Incorect Password";
}
}
}
This is what my text file looks like
matt, 12345
admin, 67890
test, abcde
Here how your code should look in more clean state.
string password = PasswordTxt.Text//you should use your control names
string userName = UserNameTxt.Text//your control
bool validUsers = false;
foreach (var line in File.ReadLines("#"C:\Users\dagostinom18\Documents\Visual Studio 2015\Projects\Assignment\Assignment\users.txt""))
{
string textUserName = line.Split(',')[0].Trim();
string textPassword = line.Split(',')[1].Trim();
validUsers = textUserName == userName && textPasword == password;
}
if(!validUsers)
{
//show error, user credentials are not valid
return;
}
//go log in.
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.
I am having difficulties on getting my insert method to work correctly. I am new to back end development so any suggestions or comments will be helpful.
public Boolean insertDefaultUser()
{
Boolean flag = true;
Users newUser = new Users();
newUser.alias = "bulby";
newUser.password = "chicken";
newUser.email = "r#hot.com";
dbc.Users.AddObject(newUser); // ERROR !
dbc.SaveChanges();
return flag;
}
However, on the "add object line" it gives me the follow error --->
Error "The best overloaded method match for System.Data.Objects.ObjectSet<Guild_Chat.User>.AddObject(Guild_Chat.User)' has some invalid arguments ".
Try adding the actual entity type Guild_Chat.User, for example:
public bool InsertDefaultUser()
{
try
{
Guild_Chat.User newUser = new Guild_Chat.User
{
alias = "bulby",
password = "chicken",
email = "r#hot.com"
};
dbc.Users.AddObject(newUser);
dbc.SaveChanges();
return true;
}
catch(Exception e)
{
return false;
}
}
I'm still very new to C# and would appreciate any help with my code.
I'm creating a user profile page and am getting the error "Nullable object must have a value" on "photo = (byte)user.Photo;" in the following code. I assume it's because I declared "photo = 0;" How do I add a value to it?
Update:
Here's the entire method
public static bool UserProfile(string username, out string userID, out string email, out byte photo)
{
using (MyDBContainer db = new MyDBContainer())
{
userID = "";
photo = 0;
email = "";
User user = (from u in db.Users
where u.UserID.Equals(username)
select u).FirstOrDefault();
if (user != null)
{
photo = (byte)user.Photo;
email = user.Email;
userID = user.UserID;
return true; // success!
}
else
{
return false;
}
}
}
I am assuming that you are getting error for this one...
if (user != null)
{
photo = (byte)user.Photo;
email = user.Email;
userID = user.UserID;
return true; // success!
}
else
{
return false;
}
If yes then just replace it with...
if (user != null)
{
photo = user.Photo== null ? null : (byte)user.Photo;
email = user.Email;
userID = user.UserID;
return true; // success!
}
else
{
return false;
}