How to use SqlConnection InfoMessage - asp.net

I have this method that calls a stored procedure. My problem is that it does not return a row, but it prints a message. I am trying to capture that print message into a variable. My problem is I have never ever used InfoMessage before and I checked it out online and for the life of me I can't seem to understand it. Can someone help me out or point me in the right direction?
Here is my code:
public List<showWhatClass> showWhatMethod(string deviceWhat, int tagWhat, Decimal latit, Decimal longit, int Process, string CallNext, int CallNextVar)
{
showWhatCell = new List<showWhatClass>();
try
{
using (connection = new SqlConnection(connectionString))
{
using (SqlCommand command = new SqlCommand("iosShowWhat", connection))
{
command.CommandType = CommandType.StoredProcedure;
command.Parameters.AddWithValue("#DeviceId", deviceWhat);
command.Parameters.AddWithValue("#TagId", tagWhat);
command.Parameters.AddWithValue("#Latitude", latit);
command.Parameters.AddWithValue("#Longitude", longit);
command.Parameters.AddWithValue("#Process", Process);
command.Parameters.AddWithValue("#CallNext", CallNext);
command.Parameters.AddWithValue("#CallNextVar", CallNextVar);
connection.Open();
/*SqlDataReader reader = command.ExecuteReader();
while (reader.Read())
{
showWhatClass item = new showWhatClass();
item.CallNext = reader.GetValue(0).ToString();
item.CallNextVar = (int)reader.GetValue(1);
showWhatCell.Add(item);
}*/
}
}
}
finally
{
connection.Close();
}
return showWhatCell;
}
I have tried the following:
connection.Open();
connection.InfoMessage += delegate(object sender, SqlInfoMessageEventArgs e)
{
showWhatClass item = new showWhatClass();
item.CallNext += "\n" + e.Message;
showWhatCell.Add(item);
};
returns nothing.

You can use an output parameter to get the message from stored procedure and use it in your code.
Add output parameter in stored procedure
#name varchar(20) output
And then set value of this parameter
set #name='Mairaj Ahmad Minhas'
Now in your code when you call stored procedure add another parameter like this
command.Parameters.Add("#name", SqlDbType.VarChar, 20);
command.Parameters["#name"].Direction = ParameterDirection.Output;
And after you have called the stored procedure do this to get value from this parameter.
string name = command.Parameters["#name"].Value.ToString();

Related

No values output to txtField while reading from SQL Server database in ASP.NET

I am trying to simply read data from my SQL Server database and input them into text fields on a webform.
I can't figure out what I'm missing but everything compiles smoothly and runs but my text fields remain empty.
protected void Page_Load(object sender, EventArgs e)
{
String index = Request.Form["indexTb"];
string constr = ConfigurationManager.ConnectionStrings["TravelLogConnectionString2"].ConnectionString;
SqlConnection con = new SqlConnection(constr);
string selectSql = "SELECT Location, Date, Message FROM EntryLogs WHERE ID='" + Convert.ToInt32(index) + "'";
SqlCommand com = new SqlCommand(selectSql, con);
try
{
con.Open();
using (SqlDataReader reader2 = com.ExecuteReader())
{
while (reader2.Read())
{
reader2.Read();
LocTb.Text = (reader2["Location"].ToString());
DateTb.Text = (reader2["Date"].ToString());
MessTb.Text = (reader2["Message"].ToString());
}
reader2.Close();
reader2.Dispose();
}
}
finally
{
con.Close();
}
}
You're calling the reader2.Read(); twice - once in the while loop, once just below:
while (reader2.Read())
{
reader2.Read(); // <=== WHY call .Read() a second time ?!?!!?!
LocTb.Text = (reader2["Location"].ToString());
DateTb.Text = (reader2["Date"].ToString());
MessTb.Text = (reader2["Message"].ToString());
}
That's both unnecessary, and could lead to no results being returned.
If your query only returns one row, the .Read() in the while loop would read that row and return it, but then the next line does another Read(), which would not return any data (since the first and only row has already been read).
Just remove that unnecessary second call to .Read() and I bet your data will begin to show up!
And to fix that glaring SQL injection - use parametrized queries! as one should always do anyway!
string selectSql = "SELECT Location, Date, Message FROM EntryLogs WHERE ID = #Id;";
SqlCommand com = new SqlCommand(selectSql, con);
com.Parameters.Add("#Id", SqlDbType.Int).Value = Convert.ToInt32(index);
try
{
con.Open();
using (SqlDataReader reader2 = com.ExecuteReader())
{
while (reader2.Read())
{
// REMOVE THIS reader2.Read();
LocTb.Text = (reader2["Location"].ToString());
DateTb.Text = (reader2["Date"].ToString());
MessTb.Text = (reader2["Message"].ToString());
}
reader2.Close();
reader2.Dispose();
}
}
finally
{
con.Close();
}

