return parameters from function - asp.net

I have a function:
internal static void GetUserData(int userId, out string userName,
out string userEmail, out string userPassword)
{
using (SqlConnection con = Util.GetConnection())
{
con.Open();
using (SqlCommand cmd = new SqlCommand("usp_UD_SelectById", con))
{
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.Add("#UD_ID", SqlDbType.Int).Value = userId;
cmd.Parameters.Add("#UD_UserName", SqlDbType.NVarChar, 100).Direction = ParameterDirection.Output;
cmd.Parameters.Add("#UD_Password", SqlDbType.NVarChar, 100).Direction = ParameterDirection.Output;
cmd.Parameters.Add("#UD_Email", SqlDbType.NVarChar, 100).Direction = ParameterDirection.Output;
cmd.ExecuteNonQuery();
userName = Convert.ToString(cmd.Parameters["#UD_UserName"].Value);
userEmail = Convert.ToString(cmd.Parameters["#UD_Email"].Value);
userPassword = Convert.ToString(cmd.Parameters["#UD_Password"].Value);
}
}
}
and the call
string userEmail;
string userName;
string userPassword;
MemberHelper.GetUserData(userId, out userName, out userEmail, out userPassword);
Sometimes I need to get just one parameter from the out parameters, how can I call the function when I want to get just one:
string userPassword;
MemberHelper.GetUserData(userId,"","",out userPassword);

You have to supply them. out parameters are not optional. You could write a custom overload that only provides the out parameters that you need.

Related

SQLCommand AddWithValue - What am I doing wrong?

protected void gridOmniZone_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
GridViewRow row = gridOmniZone.Rows[e.RowIndex];
Int64 ID = Convert.ToInt64(gridOmniZone.DataKeys[e.RowIndex].Values[0]);
string Description = (row.Cells[2].Controls[1] as TextBox).Text;
string LatCenter = (row.Cells[3].Controls[1] as TextBox).Text;
string LongCenter = (row.Cells[4].Controls[1] as TextBox).Text;
string Radius = (row.Cells[5].Controls[1] as TextBox).Text;
string Address = (row.Cells[6].Controls[1] as TextBox).Text;
string City = (row.Cells[7].Controls[1] as TextBox).Text;
string State = (row.Cells[8].Controls[1] as TextBox).Text;
string PostalCode = (row.Cells[9].Controls[1] as TextBox).Text;
using (SqlConnection con = new SqlConnection(constr))
{
using (SqlCommand cmd = new SqlCommand("dbo.usp_UpdateOmniZone"))
{
cmd.Connection = con;
cmd.Parameters.Add("#ID", SqlDbType.BigInt);
cmd.Parameters[0].Value = ID;
cmd.Parameters.AddWithValue("#Description", Description);
cmd.Parameters.AddWithValue("#LatCenter", LatCenter);
cmd.Parameters.AddWithValue("#LongCenter", LongCenter);
cmd.Parameters.AddWithValue("#Radius", Radius);
cmd.Parameters.AddWithValue("#Address", Address);
cmd.Parameters.AddWithValue("#City", City);
cmd.Parameters.AddWithValue("#State", State);
cmd.Parameters.AddWithValue("#PostalCode", PostalCode);
con.Open();
cmd.ExecuteNonQuery();
con.Close();
}
}
gridOmniZone.EditIndex = -1;
this.BindGrid();
}
My code above throws an error on cmd.ExecuteNonQuery. The error is:
stored procedure expects parameter #ID which was not supplied.
As you can see, I did provide the parameter. Any idea what I am doing wrong? The debugger is telling me that the variable ID is a valid integer value.
I think the problem is that you forgot to set the CommandType to CommandType.StoredProcedure.
I up-voted the other answer - the issue is that message is common if you don't set the command type to stored procedure.
And you ARE better off to strong type the values.
So, this:
using (SqlConnection con = new SqlConnection(constr))
{
using (SqlCommand cmd = new SqlCommand("dbo.usp_UpdateOmniZone",con))
{
cmd.Parameters.Add("#ID", SqlDbType.BigInt).Value = ID;
cmd.Parameters.Add("#Description",SqlDbType.NVarChar).Value = Description;
cmd.Parameters.Add("#LatCenter", SqlDbType.NVarChar).Value = LatCenter;
cmd.Parameters.Add("#LongCenter", SqlDbType.NVarChar).Value = LongCenter;
cmd.Parameters.Add("#Radius", SqlDbType.NVarChar).Value = Radius;
cmd.Parameters.Add("#Address", SqlDbType.NVarChar).Value = Address;
cmd.Parameters.Add("#City", SqlDbType.NVarChar).Value = City;
cmd.Parameters.Add("#State", SqlDbType.NVarChar).Value = State;
cmd.Parameters.Add("#PostalCode", SqlDbType.NVarChar).Value = PostalCode;
cmd.CommandType = CommandType.StoredProcedure;
con.Open();
cmd.ExecuteNonQuery();
}
}
And you don't need the "close" connection - quite much the WHOLE point of the "using" block.

