SELECT statement with COUNT Always Returns 0 - c#

Don't know why I can't reply to people on here with only a small amount of comment text, but my revised code exceeds that so I'm posting new.
This web service always returns 0. If I run it in SSMS it returns 3... not sure why, any ideas?
string ConnString = "Removed";
String query = "DECLARE #userSID varchar(255) SELECT COUNT(AD_SID) As ReturnCount FROM AD_Authorization WHERE AD_SID = #userSID ";
using (OleDbConnection conn = new OleDbConnection(ConnString))
{
using (OleDbCommand cmd = new OleDbCommand(query, conn))
{
cmd.Parameters.AddWithValue("userSID", SpartaCrypto.SpartaEncryptAES(userSID.ToString(), "s3cret!"));
conn.Open();
int returnCount = (Int32)cmd.ExecuteScalar();
conn.Close();
if (returnCount > 1)
{
return 1;
}
else
{
return 0;
}
}
}

Your query is not a good OLEDB parameterized query.
Try this instead:
"SELECT COUNT(AD_SID) As ReturnCount FROM AD_Authorization WHERE AD_SID = #userSID";
Also, the parameter name should match:
cmd.Parameters.AddWithValue("#userSID", SpartaCrypto.SpartaEncryptAES(userSID.ToString(), "s3cret!"));

Related

Why is my response always 0 after using parameters in OleDB?

I have a simple .aspx login website and I use OleDB for local validation.
Here is my problem: After finding SQL Injection vulnerability, I decided to use parameters. But after using parameters my response is always "0" (Same as "Authenticated=false"). But if I don't use parameters, my response is "1" (Same as "Authenticated=true").
Here some pics while debugging:
Without parameters where the response=1 (Authenticated):
With code:
string idstr = Request.QueryString["id"];
idstr.Replace("''", "");
string passpath = Request.QueryString["password"];
passpath.Replace("''", "");
OleDbConnection connect = new OleDbConnection();
OleDbCommand cmd = new OleDbCommand();
connect.ConnectionString = #"Provider=Microsoft.ACE.OLEDB.12.0; Data Source= C:\Users\hugow_000\Desktop\OSGS_Kantine_htm_design\Kantine_data.accdb; Persist Security Info = False;";
cmd.Connection = connect;
connect.Open();
cmd.CommandText = "select * from User_data where Stamnummer="+idstr+" and Wachtwoord="+ passpath;
OleDbDataReader read = cmd.ExecuteReader();
int code = 0;
while (read.Read())
{
code = code + 1;
}
if (code == 1)
{
Response.Redirect("~/AuthKeyGEN.aspx?Auth=true&id=" + idstr + "&password=" + passpath + "");
}
if (code > 1)
{
Response.Redirect("~/Login.aspx?response=0");
}
if (code < 1)
{
Response.Redirect("~/Login.aspx?response=0");
}
}
And with parameters where the response is 0 (Not Authenticated):
And with code:
string idstr = Request.QueryString["id"];
idstr.Replace("''", "");
string passpath = Request.QueryString["password"];
passpath.Replace("''", "");
OleDbConnection connect = new OleDbConnection();
OleDbCommand cmd = new OleDbCommand();
connect.ConnectionString = #"Provider=Microsoft.ACE.OLEDB.12.0; Data Source= C:\Users\hugow_000\Desktop\OSGS_Kantine_htm_design\Kantine_data.accdb; Persist Security Info = False;";
cmd.Connection = connect;
connect.Open();
cmd.CommandText = "select * from User_data where Stamnummer=#idstr and Wachtwoord=#passpath";
cmd.Parameters.Add("#idstr", OleDbType.BSTR).Value = idstr;
cmd.Parameters.Add("#passpath", OleDbType.BSTR).Value = passpath;
OleDbDataReader read = cmd.ExecuteReader();
int code = 0;
while (read.Read())
{
code = code + 1;
}
if (code == 1)
{
Response.Redirect("~/AuthKeyGEN.aspx?Auth=true&id=" + idstr + "&password=" + passpath + "");
}
if (code > 1)
{
Response.Redirect("~/Login.aspx?response=0");
}
if (code < 1)
{
Response.Redirect("~/Login.aspx?response=0");
}
}
I am using the same credentials in both scenarios,
So why is my response always 0 if I use parameters in here?
Thanks in advance!
Doesn't look anything wrong but try using OleDbType.VarChar instead of OleDbType.BSTR since both the parameter are of string type; like
cmd.Parameters.Add("#idstr", OleDbType.VarChar).Value = idstr;
cmd.Parameters.Add("#passpath", OleDbType.VarChar).Value = passpath;
Also as a side note, instead of using select * use a count() query like below in which case you can use ExecuteScalar() rather than using ExecuteReader()
"select count(*) from User_data
where Stamnummer=#idstr and Wachtwoord=#passpath";
Ms Access uses ? as parameter place holders and the order is important (your order is correct). The parameter objects can be named as the name is ignored by the engine so it really does not matter but might make for more readable code. See OleDbCommand.Parameters as reference.
cmd.CommandText = "select 1 from User_data where Stamnummer = ? and Wachtwoord= ?";
Also change the parameter types as #Rahul had pointed out to VarChar.
General recommendations
Wrap your connection in a using block.This ensures your connection is always closed even when an Exception is encountered.
Like #Rahul said use ExecuteScalar instead of ExecuteReader. Use either COUNT(*) or hardcode 1 as the result: select 1 from User_data ...
Never ever store passwords as plain text, ever! This is horrible practice and makes for a very unsecure app. I have submitted a complete solution to creating a password hash that you could copy/paste and use directly.

