How to central the db connection in c# .net? - c#

Does anyone know how can I central the db connection in c# .net (perhaps in the mian.master)?
I have the following code for the db connection and used to call to the difference stored proc to retrieved data.
string strConnString = ConfigurationManager.ConnectionStrings["testString"].ConnectionString;
SqlConnection mySqlConnection = new SqlConnection(strConnString);
SqlCommand mySqlCommand = mySqlConnection.CreateCommand();
mySqlCommand.CommandText = "EXEC app_campaign_select #CampaignID=" + Request.QueryString["ixCampaign"].ToString();
mySqlConnection.Open();
SqlDataReader mySqlDataReader = mySqlCommand.ExecuteReader();
Instead of coding it in every pages and connection to the db multiple times, any way I can code the following connection code in the master page and only connecting to the db once, then each page can call it when need to be connect into the db
string strConnString = ConfigurationManager.ConnectionStrings["testString"].ConnectionString;
SqlConnection mySqlConnection = new SqlConnection(strConnString);
SqlCommand mySqlCommand = mySqlConnection.CreateCommand();
SqlDataReader mySqlDataReader;

Add it to a static DAL class and add parameters as needed.
public static void YourFunction() {
// your code
}
Note:
Beware this line: mySqlCommand.CommandText = "EXEC app_campaign_select #CampaignID=" + Request.QueryString["ixCampaign"].ToString();
If that QueryString comes from a user entered value somewhere, you could be open to SQL Injection.

Sure. Just create a helper class that has a few static methods in them for each type of return type you could have. Pass to one a string for stored procedure name and have an overloaded one that takes a string for a sql statment that you would pass in. You can also have one that just returns back a scalar value as well. So you would probably have 3 or so static methods you could call from any page.

Related

How to use a database connection class in my entire application