asp.net mvc using string id on details view

Please help me to find error on my code
public ActionResult Details(string id)
{
String connectionString = ConfigurationManager.ConnectionStrings["SAPB1"].ConnectionString;
SqlConnection conn = new SqlConnection(connectionString);
String sql = "Select a.[CardCode] As CCODE,a.[CardName] As Name from ocrd a where a.CardCode = " + id;
SqlCommand cmd = new SqlCommand(sql, conn);
BPModel BP = new BPModel();
using (conn)
{
conn.Open();
if (string.IsNullOrEmpty(id))
{
}
SqlDataReader rdr = cmd.ExecuteReader();
while (rdr.Read())
{
BP.CCODE = rdr["CCODE"].ToString();
BP.Name = rdr["Name"].ToString();
}
}
return View(BP);
}
You need to wrap your id values inside single quote ('). Try like below.
String sql = "Select a.[CardCode] As CCODE,a.[CardName] As Name from ocrd a where a.CardCode = '" + id + "'";

Code to help change data in the SQL Server from lower case to upper case?

I require help to use data from the SQL Server to extract it then decrpyt it, convert it to capital and then encrypt it and send back to database. Is there code to help upper case the columns in the database?
// connection string
static string connStr = ConfigurationManager.ConnectionStrings["tmsdbConnection"].ConnectionString;
SqlConnection conn = new SqlConnection(connStr);
protected Cryptography a = new Cryptography();
protected void btnUpdate_Click(object sender, EventArgs e)
{
conn.Open();
// Response.Write("Connection Established");
this.getdataTable();
this.getDataSet();
// retrieve data
SqlCommand command;
String sql, Output = " ";
sql = "SELECT applicantId, fullName, idNumber, idType, nationality, race, gender, birthDate, highestEducation, spokenLanguage, getToKnowChannel FROM applicant";
// command = new SqlCommand(sql, conn);
command = new SqlCommand("SELECT applicantId, fullName, idNumber, idType, nationality, race, gender, birthDate, highestEducation, spokenLanguage, getToKnowChannel FROM applicant");
Cryptography c = new Cryptography();
lblRecords.Text = c.encryptInfo(lblRecords.Text);
}
These are the database methods:
public DataTable getDataTable(SqlCommand cmd)
{
cmd.Connection = getDBConnection();
cmd.Connection.Open();
cmd.CommandTimeout = 1200;
SqlDataAdapter dataAdapter = new SqlDataAdapter(cmd);
DataTable dt = new DataTable();
dataAdapter.Fill(dt);
cmd.Connection.Close();
return dt;
}
public DataSet getDataSet(SqlCommand cmd)
{
cmd.Connection = getDBConnection();
cmd.Connection.Open();
cmd.CommandTimeout = 1200;
SqlDataAdapter dataAdapter = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
dataAdapter.Fill(ds);
cmd.Connection.Close();
return ds;
}
and these are the cryptography methods:
public string encryptInfo(string inputText)
{
cipherData = AES_256.encryptStringToBytes(inputText, keyBytes, ivBytes);
string userinfo64Text = Convert.ToBase64String(cipherData);
return userinfo64Text;
}
public string decryptInfo(string outputText)
{
byte[] inputbytes = Convert.FromBase64String(outputText);
string plainText = AES_256.decryptStringFromBytes(inputbytes, keyBytes, ivBytes);
return plainText;
}
There is a built-in SQL Server Function called UPPER:
SELECT UPPER('myvalue')

How do i fill up textbox from database in asp.net visual studio without id?

I am trying to get details of an account in a row using the Username instead of id. I have limited knowledge on this matter so im only stuck with the code that i learned in class.
I have tried changing variables, but probably wont help and the code i have provided below, would not retrieve any data from the database...
(Username are retrieved from previous page and yes it did show up in this page)
This is the code used on previous page: (code is placed on a button)
string username = Session["Username"].ToString();
Response.Redirect("EditAccountDetail.aspx?Username="+ username);
private DataTable GetData()
{
string constr = ConfigurationManager.ConnectionStrings["myDbConnectionString"].ConnectionString;
using (SqlConnection con = new SqlConnection(constr))
{
using (SqlCommand cmd = new SqlCommand("SELECT * FROM Guest"))
{
using (SqlDataAdapter sda = new SqlDataAdapter())
{
cmd.Connection = con;
sda.SelectCommand = cmd;
using (DataTable dt = new DataTable())
{
sda.Fill(dt);
return dt;
}
}
}
}
}
This is the code im working on right now:
String Uname = Request.QueryString["Username"];
string constr = ConfigurationManager.ConnectionStrings["MyDbConnectionString"].ConnectionString;
using (SqlConnection con = new SqlConnection(constr))
{
using (SqlCommand cmd = new SqlCommand("SELECT * FROM Guest WHERE Username='" + Uname+"'"))
{
using (SqlDataAdapter sda = new SqlDataAdapter())
{
cmd.Connection = con;
sda.SelectCommand = cmd;
using (DataTable dt = new DataTable())
{
sda.Fill(dt);
foreach (DataRow row in dt.Rows)
{
string id = row["Id"].ToString();
string Full_name = row["Full_name"].ToString();
string Username = row["Username"].ToString();
string Password = row["Password"].ToString();
string Email = row["Email"].ToString();
string DOB = row["DOB"].ToString();
string Gender = row["Gender"].ToString();
this.HiddenField1.Value = id;
this.TextBox_Name.Text = Full_name;
this.TextBox_Username.Text = Username;
this.TextBox_Password.Text = Password;
this.TextBox_Email.Text = Email;
this.TextBox_DOB.Text = DOB;
this.RadioButtonList_Gender.Text = Gender;
}
}
}
}
}
This is the code in the button:
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["myDbConnectionString"].ConnectionString);
try
{
string query = "UPDATE Guest SET Full_name=#Full_name, Username=#Username, Password=#Password, Email=#Email, DOB=#DOB, Gender=#Gender WHERE Id=#id";
SqlCommand cmd = new SqlCommand(query, con);
cmd.Parameters.AddWithValue("#id", HiddenField1.Value);
cmd.Parameters.AddWithValue("#Full_name", TextBox_Name.Text);
cmd.Parameters.AddWithValue("#Username", TextBox_Username.Text);
cmd.Parameters.AddWithValue("#Password", TextBox_Password.Text);
cmd.Parameters.AddWithValue("#Email", TextBox_Email.Text);
cmd.Parameters.AddWithValue("#DOB", TextBox_DOB.Text);
cmd.Parameters.AddWithValue("#Gender", RadioButtonList_Gender.Text);
con.Open();
cmd.ExecuteNonQuery();
Response.Redirect("GuestMenu.aspx");
con.Close();
}
catch (Exception ex)
{
Response.Write("Error: " + ex.ToString());
}
If you are redirecting to the "GuestMenu" page, then you have to add username in the query string so that you can retrieve this on the page.
Response.Redirect("GuestMenu.aspx?Username="+TextBox_Username.Text);
By seeing your current code, you should be getting some error. Please post the error details if any.
You can try changing the query as below and check for database result
new SqlCommand("SELECT * FROM Guest WHERE Username='" + Uname + "'")