Create Data Dictionary to read column from DB

I am creating a WinForm Application that reads all the records from a certain column in a textfile. What I now need is a Data Dictionary that I can use to read records from the Database once the applications runs and prior to reading the TextFile. I need to read a specific column from the database and match it with the textfile. I am not sure how to go about creating a data dictionary. This is what I have so far.
This is to read the textfile, which is working fine.
using (StreamReader file = new StreamReader("C:\\Test1.txt"))
{
string nw = file.ReadLine();
textBox1.Text += nw + "\r\n";
while (!file.EndOfStream)
{
string text = file.ReadLine();
textBox1.Text += text + "\r\n";
string[] split_words = text.Split('|');
int dob = int.Parse(split_words[3]);
This is what I have so far to create the Data Dictionary.
public static Dictionary<int, string> dictionary = new Dictionary<int, string>();
You can use a SqlDataReader. Here is some code, you just need to modify it to suit your needs. I have added comments for you:
// declare the SqlDataReader, which is used in
// both the try block and the finally block
SqlDataReader rdr = null;
// Put your connection string here
SqlConnection conn = new SqlConnection(
"Data Source=(local);Initial Catalog=Northwind;Integrated Security=SSPI");
// create a command object. Your query will go here
SqlCommand cmd = new SqlCommand(
"select * from Customers", conn);
try
{
// open the connection
conn.Open();
// 1. get an instance of the SqlDataReader
rdr = cmd.ExecuteReader();
while (rdr.Read())
{
string id = (int)rdr["SomeColumn"];
string name = (string)rdr["SomeOtherColumn"];
dictionary.Add(id, name);
}
}
finally
{
// 3. close the reader
if (rdr != null)
{
rdr.Close();
}
// close the connection
if (conn != null)
{
conn.Close();
}
}

Populate web form edit page C# ASP.NET

I am trying to select a single row on a gridview and have that selection take me to a separate edit page with the data populated. I have the idea of using a session variable to hold the row id and then retrieving the data on page load and populating the text boxes. My question is whether or not this is the best method to go about doing this? I would prefer to not use the inline edit option in gridview as I have too many columns that would require scrolling horizontally. Here is my page load method using the session variable:
if (Session["editID"] != null)
{
dbCRUD db = new dbCRUD();
Recipe editRecipe = new Recipe();
var id = Convert.ToInt32(Session["editID"]);
Session.Remove("editID");
editRecipe = db.SelectRecord(id);
addName.Text = editRecipe.Name;
}
Here is the SelectRecord method that is used to retrieve the row:
public Recipe SelectRecord(int id)
{
Recipe returnedResult = new Recipe();
var dbConn = new SqlConnection(connString);
var dbCommand = new SqlCommand("dbo.selectRecipe", dbConn);
dbCommand.CommandType = CommandType.StoredProcedure;
dbCommand.Parameters.Add("#ID", SqlDbType.Int).Value = id;
dbConn.Open();
SqlDataReader reader = dbCommand.ExecuteReader();
while (reader.HasRows)
{
while (reader.Read())
{
returnedResult.Name = reader["Name"].ToString();
}
}
dbConn.Close();
return returnedResult;
}
I'm probably not utilizing the SQLDataReader appropriately, but my result is no data in the reader therefore no returned data when calling the method. Any help is appreciated - thanks in advance!
Few things you should be aware of here:
1.
You should use while (reader.HasRows) in case your stored procedure returns multiple resultsets. In that case you have to iterate through the result sets. See Retrieving Data Using a DataReader. So, if selectRecipe returns multiple resultsets (I am assuming this is not the case), change your code to this:
while (reader.HasRows)
{
while (reader.Read())
{
returnedResult.Name = reader["Name"].ToString();
}
reader.NextResult();
}
2.If selectRecipe returns single result set, change the while loop to if(){}:
if(reader.HasRows)
{
while (reader.Read())
{
returnedResult.Name = reader["Name"].ToString();
}
}
3. I would probably use using to manage the connection better (using Statement) :
public Recipe SelectRecord(int id)
{
Recipe returnedResult = new Recipe();
using (SqlConnection dbConn = new SqlConnection(connString))
{
var dbCommand = new SqlCommand("dbo.selectRecipe", dbConn);
dbCommand.CommandType = CommandType.StoredProcedure;
dbCommand.Parameters.AddWithValue("#ID", id);
dbConn.Open();
SqlDataReader reader = dbCommand.ExecuteReader();
if (reader.HasRows)
{
while (reader.Read())
{
returnedResult.Name = reader["Name"].ToString();
}
}
reader.Close();
}
return returnedResult;
}

Passing SqlParameter in webmethod asp.net

I am trying to create a web service which will help to execute stored procedure. And that web method I am calling in my code to execute a stored procedure. This is my web method -
[WebMethod(Description = des_ExecuteParamerizedSelectCommand)]
public DataTable ExecuteParamerizedSelectCommand(string CommandName, CommandType cmdType, SqlParameter[] param)
{
DataTable table = new DataTable();
using (SqlConnection con = new SqlConnection(ConnectionString()))
{
using (SqlCommand cmd = con.CreateCommand())
{
cmd.CommandType = cmdType;
cmd.CommandText = CommandName;
cmd.Parameters.AddRange(param);
try
{
if (con.State != ConnectionState.Open)
{
con.Open();
}
using (SqlDataAdapter da = new SqlDataAdapter(cmd))
{
da.Fill(table);
}
}
catch
{
throw;
}
}
}
return table;
}
Now this is my code in my data access layer - when I am trying to call this web method, its throwing compile time error.
Error 2 Argument 2: cannot convert from 'System.Data.CommandType' to 'DAL.sqlDBHelper.CommandType'
Error 3 Argument 3: cannot convert from 'System.Data.SqlClient.SqlParameter[]' to 'DAL.sqlDBHelper.SqlParameter[]'
My code to call the webmethod -
sqlDBHelper.ODCdbHelper mysqlDBHelper = new sqlDBHelper.ODCdbHelper();
public Login GetUserRoles(string _Idsid)
{
Login login = null;
SqlParameter[] parameters = new SqlParameter[]
{
new SqlParameter("#UserName", _Idsid)
};
//Lets get the list of all employees in a datataable
using (DataTable table = mysqlDBHelper.ExecuteParamerizedSelectCommand("GetUserRole", CommandType.StoredProcedure, parameters))
Can you please tell me someone, where I am wrong??
Thanks in advance
Gulrej
Try like this
DAL.sqlDBHelper.SqlParameter[] parameters = new DAL.sqlDBHelper.SqlParameter[]//Change Here {
SqlParameter("#UserName", _Idsid)
};
//Lets get the list of all employees in a datataable
using (DataTable table = mysqlDBHelper.ExecuteParamerizedSelectCommand("GetUserRole", DAL.sqlDBHelper.CommandType.StoredProcedure, parameters))
I presume DAL.sqlDBHelper.CommandType will be an enumerator in your data access layer.
And the expected parameter is DAL.sqlDBHelper.SqlParameter[] instead of System.Data.SqlClient.SqlParameter[]
So you might call the select function as
DAL.sqlDBHelper.SqlParameter[] parameters = new DAL.sqlDBHelper.SqlParameter[]
{
new SqlParameter("#UserName", _Idsid)
};
using (DataTable table = mysqlDBHelper.ExecuteParamerizedSelectCommand("GetUserRole", DAL.sqlDBHelper.CommandType.StoredProcedure, parameters))
Please check what is the command type defined for stored procedures in your DAL.

Not able to insert update delete

I'm using Asp.net c# and MYSql as back-end. I'm updating a table,but table is not updating.There are only 3 columns in the table.
There is no exception when I'm executing the command object. But this returns 0 value from cmd.ExecuteNonQuery().
I debugged this and found cmd.Parameters are full with values. and if i manually run the update command in mysql it works fine.
the table is as follow
column -- Datatype
ShortText -- varchar
title -- varchar
id -- int
Please guide me...
int retVal = 0;
string shortText = ((TextBox)fmvwShortText.FindControl("txtShortText")).Text.Trim();
try
{
int id = Convert.ToInt32(((Label)fmvwShortText.FindControl("lblShrtTextID")).Text);
MySqlConnection con = new MySqlConnection(System.Configuration.ConfigurationManager.AppSettings["conn"]);
cmd = new MySqlCommand();
cmd.Connection = con;
cmd.CommandText = "UPDATE temp_posts SET ShortText=#shrtText WHERE id=#id AND Title=#title";
cmd.Parameters.Add("#shrtText", MySqlDbType.VarChar).Value = shortText;
cmd.Parameters.Add("#title", MySqlDbType.VarChar).Value =Session["EditTitle"].ToString();
cmd.Parameters.Add("#id", MySqlDbType.Int32).Value = id;
con.Open();
retVal = cmd.ExecuteNonQuery();
con.Close();
}
catch (Exception e) { }
return retVal;
Is it possibly a casing issue with your Title parameter? I notice you are only updating if the ID & Title match exactly?
Also as a general rule of thumb, when using objects which implement IDisposable you should wrap them with a using statement, this will make sure your objects are always disposed (even on the result of an error)
using (var con = new MySqlConnection(...))
{
using (var cmd = new MySqlCommand(...))
{
....
}
}
First of all thank you every one who kept looking and tried their best to sort out this problem with me..
Finally got the solution.
In my code I used # in cmd.CommandText and in parameters.
But when I replace this # with ? both in cmd.CommandText and in parameters and used the cmd.ExecuteScalar(); this worked.
Actually Parameter names depend on the provider. When using the provider for
SQL Server, it should start with # (e.g. #param1). For Oracle
provider, it should start with a colon (...for e.g. aram1. For
OleDb provider, just a question mark (?) would work
Thank you everyone to contribute your best... many thanks
But i'm still left with a question that ExecuteScalar() is updating the records in the database? I am with no answer... looking for this.
Try this nt sure about code formating coz currently am not using ide frmwrk
int retVal = 0;
string shortText = ((TextBox)fmvwShortText.FindControl("txtShortText")).Text.Trim();
try
{
int id = Convert.ToInt32(((Label)fmvwShortText.FindControl("lblShrtTextID")).Text);
MySqlConnection con = new MySqlConnection(System.Configuration.ConfigurationManager.AppSettings["conn"]);
cmd = new MySqlCommand("UPDATE temp_posts SET ShortText='"+shortText+"' WHERE id='"+id+"' AND Title='"+Session["EditTitle"].ToString()+"'",con);
con.Open();
retVal = cmd.ExecuteNonQuery();
con.Close();
return retVal;
}
catch (Exception e) { }

Resources