Reputation: 35
How to resolve this Error String Must be exactly one character long . i am sharing this function please look into this and resolve this issue .
i am highlighting line you can see this line . And how to solve this issue if can we convert char to string or something else.
Function
public DataTable mlogin(string username, string password)
{
string constring = ConfigurationManager.ConnectionStrings["Real"].ConnectionString;
SqlConnection con = new SqlConnection(constring);
password = Cryptographer.Encrypt(password);
con.Open();
if ( char.IsNumber( Convert.ToChar(username))) //String must be exactly one character long
{
cmd = new SqlCommand("select MD.MembershipID, MembershipName, address, ISNULL(FD.FileID,'') as FileID,ISNULL(Sec.SectorName, '') as SectorName, ISNULL(I.PlotNo, '') as PlotNo, MD.ClientPic from MemberMaster MM " +
" inner join MembersDetail MD on MD.MemberShipID = MM.MemberShipID and MD.Srno = 1 " +
" inner join MasterFileDetail FD on FD.MembershipID = MM.MemberShipID and FD.IsOwner = 1 and FD.IsTransfered = 1 " +
" inner join MasterFile FM on FM.FileID = FD.FileID and FM.Cancel = 0 " +
" inner join Sectors Sec on Sec.Phase_ID = FM.PhaseId and Sec.Sector_ID = FM.Sector_ID " +
" inner join PlotsInventory I on I.Phase_ID = FM.PhaseId and I.Plot_ID = FM.Plot_ID " +
" where MM.MemberShipID = '" + username + "' and MM.IsApproved = 1 and RTRIM(MM.LoginPwd) = '" + password + "' and MM.IsActive = 1 " +
" order by FD.FileID", con);
}
else
{
cmd = new SqlCommand("select User_Id, User_Name,User_Type, Group_Id from BriskSecurity.dbo.Users where User_Login='" + username + "' and User_password='" + password + "' ", con);
}
cmd.CommandType = CommandType.Text;
cmd.Parameters.AddWithValue("@MembershipID",username);
cmd.Parameters.AddWithValue("@LoginPwd", password);
DataTable mDT_User = new DataTable();
SqlDataAdapter da = new SqlDataAdapter(cmd);
da.Fill(mDT_User);
con.Close();
return mDT_User;
}
Upvotes: 0
Views: 1409
Reputation: 38767
What you're doing is fundamentally wrong.
Consider the username "John". Can you convert a 4 character string into a single char? No. You can't use this to validate if the whole username is a number.
Instead, you have two options:
(1) Validate that each char of the username is numeric:
if (username.All(c => char.IsNumber(c)))
{
(2) Parse it to a number (assuming it can be expressed as a number and leading zeroes aren't important)
if (int.TryParse(username, out var usernameAsInt))
{
Next, I recommend looking at parameterized SQL queries.
Imagine the following query:
"SELECT * FROM users WHERE username = '" + username + "' AND password = '" + password + "'"
What happens if my username is ' OR username = 'administrator'; --
? The query becomes this:
SELECT * FROM users WHERE username = '' OR username = 'administrator'; -- ' AND password = ''
Everything after the -- becomes a comment. You can learn more about parameterizing SQL queries here.
Upvotes: 6