why does SELECT SCOPE_IDENTITY() returning null?

I am trying to get ID generated by last Insert function. I understand very little about Scope and Session. But by reading blogs and other sources, I understood that, I should use Scope_Identity() function. But I am getting null value. Here is my code :
public int InsertUser(string username, string gender, string agegroup, string email, int partnerID, string userType)
{
try
{
string query = "Insert into tblUser (username,gender,agegroup,email,partnerid,usertype) values (#username,#gender,#age,#email,#partnerid,#usertype)";
SqlCommand cmd = new SqlCommand(query, _dbConnection.getCon());
cmd.CommandType = CommandType.Text;
cmd.Parameters.AddWithValue("#username", username);
cmd.Parameters.AddWithValue("#gender", gender);
cmd.Parameters.AddWithValue("#age", agegroup);
cmd.Parameters.AddWithValue("#email", email);
cmd.Parameters.AddWithValue("#partnerid", partnerID);
cmd.Parameters.AddWithValue("#usertype", userType);
if (cmd.ExecuteNonQuery() > 0)
{
query = "select scope_identity() as id";
cmd = new SqlCommand(query, _dbConnection.getCon());
SqlDataAdapter adp = new SqlDataAdapter(cmd);
DataTable dt = new DataTable();
adp.Fill(dt);// dt is showing no value in it
return 1;// This should return ID
}
else {
return -1;
}
}
catch (Exception e) {
throw e;
}
}
How can I achieve this?
Try appending SELECT scope_identity() to your first query and then capture the identity using var identity = cmd.ExecuteScalar() instead of running cmd.ExecuteNonQuery().

Resources