Login page in asp.net. Issue with query?

I would like to create a simple login page in asp.net. here is my code:
protected void Button1_Click(object sender, EventArgs e)
{
SqlConnection conn = new SqlConnection();
conn.ConnectionString = "Data Source=TEST-PC\\SQLSERVER2012;Initial Catalog=oncf;Integrated Security=True";
conn.Open();
string query = "SELECT COUNT(*) FROM Account WHERE acc_username= '" + TextBox1.Text + "' AND acc_password= '" + TextBox2.Text + "'";
SqlCommand cmd = new SqlCommand(query, conn);
SqlDataReader myreader = cmd.ExecuteReader();
int count = 0;
while(myreader.Read())
{
count = count + 1;
}
if(count==1)
{
Response.Redirect("page2.aspx");
}
else
{
Label1.Visible = true;
}
conn.Close();
}
I set a counter in order to know if the credentials entered are present in the DB. If the value of the counter goes to 1, the login is successful. Otherwise, the label with a message error is displayed!
However, whatever I enter as input in the username and login textboxes, it always redirect me to the other page !
For now, my concern is not the security aspects, I just want to test this simple code, I don't see any problem with the code, but still it doesnt work, it is driving me crazy...
The reason that you are always redirecting is that your reader always returns 1 row, whether there is a match or not. If there is a match in your database, then the query will return
(no column name)
---------------
1
If there is not a match then it will return:
(no column name)
---------------
0
Either way, myreader.Read() will return true, and you will increment count in this part:
while(myreader.Read())
{
count = count + 1;
}
if(count==1)
{
Response.Redirect("page2.aspx");
}
Rather than checking the if the query returns rows you can retrieve the value of the count using SqlCommand.ExecuteScalar(). In addition to this I would make three more changes:
1. Use parameterised queries
This is not just a security concern, parameterised queries are able to use cached plans, whereas if you concatenate the parameters into the query then a new plan is compliled for each new variable value. In addition, parameterised queries are more strongly typed, and you don't need to escape things like O'shea to ensure that your extra quote doesn't mess up the query.
2. Encrypt the passwords
This is directly to do with security so should really be overlooked as per your request to not comment on security, HOWEVER, this answer is not just for your benefit, and a half answer is likely to be read by someone in the future who may or may not be aware of the risks of storing plain text passwords. There is a simple encryption method in this answer.
3. Add using blocks to your code
A minor change, but when you have objects that implement IDisposable it is a good idea to use a using block to esnure they are disposed of properly.
So you might end up with:
string password = SomeStaticClass.Encrypt(TextBox2.Text);
string connectionString = "Data Source=TEST-PC\\SQLSERVER2012;Initial Catalog=oncf;Integrated Security=True";
string query = "SELECT UserCount = COUNT(*) FROM Account WHERE acc_username= #UserName AND acc_password= #Password";
using (var connection = new SqlConnection(connectionString))
using (var command = new SqlCommand(query, connection))
{
connection.Open();
command.Parameters.Add("#UserName", SqlDbType.VarChar, 50).Value = TextBox1.Text;
command.Parameters.Add("#Password", SqlDbType.VarChar, 50).Value = password;
int count = Convert.ToInt32(command.ExecuteScalar());
if(count==1)
{
Response.Redirect("page2.aspx");
}
else
{
Label1.Visible = true;
}
}
The problem you are experiencing is because the followinq query Always returns one row even if there isn't a match in the database:
SELECT COUNT(*) FROM Account WHERE acc_username=....
If there is no match, you get a row with one column, value 0.
You are checking the number of rows returned when you should just be checking the return value.
Use this instead
int count = Convert.ToInt32(cmd.ExecuteScalar());
if(count==1)
{
Response.Redirect("page2.aspx");
}
else
{
Label1.Visible = true;
}
I know you said you don't want advice on security but just to be sure:
Don't store passwords plain text in a database. Always hash them using a salt.
Don't use string concatenation when building sql. Use parameters.
don't use ExecuteReader when you want to return a single value, use ExecuteScalar:
int count = int.Pares(cmd.ExecuteScalar().toString());
if(count >= 1)
{
Response.Redirect("page2.aspx");
}
else
{
Label1.Visible = true;
}
You should always use Paremeterized queries Using parameters in SQL statements
string username=TextBox1.Text;
string password=TextBox2.Text;
SqlConnection conn = new SqlConnection();
conn.ConnectionString = "Data Source=TEST-PC\\SQLSERVER2012;Initial Catalog=oncf;Integrated Security=True";
conn.Open();
SqlCommand cmd = new SqlCommand("SELECT * FROM Account WHERE acc_username=#username and
AND acc_password=#password", conn);
cmd.Parameters.AddWithValue("#username",username);
cmd.Parameters.AddWithValue("#password",password);
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataTable dt = new DataTable();
da.Fill(dt);
if (dt.Rows.Count > 0)
{
Response.Redirect("page2.aspx");
}
else
{
Label1.Visible = true;
}
Try adding if (myreader.HasRows) before while(myreader.Read())

MySqlCommand: no rows returned

I have a database created in a server and I added a row by MySql query browser for testing. This row is visible either with PhpMyAdmin or MySql query browser.
But when I want to reach this table within my program it says me there is no rows (reader.HasRows = false)
cs is the connection string in PublicVariables class
Here is the code
public static int checkuser(string myuser, string mypass)
{
try
{
using (MySqlConnection conn = new MySqlConnection(PublicVariables.cs))
{
string MypassMd5 = MakeMD5(mypass);
conn.Open();
if (conn == null)
Environment.Exit(0);
using (MySqlCommand cmd =
new MySqlCommand("SELECT username, password " + "FROM Users WHERE username = 'myuser'" ,conn))
{
using (MySqlDataReader reader = cmd.ExecuteReader())
{
//DateTime mytime = DateTime.Now ;
if (reader.HasRows)
{
if (Convert.ToString(reader["password"]) != MypassMd5)
{
reader.Close();
conn.Close();
return -1;
}
else
{
PublicVariables.UserId = Convert.ToString(reader["username"]);
PublicVariables.UserDegre = Convert.ToInt16(reader["userdegre"]);
conn.Close();
reader.Close();
return 1;
}
}
else
{
reader.Close();
conn.Close();
return 2;
}
}
}
}
}
catch (MySqlException ex)
{
MessageBox.Show(ex.ToString());
}
return 0;
}
What's wrong in my code?
Well the primary error is in your command string , myuser is a variable and you cannot pass its value putting the variable name inside quotes.
new MySqlCommand("SELECT username, password FROM Users WHERE username = 'myuser'" ,conn)
instead this line should be converted to use a parameterized query
string commandText = "SELECT username, password, userdegre FROM Users WHERE username = #uname";
using (MySqlCommand cmd = new MySqlCommand(commandText ,conn)
{
cmd.Parameters.AddWithValue("#uname", myuser);
....
Looking at your code you have another error after this. You try to read the field userdegre, but this field is not retrieved by your query, so you need to add it to the list of retrieved fields.
But the only field you really need to know is userdegre because you already know the username and the password, so you could remove the datareader and use ExecuteScalar and pass the username and the password as parameters for the WHERE clause. If you get anything in return then you are sure that your user is authenticated by the database.
string commandText = "SELECT userdegre FROM Users WHERE username = #uname AND Password =#pwd";
using(MySqlCommand cmd = new MySqlCommand( commandText ,conn))
{
cmd.Parameters.AddWithValue("#uname", myuser);
cmd.Parameters.AddWithValue("#pwd", MypassMd5);
var result = cmd.ExecuteScalar();
if(result != null)
{
PublicVariables.UserId = myuser;
PublicVariables.UserDegre = result.ToString();
}
}
Don't check reader.HasRows. You need to call reader.Read(), and check the result of that.
Also, some side issues:
MD5 is incredibly weak for a password hash. Really. Just don't use it for that. Look into bcrypt as a much better alternative. Better still if you're not writing authentication code yourself at all. Look for a library for help to get this stuff right... it's just so easy to write authentication code that seems to work, passes all your tests, but has a subtle flaw that gets you hacked a few months down the road.
No need to call conn.Close(). That's what your using blocks are for. They will handle this for you.
I'd remove the try/catch as well. Since you're already returning error conditions to the calling code, I'd leave that as the place where errors are processed, such that your try/catch should go at that level.
You're looking for userdegre in the results that was not in the select list.
Parameterized queries are your friend.
Put it all together you and you end up with this:
public static int checkuser(string myuser, string mypass)
{
string passHash = BCrypt(mypass); //Need to get bcyrpt library and make the function
using (MySqlConnection conn = new MySqlConnection(PublicVariables.cs))
using (MySqlCommand cmd =
new MySqlCommand("SELECT username, password, userdegre FROM Users WHERE username = #user" ,conn))
{
cmd.Parameters.Add("#user", SqlDbType.NVarChar, 20).Value = myuser;
conn.Open();
using (MySqlDataReader reader = cmd.ExecuteReader())
{
if (!reader.Read()) return 2;
if (Convert.ToString(reader["password"]) != MypassMd5) return -1;
PublicVariables.UserId = Convert.ToString(reader["username"]);
PublicVariables.UserDegre = Convert.ToInt16(reader["userdegre"]);
return 1;
}
}
}
I would try something like this new MySqlCommand("SELECT username, password, userdegre " + "FROM Users WHERE username = 'myuser'" ,conn))
adding userdegre the column name in your select statement.
Finally for c# 2008 net 3.5 WORKING COPY of this after the help of #Joel and # Steve is as this:
public static int usertrue(string myuser, string mypass)
{
try
{
using (MySqlConnection conn = new MySqlConnection(PublicVariables.cs))
{
string MypassMd5 = MakeMD5(mypass);
using (MySqlCommand cmd =
new MySqlCommand("SELECT username, password ,userdegre FROM Users WHERE username = #user",conn))
{
cmd.Parameters.Add("#user", MySqlDbType.VarChar, 15).Value = myuser;
conn.Open();
using (MySqlDataReader reader = cmd.ExecuteReader())
{
if (!reader.Read()) return 2;
if (Convert.ToString(reader["password"]) != MypassMd5) return -1; {
PublicVariables.UserId = Convert.ToString(reader["username"]);
PublicVariables.UserDegre = Convert.ToInt16(reader["userdegre"]);
return 1;
}
}
}
}
}

how to check if stored procedure exists or not in sql server using c# code

I tried below code for cheking SP is alredy exist or not. if not exist i am creating..
But every time it is showing sp is not created.....But my database already have this sp.
Let me know where i am doing mistake.
string checkSP = String.Format(
"IF OBJECT_ID('{0}', 'U') IS NOT NULL SELECT 'true' ELSE SELECT 'false'",
"GP_SOP_AdjustTax");
SqlCommand command = new SqlCommand(checkSP, myConnection);
command.CommandType = CommandType.Text;
if (myConnection == null || myConnection.State == ConnectionState.Closed)
{
try
{
myConnection.Open();
}
catch (Exception a)
{
MessageBox.Show("Error " + a.Message);
}
}
bool Exist = false;
Exist = Convert.ToBoolean(command.ExecuteScalar());
if (Exist == false) //false : SP does not exist
{
// here i am writing code for creating SP
}
Try:
if exists(select * from sys.objects where type = 'p' and name = '<procedure name>' )
Also you can check that with c#:
string connString = "";
string query = "select * from sysobjects where type='P' and name='MyStoredProcedureName'";
bool spExists = false;
using (SqlConnection conn = new SqlConnection(connString))
{
conn.Open();
using (SqlCommand command = new SqlCommand(query, conn))
{
using (SqlDataReader reader = command.ExecuteReader())
{
while (reader.Read())
{
spExists = true;
break;
}
}
}
}
For those who use Entity Framework and a DbContext:
create an extension class for DbContext:
internal static class DbContextExtensions
{
public static bool StoredProcedureExists(this DbContext context,
string procedureName)
{
string query = String.Format(
#"select top 1 from sys.procedures " +
"where [type_desc] = '{0}'", procedureName);
return dbContext.Database.SqlQuery<string>(query).Any();
}
}
As robIII remarked, this code should not be published to the outside world as it makes the database vulnerable for hackers (thank you RobIII!). To prevent this use a parameterized statement. The problem with the above mentioned method is described here
The solution is to put procedureName as a parameter in an SQL statement. SQL will check if the string parameter has the desired format, thus inhibiting malicious calls:
public static bool ImprovedExists(this DbContext dbContext, string procedureName)
{
object[] functionParameters = new object[]
{
new SqlParameter(#"procedurename", procedureName),
};
const string query = #"select [name] from sys.procedures where name= #procedurename";
return dbContext.Database.SqlQuery<string>(query, functionParameters).Any();
}
I found this on MSDN
select * from sys.objects where type_desc = 'SQL_STORED_PROCEDURE' AND name = 'Sql_PersonInsert'
Try:
SELECT *
FROM sys.objects
WHERE object_id = OBJECT_ID(N'GP_SOP_AdjustTax') AND type in (N'P', N'PC')
My stab at it:
Reusable extension method
Minimal Sql / Minimal C#
Called from .Net as the OP implicitly requested
Could be faster because of the object_id function
public static bool StoredProcedureExists(this string source)
{
using (var conn = new SqlConnection(ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString))
{
conn.Open();
using (var cmd = new SqlCommand($"select object_id('{source}')", conn))
return !cmd.ExecuteScalar().ToString().IsNullOrWhiteSpace();
}
}
You can check with following tsql query (suitable for SQL Server):
select * from sysobjects where ytype='P' and name='MyStoredProcedureName'
If query returns row then stored procedure named 'MyStoredProcedureName' exists.
And here is how you can use it in code:
//TODO: set connection string
string connString = "";
string query = "select * from sysobjects where ytype='P' and name='MyStoredProcedureName'";
bool spExists = false;
using (SqlConnection conn = new SqlConnection(connString))
{
conn.Open();
using (SqlCommand command = new SqlCommand(query,conn))
{
using (SqlDataReader reader = command.ExecuteReader())
{
while (reader.Read())
{
spExists = true;
break;
}
}
}
}
string checkSP = String.Format(
"IF OBJECT_ID('{0}', 'U') IS NOT NULL SELECT 'true' ELSE SELECT 'false'",
"GP_SOP_AdjustTax");
is fine if you change the 'U' to 'P'.
With 'U' you query for user-tables, where 'P' gives you stored-procedures.
private static bool StoredProcedureExists(string sp)
{
var connString = #"<your string here>";
var query = string.Format("SELECT COUNT(0) FROM INFORMATION_SCHEMA.ROUTINES WHERE ROUTINE_NAME = '{0}'", sp);
using (var conn = new SqlConnection(connString))
{
conn.Open();
using (var cmd = new SqlCommand(query, conn))
{
return Convert.ToInt32(cmd.ExecuteScalar()) > 0;
}
}
}
Handles procedure names with different schemas
Names with and without brackets ([])
Uses parameter to avoid SQL injection
Note: Caller owns SQL Connection
public static class SqlConnectionExtensions
{
public static Task<bool> StoredProcedureExistsAsync(this SqlConnection sqlConnection, string storedProcedureName)
{
string query = "SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(#storedProcedureName) AND type in (N'P', N'PC')";
using (SqlCommand command = new SqlCommand(query, sqlConnection))
{
command.Parameters.AddWithValue("#storedProcedureName", storedProcedureName);
using (SqlDataReader reader = command.ExecuteReader())
{
return reader.ReadAsync();
}
}
}
}
The following works with MySQL, SQL Server, and Oracle I think:
SELECT * FROM INFORMATION_SCHEMA.ROUTINES
WHERE ROUTINE_TYPE='PROCEDURE'
AND (ROUTINE_SCHEMA='questionnaire' OR ROUTINE_CATALOG = 'questionnaire')
AND SPECIFIC_NAME='create_question';
Usage:
string procedureName = "create_question";
using (DbConnection conn = new SqlConnection("Server=localhost;Database=questionnaire;Trusted_Connection=True;")) // Connection is interchangeable
{
conn.Open();
using (var cmd = conn.CreateCommand())
{
cmd.CommandText = $"SELECT * FROM INFORMATION_SCHEMA.ROUTINES WHERE ROUTINE_TYPE='PROCEDURE' AND (ROUTINE_SCHEMA='{conn.Database}' OR ROUTINE_CATALOG = '{conn.Database}') AND SPECIFIC_NAME='{procedureName}';";
return cmd.ExecuteScalar() != null;
}
}
If you use Microsoft.SqlServer.Management.Smo, try
private static bool CheckIfStoredProcedureExists(Database db, string spName, string schema)
{
db.StoredProcedures.Refresh();
return (db.StoredProcedures[spName, schema] != null);
}
Try this;
if object_id('YourStoredProcedureName') is null
exec ('create procedure dbo.YourSp as select 1')
go
alter procedure dbo.YourStoredProcedure
as

Checking for random number duplicate

I am generating a random number admission no and this is my DAL
public static int randomgen()
{
int id=0;
int number = r.Next(100);
HttpContext.Current.Session["number"] = "SN" + (" ") + number.ToString();
SqlConnection con = DBConnection.OpenConnection();
try
{
string sql1 = "select admissionno from tblstudent_details";
SqlCommand cmd=new SqlCommand(sql1,con);
SqlDataReader dr = cmd.ExecuteReader();
if (dr.Read())
{
id = Convert.ToInt32(dr[0]);
}
dr.Close();
return id;
}
catch (Exception)
{
throw;
}
}
and i am checking if there is any duplicate is getting generated but i am getting an error like Input string is not in a correct format?Where i am doing wrong?Is any better way than this?
You asked if there is a better way...
From what I understand about the question what you are trying to do is pick a random value and then check the database to see if that value already exists. You want to return a value back to the UI to tell the UI whether the value exists or not...
Here is a couple alternatives to consider...
public static bool randomgen()
{
bool isFound = false;
string admissionNumber = "SN " + r.Next(100);
HttpContext.Current.Session["number"] = admissionNumber;
using (SqlConnection con = new SqlConnection()) // use "using" to guarantee connection is closed
{
string sql1 = "SELECT CASE WHEN EXISTS(SELECT admissionno FROM tlblstudent_details WHERE admissionno = #admissionno) THEN 1 ELSE 0 END";
using (SqlCommand cmd = con.CreateCommand())
{
cmd.CommandText = sql;
cmd.Parameters.AddWithValue("#admissionno", number);
using (SqlDataReader dr = cmd.ExecuteReader())
{
if (dr.Read())
{
isFound = (Convert.ToInt32(dr[0]) == 1)
}
}
}
}
return isFound;
}
This way you let SQL Server check to see if the value exists.
Another approach...
Not sure if you are required to prompt the user if the value is not unique, if that is not a requirement then I would consider a different approach; Keep trying until you find a unique value...Like this...
public static int randomgen()
{
bool isFound = true;
while (isFound)
{
string admissionNumber = "SN " + r.Next(100);
using (SqlConnection con = new SqlConnection()) // use "using" to guarantee connection is closed
{
string sql1 = "SELECT CASE WHEN EXISTS(SELECT admissionno FROM tlblstudent_details WHERE admissionno = #admissionno) THEN 1 ELSE 0 END";
using (SqlCommand cmd = con.CreateCommand(sql1))
{
cmd.Parameters.AddWithValue("#admissionno", admissionNumber);
using (SqlDataReader dr = cmd.ExecuteReader())
{
if (dr.Read())
{
isFound = (Convert.ToInt32(dr[0]) == 1)
}
}
}
}
return number;
}
This keeps checking until a unique value is returned. Then you return that unique value to the calling method. Now you set HttpContent.Current session from the caller, leaving the responsibility of this method to only be finding a unique Admission Number. The downside to the second approach is that it may take a long time to find a unique value, depending on how many values are already used, especially considering you are only allowing 100 values.
Hope this gives you good alternatives to consider. Let me know if you have additional questions.

Categories

Resources