How to make sure stored procedure executes correctly? - asp.net

I am developing an ASP.NET MVC application. I have a stored procedure. I want to send some values to the stored procedure. Below are the parameters
#CorporateId Input
#CitizenId Input
#DocType Input
#Revert Input
#ResponseCode Out
#ResponseMessage Out
I need to send values for CorporateId ,CitizenId,DocType and #Revert where the value is 0 always. when inserting documents I want to send 0 as a value to #rever.
Sample code I've tried
public EmployeeDetail InsertDocumentFlagRevert(int? corporateID, string citizenId, int? docType, string connectingString)
{
string constring = connectingString;
EmployeeDetail objclValues = new EmployeeDetail();
using (SqlConnection con = new SqlConnection(constring))
{
using (SqlCommand cmd = new SqlCommand("uup_Employee_KYC_Uploaded_Flag", con))
{
cmd.CommandType = CommandType.StoredProcedure;
if (corporateID == null)
{
cmd.Parameters.AddWithValue("#CorporateID", DBNull.Value);
}
else
{
cmd.Parameters.AddWithValue("#CorporateID", corporateID);
}
if (string.IsNullOrEmpty(citizenId))
{
cmd.Parameters.AddWithValue("#CitizenId", DBNull.Value);
}
else
{
cmd.Parameters.AddWithValue("#CitizenId", citizenId);
}
if (docType == null)
{
cmd.Parameters.AddWithValue("#DocType", DBNull.Value);
}
else
{
cmd.Parameters.AddWithValue("#DocType", docType);
}
cmd.Parameters.Add("#ResponseCode", SqlDbType.VarChar, 2);
cmd.Parameters.Add("#ResponseMessage", SqlDbType.VarChar, 70);
cmd.Parameters.AddWithValue("#Revert", 0);
cmd.Parameters["#ResponseCode"].Direction = ParameterDirection.Output;
cmd.Parameters["#ResponseMessage"].Direction = ParameterDirection.Output;
con.Open();
int i = cmd.ExecuteNonQuery();
con.Close();
}
}
}
In this code, the value for i is -1. I am not sure if the parameters are actually being passed to the stored procedure or not? Can someone help me out with this?

As you know, ExecuteNonQuery returns the number of rows affected.
Try Commenting the SET NOCOUNT ON in your stored procedure.
This will return the number of affected rows. I hope this will help you resolve the issue.

You can either use SQL Profiler to inspect the query sent with parameters from your application to SQL Server.
Or, you can use the two output variables and inspect its values to make sure the parametres were sent correctly, the least is to append the parameter values in the #ResponseMessage parameter and check its value after the call for ExecuteNonQuery method

Related

How to store stored procedure results to a variable in Entity Framework?

How do I store the results from my stored procedure to variables? Here is my sample code:
public ActionResult ManageProfile(string eid)
{
var vm = new ManageProfileViewModel(); // Call ViewModel
sp_GetUserDetails_Result gResult = db_RIRO.sp_GetUserDetails(Session["EID"].ToString()).First();
// Get UserId, FirstName, LastName from stored procedure result
gResult.UserId = vm.UserId;
gResult.FirstName = vm.FirstName;
gResult.LastName = vm.LastName;
return View(vm);
}
The stored procedure works fine when I manually try to execute it in Management Studio. The problem with my code is after executing it returns a null.
Assigning of my variables should be the other way around.
vm.FirstName = gResult.SAPID
instead of
gResult.SAPID = vm.FirstName.
It is difficult to tell you without seeing the stored procedure.
Make sure your stored procedure has output parameter.
For example, if you have a output variable "#userId" from stored procedure:
something like in your code:
sqlcmd.Parameters.Add("#userId", SqlDbType.NVarChar, 4000).Value = "";
sqlcmd.Parameters["#userId"].Direction = ParameterDirection.Output;using
using (SqlConnection conn = new SqlConnection(dbConnStr))
{
sqlcmd.Connection = conn;
conn.Open();
sqlcmd.ExecuteNonQuery();
conn.Close();
if(sqlcmd.Parameters["#userId"].SqlValue.ToString() != "Null")
{
gResult.UserId = sqlcmd.Parameters["#userId"].SqlValue.ToString();
}
}
Hope this pseudo code helps you.

how can i bind an object to a gridview