I have created a class for the MS Access database connection. It works fine on the majority of the forms within my Winforms app. However, I have a form where the user can add, edit or delete information from the database. I've constructed that part using a string, but when I remove the long database connection string I had there before and replace it with the class I created it throws an exception.
I've tried changing the code by removing the string, but I want to use the string method.
This is the code I have for the delete button click event
string con = (#"Provider = Microsoft.ACE.OLEDB.12.0; Data Source =C:\Users\folder\Desktop\ApplicationFolder\AppName\bin\Debug\DataBase\DatabaseName.accdb");
string Query = "delete from Employees2 where EmployeeName = '" +
this.txtAdminFEmployee.Text + "' ; ";
OleDbConnection ConnectionString = new OleDbConnection(con);
OleDbCommand command = new OleDbCommand(Query, ConnectionString);
OleDbDataReader reader;
try
{
ConnectionString.Open();
reader = command.ExecuteReader();
DialogResult result = MessageBox.Show("Employee Deleted Successfully",
"Information",
MessageBoxButtons.OK, MessageBoxIcon.Information);
while (reader.Read())
{
}
}
catch (Exception ex)
{
MessageBox.Show("Error " + ex);
ConnectionString.Close();
This is the database class I created
using System.Data.OleDb;
namespace AppName
{
class OledbConnect
{
public OleDbConnection con;
public void Connection()
{
con = new OleDbConnection(#"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=|DataDirectory|\DatabaseName.accdb");
}
}
}
I need to know how to use the database class in that string. I've tried different ways but nothing works. I am still new to c# and Google is not really returning anything I can use. Thanks
Your initial code works, but confusion is evident in the naming of variables.
string con = #"Provider = Microsoft.ACE.OLEDB.12.0; Data Source =C:\Users\folder\Desktop\ApplicationFolder\AppName\bin\Debug\DataBase\DatabaseName.accdb";
(I've taken the un-needed parentheses off the declaration; it's just a string.)
Calling that string 'con' is a bit confusing. I'd call it 'connectionString', or maybe 'cs' for short.
OleDbConnection ConnectionString = new OleDbConnection(con);
OleDbCommand command = new OleDbCommand(Query, ConnectionString);
OK, so you correctly create an OleDbConnection, passing the connection string (con) to its constructor. This is good. But you confusingly call it ConnectionString. It isn't the connection string; it's the connection, and your code thereafter uses it correctly.
So that works. Confusing for a human to read because of the mis-naming of variables, but the compiler doesn't care what their names are - it knows very well that ConectionString is an OleDbConnection and doesn't feel any of the cognitive dissonance that I do when I look at it.
If you rename the variables in the original code as I've suggested, and then copy that code into your class (BTW, I'd just call it DbConnection; it's current name is very close to another class name which might also be confusing), paying attention to what each statement does and what each variable represents then you should be good to go.

C# function that calls a SQL stored procedure works when used from local machine but fails when called from an Azure function in the cloud

I created this C# file that takes a JSON document as input, processes data and then sends the processed data to an SQL database. The eventuall plan is to put it in the cloud as an Azure function with a trigger for any new document entering an Azures CosmosDB.
Currently the part of the code responsible for sending the information to SQL looks like this:
public void Store (PushData i)
{
using (SqlConnection conn = new SqlConnection("Server=<serverconnection>;DataBase=<DBName>;User ID=<ID>;Password=<PW>"))
{
conn.Open();
// 1. create a command object identifying the stored procedure
SqlCommand cmd = new SqlCommand("ActualsCreator", conn);
// 2. set the command object so it knows to execute a stored procedure
cmd.CommandType = System.Data.CommandType.StoredProcedure;
// 3. add parameter to command, which will be passed to the stored procedure
cmd.Parameters.AddWithValue("#Date", i.Date);
cmd.Parameters.AddWithValue("#AvailabilityTime", i.MinutesUptime);
cmd.Parameters.AddWithValue("#EnvName", i.EnvName);
cmd.Parameters.AddWithValue("#MeaName", i.MeaName);
cmd.Parameters.AddWithValue("#MeaType", i.MeaType);
cmd.Parameters.AddWithValue("#LastUpdate", i.LastUpd);
cmd.Parameters.AddWithValue("#ClusterStatus", i.Status);
cmd.Parameters.AddWithValue("#ResourceID", i.ResID);
cmd.Parameters.AddWithValue("#MidnightTime", i.MinutesUptimeForMidnight);
// execute the command
using (SqlDataReader rdr = cmd.ExecuteReader())
{
}
}
}
When run localy all the information makes it to the SQL server without an issue, however when run from the azure function it will fail at "#MeaName" or "#EnvName" or "#ResourceID".
[Error] Exception while executing function: Functions.monitorResultFullTrigger. mscorlib: Exception has been thrown by the target of an invocation. .Net SqlClient Data Provider: Procedure or function 'ActualsCreator' expects parameter '#MeaName', which was not supplied.
Whichever one fails is whichever one is stated first in the code. The only thing these 3 have in common over all the other types is they are stored as nvarchar(50) in the SQL database. The error message indicates that nothing is being passed to the parameter, but the exact same code doesnt have this issue localy, and none of the other variables but those 3 have this issue either.
My question is what can cause this? Why does it only fail in the Azure function when in the cloud and why only the nvarchar types.
Please try to specify the SqlDbType in our code, we can do like below:
SqlParameter para = new SqlParameter("#MeaName", SqlDbType.NVarChar) { Value = i.MeaName };
cmd.Parameters.Add(para);
Hope it will be helpful
Try like the below one for all the parameters
using (SqlConnection sqlConnection = new SqlConnection(CONNECTIONSTRING))
{
using (SqlCommand sqlCommand = new SqlCommand(#"ActualsCreator", sqlConnection))
{
//define sqlcommandtype as SP
sqlCommand.CommandType = CommandType.StoredProcedure;
//define induvidual parameters for the SP
SqlParameter Param_MeaName = sqlCommand.CreateParameter();
Param_MeaName.ParameterName = #"#MeaName";
Param_MeaName.SqlDbType = SqlDbType.NVarChar;
Param_MeaName.Size = 50;
Param_MeaName.Direction = ParameterDirection.Input;
Param_MeaName.Value = i.MeaName;
//Add the paramters in the sqlcommand
sqlCommand.Parameters.Add(Param_Order_Key);
//Open the connection
sqlConnection.Open();
//Execute the SP
SqlDataReader sqlDataReader = sqlCommand.ExecuteReader();

OleDB connection string for SQL Server in a C# program

I have seen lots of answers to connect to MS Access via OleDB but there is not good answer for SQL Server. I try to connect to a SQL Server database via OleDB provider in my C# program.
This is the connection string I am providing.
Provider=SQLOLEDB;Data Source=<servername>;Initial Catalog=<dbname>;Integrated Security=SSPI
But it gives me error
‘Keyword not support ‘Provider’’
What I want to do here is connect database via OleDB in C# program.
This works as expected on my side. From the error message I strongly suspect that you are using the SqlConnection class instead of the OleDbConnection (Of course you need to use all the other classes provided by OleDb like OleDbCommand, OleDbDataReader etc...)
string connStr = "Provider=SQLOLEDB;Data Source=<servername>;Initial Catalog=<dbname>;Integrated Security=SSPI";
using(OleDbConnection cnn = new OleDbConnection(connStr))
{
....
}
When in doubt, use the string builder in visual studio. That way unsupported keywords can't creep into your connection strings, the following is a wonderful example on how to use it.
http://www.c-sharpcorner.com/uploadfile/suthish_nair/how-to-generate-or-find-connection-string-from-visual-studio/
The same Connection string is working fine at my end.
I am posting my sample code which is executes successfully at my end
public string connStr = "Provider=SQLOLEDB;Data Source=.;Initial Catalog=<dbName>;Integrated Security=SSPI";
public OleDbConnection con;
protected void Page_Load(object sender, EventArgs e)
{
Test();
}
public void Test()
{
con = new OleDbConnection(connStr);
con.Open();
OleDbCommand cmd = new OleDbCommand("select * from tblApartments", con);
OleDbDataAdapter da = new OleDbDataAdapter(cmd);
DataSet ds = new DataSet();
da.Fill(ds);
con.Close();
}
Please place breakpoint and check line to line and when your breakpoint comes to con.close(); then check ds, you can see the output.
The connection string you're using, considering the OLE DB provider, is correct. I didn't find any error in the connection string used, if you want to connect to a SQL Server data source.
Most probably, the reason of that error should be that you're not using correctly all the classes and objects required by the OLE DB provider, like OleDbCommand (that is similar to a SqlCommand but it's different), OleDbConnection, OleDbDataAdapter and so on. In a nutshell, the reason of that error should be this:
string connStr = "Provider=SQLOLEDB;Data Source=<servername>;Initial Catalog=<dbname>;Integrated Security=SSPI";
using(SqlConnection scn = new SqlConnection(connStr))
{
....
}
Indeed, using a SqlConnection object, the ConnectionString property doesn't support the keyword Provider and, executing your application, you got an error about a keyword not supported.
Have a look at this simple tutorial about the use of OLE DB provider.

Dynamically choose SQL Server or Oracle database

I have an application that allows my user to run queries against a database of their choice. The database can be either SQL server or Oracle. this method accepts two parameters from another class, first parameter is the connection string to the database the user chooses, and the second is the database type. that part works fine. what I am trying to do is cut back on the code I need to write and not type the query and connection stuff over and over. so, I would like to do something like this. Obviously this wont work, but I'm open to most solutions.
public void createTable(string connectstring, string rdbms)
{
if (rdbms == "oracle")
{
con = new OracleConnection(connectionString);
con.Open();
OracleCommand query = con.CreateCommand();
}
else if (rdbms == "SQL Server")
{
con = new SqlConnection(connectionString);
con.Open();
SqlCommand query = con.CreateCommand();
}
else
{
// broke
}
query.CommandText = "CREATE TABLE " + RndName +
" (Col0 Varchar(10),Col1 Varchar(10), Col2 Varchar(10))";
query.ExecuteNonQuery();
con.Close();
executeInsertTransactions(connectstring);
}
This problem is generally solved via interfaces. There may be these common interfaces:
IConnection
IDataProvider
IRepository
Implement interfaces using MySql database, such as class MySqlConnection : IConnection. For Oracle, add class MsOracleConnection : IConnection.
Ideally you should abstract all the functionality into common interfaces. You will have to provide implementations for each database/storage engine you want to support. At runtime, you will use IoC container and DI principle to set up the current implementation. All the child dependencies will use interfaces passed in as parameters to constructor (or properties or methods)
You can create more abstract code by leveraging the framework's DbProviderFactory and using the obtained Db* classes.
Dim con As System.Data.IDbConnection
Dim cmd As System.Data.IDbCommand
Select Case ConDBType
Case TypeDatabase.SqlServer
con = New OleDbConnection(CN.ConnectionString)
cmd = New OleDbCommand
Case TypeDatabase.MySql
con = New MySqlConnection(CNMySql.ConnectionString)
cmd = New MySqlCommand
Case TypeDatabase.Access
Call InitNameing()
ConDBAccess.DataSource = PreparToRootNameing() & "\T" & NAME_SYSTEMDB
con = New OleDbConnection(CN.ConnectionString)
cmd = New OleDbCommand
End Select
cmd.Connection = con
con.Open()
cmd.CommandText = SQLUpdate
cmd.ExecuteNonQuery()

Getting an error while invoking bytes from database

I have stored an image in SQL Server. First I have converted the image into bytes and I have saved it in SQL Server and very much done with saving.....when I try to invoke the respective image's bytes value from SQL Server which I saved and when I try to implement that in C#, I am getting a error like
NullReferenceException was unhandled by user code
Object Reference not set to an instance of an object
Here is my code:
protected void GetImageButton_OnClick(object sender, EventArgs e)
{
SqlConnection connection = new SqlConnection();
connection.ConnectionString = #"";
connection.Open();
SqlCommand command = new SqlCommand();
command.Connection = connection;
command.CommandType = CommandType.StoredProcedure;
command.CommandText = "uspgetimage";
command.Parameters.AddWithValue("#imageID", getimagebutton.Text);
DataSet dataset = new DataSet();
SqlDataAdapter adapter = new SqlDataAdapter();
adapter.SelectCommand = command;
adapter.Fill(dataset);
Byte[] bytes = command.ExecuteScalar() as byte[];
string base64String = Convert.ToBase64String(bytes, 0, bytes.Length);
Image.ImageUrl = "data:image/jpeg;base64," + base64String;
}
Kindly have a look on it and help me to get out from this friends.
Before NullReferanceException, I don't believe this lines don't throw any exception..
SqlConnection connection = new SqlConnection();
connection.ConnectionString = #"";
connection.Open();
You can't open a connection before you initialize SqlConnection.ConnectionString property. In your case, your connection string is an empty string. How do you expect this connection connect to your sql server?
My suggestion is, read a book about C# and using it with databases like Begining C# 5.0 Databases
For NullReferanceException, I already mentioned in my comment what you should do.
It's likely that you're getting a NullReferenceException from your call to ExecuteScalar. From the documentation:
Return Value
The first column of the first row in the result set, or a null reference ... if the result set is empty.
Emphasis mine.
And for what it's worth, SqlConnection, SqlCommand, DataSet and SqlDataAdapter are all IDisposable. You should call Dispose on them, although the value of disposing DataSet is arguable.
Try running the stored procedure in SQL Server to see if it returns any value using
EXEC uspgetimage 'COmma seperated Parameter List'

Categories