The ConnectionString property has not been initialized using c# asp.net - c#

Hi i am getting the following error while trying to update my database using c# asp.net.
Error:
Server Error in '/' Application.
The ConnectionString property has not been initialized.
Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.
Exception Details: System.InvalidOperationException: The ConnectionString property has not been initialized.
Source Error:
Line 33: catch (Exception e)
Line 34: {
Line 35: throw e;
Line 36: }
Line 37: }
I am explaining my code below.
index.aspx.cs:
protected void reject_Click(object sender, EventArgs e)
{
//LinkButton lbtn = (LinkButton)(sender);
//lbtn.BackColor = System.Drawing.Color.Red;
GridViewRow grdrow = (GridViewRow)((LinkButton)sender).NamingContainer;
LinkButton lbtn = (LinkButton)grdrow.FindControl("accept");
LinkButton LRejectBtn = (LinkButton)grdrow.FindControl("reject");
// string status = grdrow.Cells[6].Text;
int healthId = int.Parse(lbtn.CommandArgument);
int result=0;
if (Convert.ToString(lbtn.BackColor) == "Color [Green]")
{
char updatedStatus = 'R';
result = objhealthCommentBL.updateStatusDetails(updatedStatus, healthId);
if (result == 1)
{
LRejectBtn.BackColor = System.Drawing.Color.Red;
lbtn.BackColor = System.Drawing.Color.WhiteSmoke;
ScriptManager.RegisterStartupScript(this, this.GetType(), "alert", "alert('Your status has updated successfully.')", true);
}
else
{
ScriptManager.RegisterStartupScript(this, this.GetType(), "alert", "alert('Your status couldnot updated')", true);
}
}
}
healthCommentBL.cs:
public int updateStatusDetails(char updatedStatus, int healthId)
{
int result;
try
{
result = objhealthCommentDL.updateStatusDetails(updatedStatus, healthId);
return result;
}
catch (Exception e)
{
throw e;
}
}
healthCommentDL.cs:
namespace DataAccess
{
public class healthCommentDL
{
SqlConnection con = new SqlConnection(CmVar.convar);
public DataSet getHealthCommentDetails()
{
try
{
con.Open();
DataSet ds = new DataSet();
string sql = "SELECT Health_Comment_ID,Health_ID,Health_Comment_Name,Health_comment_Email,Health_Comment_Message,Health_Comment_Website,Health_Comment_Status from T_Health_Comment";
sql += " order by Health_Comment_ID ASC ";
SqlCommand cmd = new SqlCommand(sql, con);
SqlDataAdapter objadp = new SqlDataAdapter(cmd);
objadp.Fill(ds);
return ds;
}
catch (Exception e)
{
throw e;
}
finally
{
con.Close();
con.Dispose();
}
}
public int updateStatusDetails(char updatedStatus, int healthId)
{
int result;
try
{
con.Open();
string query = "UPDATE T_Health_Comment SET Health_Comment_Status = #status WHERE Health_Comment_ID = #healthid";
SqlCommand cmd = new SqlCommand(query, con);
cmd.CommandType = CommandType.Text;
cmd.Parameters.AddWithValue("#healthid", healthId);
cmd.Parameters.AddWithValue("#status", updatedStatus);
result = cmd.ExecuteNonQuery();
con.Close();
return result;
}
catch (Exception e)
{
throw e;
}
}
}
}
I am getting the above error in healthCommentBL.cs file in catch statement.Here i can say that the commentstring is properly working in the getHealthCommentDetails method in healthCommentDL.cs file but at the same time it is not working for the 2nd method of this file.Please help me to resolve this error.