My code is
public Emp GetEmpByEmpno(int empno)
{
using (con)
{
if (con.State == ConnectionState.Closed)
{
con.ConnectionString = constr;
con.Open();
}
cmd.CommandText = "sp_emp_GetempByEmpno";
cmd.Parameters.Clear();
cmd.Parameters.AddWithValue("#eno",empno);
dr=cmd.ExecuteReader();
Emp obj=null;
while(dr.Read())
{
obj=new Emp();
obj.Empno=int.Parse(dr["Empno"].ToString());
obj.Ename=dr["Ename"].ToString();
obj.Sal=dr["Sal"].ToString();
obj.Deptno=int.Parse(dr["Deptno"].ToString());
}
return obj;
}
}
Here I fetch the record based on employee number, whenever i pass empno in textbox search button onClick, the respective employee should display in grid view. How can i bind the object to grid view?
Employee obj=EmpDeptBus.GetEmployeeByEmpno(int.Parse(txtEmpno.Text));
gvemp.DataSource = c;
gvemp.DataBind();
You should be able to just say
gvemp.DataSource = obj;
That's really all you need to do to bind the object.
Also, change your
while(dr.Read())
to
if(dr.Read())
You're only expecting one record so only fetch one. Also put your return obj outside your using to make sure everything is properly disposed before you return to the calling function.
Try making sure that txtEmpno.Text holds an int value before you attempt to pass it to this method or it will blow up. Never, ever trust user input. You could do something like:
int empNo = 0;
if(int.TryParse(txtEmpNo.Text.Trim(), out empNo)
{
// then call the function and bind your grid using the empNo as the
// variable holding the employee number.
}
else
{
// otherwise handle the fact that the user entered a non-numeric.
}

Adding value to dropdownlist

I have web Service method that returns value of one column of a table. I want add that value to my drop down list. Is there any easy way to do it.
Here is my web method that returns all conference_name in conference table.
[WebMethod(Description = "Retrieves all Conference")]
public DataSet GetAllConference()
{
DataSet dataSet = new DataSet();
// Create connection object
OleDbConnection oleConn = new OleDbConnection(connString);
try
{
oleConn.Open();
string sql = "SELECT conference_name FROM Conference";
OleDbDataAdapter dataAdapter = new OleDbDataAdapter(sql, oleConn);
dataAdapter.Fill(dataSet, "Conference");
}
catch (Exception ex)
{
Console.WriteLine(ex.ToString());
}
finally
{
oleConn.Close();
}
if (dataSet.Tables.Count <= 0)
return null;
else
return dataSet;
}
On user side there will be one dropdown list. How can i add the value return by the web method to the dropdown list.
You need to add web reference of web service in order to call the method, You may read this post to know how add reference, After adding reference you can call the method adn fill the drop down by the code given below,
DataSet ds = wsObject.GetAllConference();
if(ds.Tables.Count > 0)
{
ddlist.DataTextField = "conference_name";
ddlist.DataValueField = "conference_name"; //Change field to one you want.
//ddlist.DataValueField = "IDColumnInTheDataTable"; //un comment after give right column name
ddlist.DataSource = ds.Tables[0];
ddlist.DataBind();
}

Executing stored procedure with asp.net

I am trying to execute a stored procedure in asp.net. The stored procedure requires 3 parameters, all 3 are ID's(ints). The 3 parameters are : TaskID, ExhibitID, and InvestigatorID.
I have a hidden field that contains an array of ExhibitID's that came from a javascript function.
My question is how do I get the query to execute as I am looping through the array?
Here is an example of my stored procedure:
var cnSaveTask = new SqlConnection(ConfigurationManager.ConnectionStrings["OSCIDConnectionString"].ToString());
var comLinkExhibitToTask = new SqlCommand("p_CaseFileTasksExhibitLinkAdd", cnSaveTask) { CommandType = CommandType.StoredProcedure };
foreach (string exhibit in hidExhibitsIDs.Value.Split(','))
{
comLinkExhibitToTask.Parameters.AddWithValue("#TaskID", taskID);
comLinkExhibitToTask.Parameters.AddWithValue("#ExhibitID", Convert.ToInt32(exhibit));
comLinkExhibitToTask.Parameters.AddWithValue("#InvestigatorID", int.Parse(Session["InvestigatorID"].ToString()));
}
try
{
cnSaveTask.Open();
comLinkExhibitToTask.ExecuteNonQuery();
}
It is not working in my DB though. Nothing gets added. My guess is that since it is iterating and not executing, it just keeps replacing the "exhibitID" everytime then eventually tries to execute it. But I don't think just adding "comLinkExhibitToTask.ExecuteNonQuery()"
outside the try is a good idea. Any suggestions?
you can either move the try block into the foreach loop or wrap the foreach loop with a try block. (depending on what error handling you wish - continue with the next exhibit on error or completely abort execution)
I've never used AddWithValue, so I can't speak to its functionality. Here's how I typically write a DB call like this.
using (SqlConnection cnSaveTask = new SqlConnection(ConfigurationManager.ConnectionStrings["OSCIDConnectionString"].ConnectionString))
{
cnSaveTask.Open();
using (SqlCommand comLinkExhibitToTask = new SqlCommand("p_CaseFileTasksExhibitLinkAdd", cnSaveTask))
{
comLinkExhibitToTask.CommandType = CommandType.StoredProcedure;
comLinkExhibitToTask.Parameters.Add(new SqlParameter("#TaskID", SqlDbType.Int) {Value = taskID});
// etc.
comLinkExhibitToTask.ExecuteNonQuery();
}
}
The solution:
var cnSaveTask = new SqlConnection(ConfigurationManager.ConnectionStrings["OSCIDConnectionString"].ToString());
try
{
var comLinkExhibitToTask = new SqlCommand("p_CaseFileTasksExhibitLinkAdd", cnSaveTask) { CommandType = CommandType.StoredProcedure };
cnSaveTask.Open();
comLinkExhibitToTask.Parameters.Add(new SqlParameter("#TaskID", SqlDbType.Int));
comLinkExhibitToTask.Parameters.Add(new SqlParameter("#ExhibitID", SqlDbType.Int));
comLinkExhibitToTask.Parameters.Add(new SqlParameter("#InvestigatorID", SqlDbType.Int));
foreach (string exhibit in hidExhibitsIDs.Value.Split(','))
{
comLinkExhibitToTask.Parameters["#TaskID"].Value = taskID;
comLinkExhibitToTask.Parameters["#ExhibitID"].Value = Convert.ToInt32(exhibit);
comLinkExhibitToTask.Parameters["#InvestigatorID"].Value = int.Parse(Session["InvestigatorID"].ToString());
comLinkExhibitToTask.ExecuteNonQuery();
}
}
catch (Exception ex)
{
ErrorLogger.Log(0, ex.Source, ex.Message);
}
finally
{
if (cnSaveTask.State == ConnectionState.Open)
{
cnSaveTask.Close();
}
}
Since I was in a loop it kept adding parameters. So just declare the parameters outside the loop, and only pass the values in the loop. That way there are only 3 parameters, and the values will be passed in accordingly

ASP.NET MySQL update multiple records

I have a web page that needs to update multiple records. This page gets all the information and then begins a transaction sending multiple UPDATE queries to the data base.
foreach row
{
Prepare the query
Hashtable Item = new Hashtable();
Item.Add("Id", Id);
Item.Add("Field1", Field1);
Item.Add("Field2", Field2);
Item.Add("Field3", Field3);
...
}
Then we launch the ytransaction
DO CHANGES()
public void execute_NonQuery_procedure_transaction(string StoredProcedure, List<Hashtable> Params)
{
using (MySqlConnection oConnection = new MySqlConnection(ConfigurationManager.AppSettings[DB]))
{
MySqlTransaction oTransaction;
bool HasErrors = false;
oConnection.Open();
oTransaction = oConnection.BeginTransaction();
try
{
MySqlCommand oCommand = new MySqlCommand(StoredProcedure, oConnection);
oCommand.CommandType = CommandType.StoredProcedure;
oCommand.Transaction = oTransaction;
foreach (Hashtable hParams in Params)
{
oCommand.Parameters.Clear();
IDictionaryEnumerator en = hParams.GetEnumerator();
while (en.MoveNext())
{
oCommand.Parameters.AddWithValue("_" + en.Key.ToString(), en.Value);
oCommand.Parameters["_" + en.Key.ToString()].Direction = ParameterDirection.Input;
}
oCommand.ExecuteNonQuery();
}
}
catch (Exception e)
{
HasErrors = true;
throw e;
}
finally
{
if (HasErrors)
oTransaction.Rollback();
else
oTransaction.Commit();
oConnection.Close();
}
}
}
Is there another way to do this or this is the most efficient way?
It depends on the situation, like if you have multiple row updates or adding new rows or deleting some rows or a combination of these, which modifies the database table then, the efficient way to do this is to have Batch Update...
Please go through this link Batch Update
Hope this helps...
it looks fine to me, you could eventually do not clear the Command.Parameters list but just assign the values on following iterations but probably this leads to no visible improvements.
pay attention your throw is wrong, in C# don't use throw e; but simply throw;.

Resources