When you write your connection as;
public class healthCommentDL
{
SqlConnection con = new SqlConnection(CmVar.convar);
It will be a field of healthCommentDL class, not a local variable. And it's properties (like ConnectionString) is not initialiazed. Instead of that, define your connections as a local variables in your methods. ADO.NET is pretty good at maintaining your connections as a local variables. Read: SQL Server Connection Pooling
public DataSet getHealthCommentDetails()
{
SqlConnection con = new SqlConnection(CmVar.convar);
and
public int updateStatusDetails(char updatedStatus, int healthId)
{
SqlConnection con = new SqlConnection(CmVar.convar);
A few things more;
You should always use parameterized sql. This kind of string concatenations are open for SQL Injection attacks.
Use using statement to dispose your connections and commands automatically instead of calling Close or Dispose methods manually.
Don't use AddWithValue method. It may generate unexpected and surprising results sometimes. Use Add method overloads to specify your parameter type and it's size.

Related

How to execute DataAdapter.Fill() simultaneously

I have been working on an ASP.Net application for a long time and there are above 10 clients using the application. But now I found a problem in the application, that is, I have a stored procedure call which takes about 30 seconds to execute. It is not a problem, because the SQL code highly complicated and looping many times. The problem is :
Whenever that stored procedure call is executing, I am not able to using any other functions or stored procedure call.
When I tried debugging, the problem is that 'DataAdapter.Fill()' function is waiting for the first stored procedure call to finish.
My code that executes stored procedure call and returning data is :
public static DataSet ExecuteQuery_SP(string ProcedureName, object[,] ParamArray)
{
SqlDataAdapter DataAdapter = new SqlDataAdapter();
DataSet DS = new DataSet();
try
{
if (CON.State != ConnectionState.Open)
OpenConnection();
SqlCommand cmd = new SqlCommand();
cmd.CommandTimeout = 0;
cmd.CommandText = ProcedureName;
cmd.CommandType = CommandType.StoredProcedure;
cmd.Connection = CON;
cmd.Transaction = SqlTrans;
string ParamName;
object ParamValue;
for (int i = 0; i < ParamArray.Length / 2; i++)
{
ParamName = ParamArray[i, 0].ToString();
ParamValue = ParamArray[i, 1];
cmd.Parameters.AddWithValue(ParamName, ParamValue);
}
DataAdapter = new SqlDataAdapter(cmd);
DataAdapter.Fill(DS);
cmd.CommandText = "";
}
catch (Exception ea)
{
}
return DS;
}
All stored procedure calls are working through this function. Hence when my first stored procedure call 'A' is running, stored procedure call 'B' will not execute until 'A' is finished.
This reduces overall performance of the application and causes problem in data retrieval.
I surfed google and found that 'Threading' can be helpful but I am not able to execute threading properly. I am not so familiar with these kind of things. It will helpful if you can rectify the problem.
My first stored procedure call is:
ds = DB.ExecuteQuery_SP("SelectOutstandingReportDetailed", parArray);
Where ds is the DataSet object.
Second stored procedure call is :
ds = DB.ExecuteQuery_SP("[SelectAccLedgersDetailsByID]", ParamArray);
My current DB connection open function is :
public static bool OpenConnection()
{
try
{
Server = (String)HttpContext.GetGlobalResourceObject("Resource", "Server");
DBName = (String)HttpContext.GetGlobalResourceObject("Resource", "DBName");
UserName = (String)HttpContext.GetGlobalResourceObject("Resource", "UserName");
PassWord = (String)HttpContext.GetGlobalResourceObject("Resource", "PassWord");
string ConnectionString;
ConnectionString = "server=" + Server + "; database=" + DBName + "; uid=" + UserName + "; pwd=" + PassWord + "; Pooling='true';Max Pool Size=100;MultipleActiveResultSets=true;Asynchronous Processing=true";
CON.ConnectionString = ConnectionString;
if (CON.State != ConnectionState.Open)
{
CON.Close();
CON.Open();
}
}
catch (Exception ea)
{
}
return false;
}
Where 'CON' is a public SqlConnection variable
static SqlConnection CON = new SqlConnection();
I found the problem, that is, all stored procedure calls are performed through this 'CON' object. If there is seperate SqlConnection object for each stored procedure call, then no problem is there.
So is it possible to make separate SqlConnection for every ExecuteQuery_SP calls.
If any doubt in question, kindly comment.
Thank you
SQL Server will allow thousands of connections simultaneously, by default. This is NOT the source of your problem. You have forced every call to a stored procedure to be funneled through a single method. Factor out your calls to the stored procedures - in other words, lose the ExecuteQuery_SP method which is a bottleneck. Then test again.
Here's is an introduction to data layers.
Heres the simplest version I can create for you.
Important: to understand you should read about async-await.
You can start at the Microsoft C# Async-Await Docs
// TODO set up your connection string
private string connectionString = "<your connection string>";
// Gets data assyncronously
public static async Task<DataTable> GetDataAsync(string procedureName, object[,] ParamArray)
{
try
{
var asyncConnectionString = new SqlConnectionStringBuilder(connectionString)
{
AsynchronousProcessing = true
}.ToString();
using (var conn = new SqlConnection(asyncConnectionString))
{
using (var SqlCommand = new SqlCommand())
{
SqlCommand.Connection = conn;
SqlCommand.CommandText = procedureName;
SqlCommand.CommandType = CommandType.StoredProcedure;
string ParamName;
object ParamValue;
for (int i = 0; i < ParamArray.Length / 2; i++)
{
ParamName = ParamArray[i, 0].ToString();
ParamValue = ParamArray[i, 1];
SqlCommand.Parameters.AddWithValue(ParamName, ParamValue);
}
conn.Open();
var data = new DataTable();
data.BeginLoadData();
using (var reader = await SqlCommand.ExecuteReaderAsync().ConfigureAwait(true))
{
if (reader.HasRows)
data.Load(reader);
}
data.EndLoadData();
return data;
}
}
}
catch (Exception Ex)
{
// Log error or something else
throw;
}
}
public static async Task<DataTable> GetData(object General, object Type, string FromDate, string ToDate)
{
object[,] parArray = new object[,]{
{"#BranchID",General.BranchID},
{"#FinancialYearID",General.FinancialYearID},
{"#Type",Type},
{"#FromDate",DateTime.ParseExact(FromDate, "dd/MM/yyyy", System.Globalization.CultureInfo.InvariantCulture)},
{"#ToDate",DateTime.ParseExact(ToDate, "dd/MM/yyyy", System.Globalization.CultureInfo.InvariantCulture)}
};
return await DataBaseHelper.GetDataAsync("SelectOutstandingReportDetailed", parArray);
}
// Calls database assyncronously
private async Task ConsumeData()
{
DataTable dt = null;
try
{
// TODO configure your parameters here
object general = null;
object type = null;
string fromDate = "";
string toDate = "";
dt = await GetData(general, type, fromDate, toDate);
}
catch (Exception Ex)
{
// do something if an error occurs
System.Diagnostics.Debug.WriteLine("Error occurred: " + Ex.ToString());
return;
}
foreach (DataRow dr in dt.Rows)
{
System.Diagnostics.Debug.WriteLine(dr.ToString());
}
}
// Fired when some button is clicked. Get and use the data assyncronously, i.e. without blocking the UI.
private async void button1_Click(object sender, EventArgs e)
{
await ConsumeData();
}

update statement error in image

private void btnupdate_Click(object sender, EventArgs e)
{
byte[] img1 = File.ReadAllBytes(#"C:\Users\Admin\Desktop\Final Project Bridger\Bridger\Bridger\Images\20green.png");
try
{
if (txtfno.Text == "" && txtslab.Text == "")
{
MessageBox.Show("Update not possible");
}
else
{
cnn.Open();
cmd3.CommandText = "update Slab set indi = #img1 where s_flatno = #s_flatno and s_name = #s_name";
cmd3.Parameters.AddWithValue("#indi",img1);
cmd3.Parameters.AddWithValue("#s_flatno", txtfno.Text);
cmd3.Parameters.AddWithValue("#s_name", txtslab.Text);
cmd3.ExecuteNonQuery();
}
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
finally
{
cnn.Close();
}
}
In this code, I'm updating image in the position indi and I'm setting a new img1 in byte. While press update I'm getting an error
Must declare scalar variable #img1
You have named your variable #img1 in the SQL Statement, but #indi when you declared the variable.
Please note that best practice when handling DBConnection is as a local variable inside a using statement, and you better use one of the overloads of Add when adding parameters to a command instead of AddWithValue. For more information, read Can we stop using AddWithValue() already?
Here is an improved version of your code:
private void btnupdate_Click(object sender, EventArgs e)
{
if (txtfno.Text == "" && txtslab.Text == "")
{
MessageBox.Show("Updation not possible");
}
else
{
try
{
byte[] img1 = File.ReadAllBytes(#"C:\Users\Admin\Desktop\Final Project Bridger\Bridger\Bridger\Images\20green.png");
var sql = "update Slab set indi=#indi where s_flatno=#s_flatno and s_name=#s_name";
// I'm assuming SQL Server based on the error message
using(var cnn = new SqlConnection(connectionString))
{
using(var cmd = new SqlCommand(sql, cnn))
{
cmd.Parameters.Add("#indi", SqlDbType.VarBinary).Value = img1;
cmd.Parameters.Add("#s_flatno", SqlDbType.VarChar).Value = txtfno.Text;
cmd.Parameters.Add("#s_name", SqlDbType.VarChar).Value = txtslab.Text;
}
cnn.Open();
cmd3.ExecuteNonQuery();
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
}
}
There is a small issue with you code. You have not passed #img1 parameter. You are sending it as #indi. Either Change #img1 to #indi in sql query string or change #indi to #img1 in add parameter statement:
cnn.Open();
cmd3.CommandText = "update Slab set indi=#indi where s_flatno=#s_flatno and s_name=#s_name";
cmd3.Parameters.AddWithValue("#indi",img1);
cmd3.Parameters.AddWithValue("#s_flatno", txtfno.Text);
cmd3.Parameters.AddWithValue("#s_name", txtslab.Text);
cmd3.ExecuteNonQuery();

Connect to database in sepaerate method of my SqlCommand

I have a form that checks whether values are in a database before adding them. Each field is in a different table, and to keep everything clean, I have a checkExists method for each field. Is there a way to have a separate method that connects to the database, so that I don't have to connect in every field method?
I'd like to do something like this so that my code is less messy:
public void SetConnection()
{
SqlConnection myConnection =
new SqlConnection("user id=[username];" +
"password=[password];" +
"server=[server];" +
"database=[db_name];");
try
{
myConnection.Open();
}
catch(Exception e)
{
Console.WriteLine("Unable to Connect");
}
}
public Boolean CheckData_Company(string[] items)
{
Class_DB set_conn = new Class_DB();
try
{
set_conn.SetConnection();
}
catch(Exception e)
{
Console.WriteLine(e.ToString());
}
//check that item does not already exist
string query_string = "SELECT * FROM CR_Company WHERE ([CompanyName] = #companyName";
SqlCommand check_Company = new SqlCommand(query_string, set_conn);
check_Company.Parameters.AddWithValue("#CompanyName", items[0]);
int CompanyExist = (int)check_Company.ExecuteScalar();
if(CompanyExist > 0)
{
return true;
}
else
{
return false;
}
}
But I get a
local variable set_conn
Argument 2: Cannot Convert from Class_DB to System.Data.SqlClient.SqlConnection
I understand the error, so what can I do to return the correct value, or do I have to establish a connection within my CheckData_Comany() method?
Your method SetConnection should be returning SqlConnection back like:
public SqlConnection SetConnection()
{
SqlConnection myConnection = new SqlConnection("user id=[username];" +
"password=[password];" +
"server=[server];" +
"database=[db_name];");
try
{
myConnection.Open();
}
catch(Exception e)
{
Console.WriteLine("Unable to Connect");
}
return myConnection;
}
and then you can have something like:
SqlConnection connection = set_conn.SetConnection();
and then pass it in SqlCommand constructor as parameter :
SqlCommand check_Company = new SqlCommand(query_string, connection);
Your complete method implementation would become :
public Boolean CheckData_Company(string[] items)
{
bool Exists = false;
Class_DB set_conn = new Class_DB();
SqlConnection connection = null;
try
{
connection = set_conn.SetConnection();
//check that item does not already exist
string query_string = "SELECT * FROM CR_Company WHERE ([CompanyName] = #companyName";
SqlCommand check_Company = new SqlCommand(query_string, set_conn);
check_Company.Parameters.AddWithValue("#CompanyName", items[0]);
int CompanyExist = (int)check_Company.ExecuteScalar();
if(CompanyExist > 0)
Exists = true;
}
catch(Exception e)
{
Console.WriteLine(e.ToString());
}
finally
{
connection.Close();
}
return Exists;
}
and important thing to note is do not forget the close the connection finally by calling connection.Close(), otherwise it might cause eating up the resources that shouldn't happen when we are done with querying the database and we should release the resources occupied.

The ConnectionString property has not been initialized. Winforms C#.net

I am in the process of adding a new form to an already established Winforms application.
I have a DataGridView on my form and the relevant method in code behind which calls my dbAPI DataTable method. I have written the method with exactly the same code as many others used in the dbAPI class but for some reason it is not initialising the connection string...
public DataTable getMyTable()
{
//used for populating the DataGridView
SqlCommand _com = new SqlCommand(string.Format("select * from tab.myTable where Country = 'Angola' "), _conn);
_com.CommandTimeout = _command_timeout;
DataSet _ds = new DataSet();
SqlDataAdapter _adapt = new SqlDataAdapter();
try
{
_adapt.SelectCommand = _com;
int i = _adapt.Fill(_ds, "Asset_Transactions");
if (_ds.Tables.Count > 0)
{
return _ds.Tables[0];
}
else
{
return makeErrorTable("GetMyTable", "No Table Returned for myTable");
}
}
catch (Exception e)
{
return makeErrorTable("GetMyTable", e.Message);
}
}
_conn is an SQLConnection object. My connection string is in the app.config...
class dbAPI
{
Utils _utils = new Utils();
//this is the API between the Application Code and the LDB Database
string _ldb_connection_string = (string)dii.Properties.Settings.Default.connLDB; //connection string but with only one \ in settings as it gets converted to \\
int _command_timeout = Convert.ToInt32((string)dii.Properties.Settings.Default.commandTimeOut); //Command time out
SqlConnection _conn = new SqlConnection();
public dbAPI()
{
//constructor
}
#region --------------- Database Connectivity Section
public string openLocalDatabaseConnection()
{
try
{
//try to create the connection
_conn = new SqlConnection(_ldb_connection_string);
_conn.Open();
}
catch (Exception e)
{
return string.Concat("Can't connect to LDB with '", e.Message, "'");
}
return ""; //success
}
public string closeLocalDatabaseConnection()
{
_conn.Close();
_conn.Dispose();
return "";
}
I am getting an empty connection string and 'The ConnectionString property has not been initialized' exception thrown. I don't understand as I have numerous other methods in the class which work without issue. Any ideas?
Thanks
You have to call openLocalDatabaseConnection() function before proceeding further so that your SqlConnection Object will be initilised with Connection String Properly.
Code :
public DataTable getMyTable()
{
openLocalDatabaseConnection();
//used for populating the DataGridView
SqlCommand _com = new SqlCommand(string.Format("select * from tab.myTable where Country = 'Angola' "), _conn);
_com.CommandTimeout = _command_timeout;
DataSet _ds = new DataSet();
SqlDataAdapter _adapt = new SqlDataAdapter();
try
{
_adapt.SelectCommand = _com;
int i = _adapt.Fill(_ds, "Asset_Transactions");
if (_ds.Tables.Count > 0)
{
return _ds.Tables[0];
}
else
{
return makeErrorTable("GetMyTable", "No Table Returned for myTable");
}
}
catch (Exception e)
{
return makeErrorTable("GetMyTable", e.Message);
}
}
For example add an application config file to your project(or inside the one you have) and place this(the name and the connection string you place yours of course):
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<connectionStrings>
<add name ="MyConnection" connectionString ="your connection string here"/>
</connectionStrings>
</configuration>
Then in your _ldb_connection_string:
string _ldb_connection_string = ConfigurationManager.ConnectionStrings["MyConnection"].ConnectionString;

How to call a stored procedure using ADO.NET?

private void button1_Click(object sender, EventArgs e)
{
try
{
SqlConnection conn = new SqlConnection();
conn.ConnectionString = "Data Source=*******;Initial Catalog=ChatApp;User ID=Chatapplication;Password=****";
conn.Open();
SqlCommand cmd = new SqlCommand();
string chatroomidno = textBox1.Text;
string chatroomname = textBox2.Text;
//cmd.CommandText = "Select ChatRoomID=#ChatRoomID,ChatRoomName=#ChatRoomName from tblChatRoom";
//cmd.Connection = conn;
SqlDataAdapter adapt = new SqlDataAdapter("Chatroomapp",conn);
adapt.SelectCommand.CommandType = CommandType.StoredProcedure;
DataSet ds=new DataSet();
DataTable dt = new DataTable();
adapt.SelectCommand.Parameters.Add(new SqlParameter("#ChatRoomID", SqlDbType.VarChar, 100));
adapt.SelectCommand.Parameters["#ChatRoomID"].Value = chatroomidno;
adapt.SelectCommand.Parameters.Add(new SqlParameter("#ChatRoomName", SqlDbType.VarChar, 50));
adapt.SelectCommand.Parameters["#ChatRoomName"].Value = chatroomname;
adapt.Fill(ds, "tblChatRoom");
if (dt.Rows.Count > 0)
{
MessageBox.Show("Connection Succedded");
}
else
{
MessageBox.Show("Connection Fails");
}
}
catch (Exception ex)
{
MessageBox.Show("Error", ex.Message);
}
}
While compiling the program I got only connection fails message box, in the database. I found correct, how to overcome the program to get the connection succeeded message box.
Well, you're filling the ds data set - but then you're checking the dt data table for presence of rows... that's never going to work, of course!
If you only need a single DataTable - just use and fill that data table alone - no need for the overhead of a DataSet. Also, put your SqlConnection and SqlCommand into using blocks like this:
using (SqlConnection conn = new SqlConnection("Data Source=*******;Initial Catalog=ChatApp;User ID=Chatapplication;Password=****"))
using (SqlCommand cmd = new SqlCommand("Chatroomapp", conn))
{
string chatroomidno = textBox1.Text;
string chatroomname = textBox2.Text;
SqlDataAdapter adapt = new SqlDataAdapter(cmd);
adapt.SelectCommand.CommandType = CommandType.StoredProcedure;
adapt.SelectCommand.Parameters.Add(new SqlParameter("#ChatRoomID", SqlDbType.VarChar, 100));
adapt.SelectCommand.Parameters["#ChatRoomID"].Value = chatroomidno;
adapt.SelectCommand.Parameters.Add(new SqlParameter("#ChatRoomName", SqlDbType.VarChar, 50));
adapt.SelectCommand.Parameters["#ChatRoomName"].Value = chatroomname;
// fill the data table - no need to explicitly call `conn.Open()` -
// the SqlDataAdapter automatically does this (and closes the connection, too)
DataTable dt = new DataTable();
adapt.Fill(dt);
if (dt.Rows.Count > 0)
{
MessageBox.Show("Connection Succedded");
}
else
{
MessageBox.Show("Connection Fails");
}
}
And just because you get back no rows in dt.Rows doesn't necessarily mean that your connection failed..... it could just be that there are no rows that match your search critieria! The connection worked just fine - but the SQL command just didn't return any rows.
Connection failed means that something went wrong between your program and the database. No records returned does not mean that the connection failed. It just means that your table is empty - it contains no records.
Using ADO.NET and a stored procedures would have been a little different from what you have done it. If you need to check if the connection failed, maybe it is better to check the type of exception that is returned in the catch part.
Below is how I would have done it. I would have created a separate method that would have handled my call, and then in your button1_Click I would have just called this method:
public async Task<ChatRoom> GetAsync(string chatRoomId, string chatRoomName)
{
try
{
string connectionString = ConfigurationManager.ConnectionStrings["Db"].ConnectionString;
using (SqlConnection sqlConnection = new SqlConnection(connectionString))
{
await sqlConnection.OpenAsync();
using (SqlCommand sqlCommand = new SqlCommand("ChatRooms_Get", sqlConnection))
{
sqlCommand.CommandType = CommandType.StoredProcedure;
sqlCommand.Parameters.Add(new SqlParameter("#ChatRoomID", chatRoomId));
sqlCommand.Parameters.Add(new SqlParameter("#ChatRoomName", chatRoomName));
using (SqlDataReader sqlDataReader = await sqlCommand.ExecuteReaderAsync())
{
ChatRoom chatRoom = null;
if (await sqlDataReader.ReadAsync())
{
chatRoom = new ChatRoom();
chatRoom.Id = sqlDataReader.GetFieldValue<string>(0);
chatRoom.Name = sqlDataReader.GetFieldValue<string>(1);
chatRooms.Add(chatRoom);
}
return chatRoom;
}
}
}
}
catch (Exception exception)
{
// Try checking if the connection failed here
throw exception;
}
}
My chat room domain model could have looked like this:
public class ChatRoom
{
public string Id { get; set; }
public string Name { get; set; }
}
And the stored procedure would have looked like this:
CREATE PROCEDURE [dbo].[ChatRooms_Get]
(
#ChatRoomID VARCHAR(100),
#ChatRoomName VARCHAR(50)
)
AS
BEGIN
SET NOCOUNT ON;
SELECT
ChatRoomID,
ChatRoomName
FROM
tblChatRoom
WHERE
ChatRoomID = #ChatRoomID
AND ChatRoomName = #ChatRoomName;
END
GO
And then in the calling method you would get the chatroom and do with it whatever you need to do with it. For this example I just checked if it exists or not:
try
{
ChatRoom chatRoom = await chatRoomRepository.GetAsync(chatRoomId, chatRoomName);
if (chatRoom != null)
{
MessageBox.Show("Record found");
}
else
{
MessageBox.Show("No record found");
}
}
catch (Exception exception)
{
throw exception;
}
I hope this can help.

Categories