I am a third party provider with a small app connecting to a larger database from a different supplier.
The supplier is running SQL Server Express: Server info
Although they have created a view for me and given me a user and password I'm having issues with my connection. On some sites (businesses) everything is instant and working.
On a few, there were connection failures (timeout):
Test connection failed because of an error in initialiing provider.
Login timeout expired
I created a UDL file and at this time noticed that the connection string was this:
Data Source= {dispenseDetails.dipenseServerCompName}\\ABCDEF;Initial Catalog=Integrations;User ID = {dispenseDetails.dbUserName};Password={dispenseDetails.dbPass}; Provider=SQLOLEDB.1;Persist Security Info=False;
Even in udl this was timing out the first test of connection. THEN it was connecting instantly when I pressed connect again.
So in my C# code I added timeout = 45
I changed from using sqlConnection to oleDBconnection as per the UDL file.
(Note: sqlConnection is working at 10 sites, and not working at 2)
When I tried this, my connection took 30 seconds and finally worked.
Upon retry it worked instantly, same as the UDl situation.
Can anyone provide ideas/insight into how to solve this??
In UDL I checked and on some terminals there is no "SQL SERVER NATIVE CLIENT"... just oledb!?
This is what I was using previously to try and solve this issue but I feel something isn't right and I'm barking up the wrong tree:
var conn = new SqlConnection(dispenseDetails.conString);
var retries = 10;
bool isConnected = false;
while (conn.State != ConnectionState.Open && retries > 0)
{
try
{
conn.Open();
isConnected = true;
}
catch (Exception exe)
{
Utility.LogFile($"test Con: {retries}", exe.Message, "Utility", "con section", crashApp: false);
}
Thread.Sleep(500);
retries--;
}
return isConnected;
In reality:
Is it ok to use OLEDB?
Why would I get a 40 sec connection then it's instant?
How would I change the con string so that it just works instantly?
Thanks to anyone with any ideas I can try.
As a note, the supplier has given me a VM for testing and everything works for me... it's just these 2 locations that do not work correctly, but since the supplier systems are working fine, they won't provide support which leads me to question my connection strings.
Related
I don't get it why my (very simple) code is working properly on my local machine from Visual Studio 2022 and on the local IIS 10 to connect to a sql server express (15) and on my webserver it's not. I'm sure that's a really simple quesion for you.
What I'm tryin' to do is a simple login page. My code in the Login.aspx is:
using System.Data;
using System.Data.SqlClient;
try
{
SqlConnection con = new SqlConnection(#"Data Source=BERLIN\SQLEXPRESS;Initial Catalog=membersarea; User ID=sa;Password=Test2022!");
SqlCommand sqlCmd = new SqlCommand("select * from useraccount where username=#userName and passWord=#Password", con);
sqlCmd.Parameters.AddWithValue("#userName", tbxUsername.Text.ToString());
sqlCmd.Parameters.AddWithValue("#passWord", tbxPassword.Text.ToString());
SqlDataAdapter sqlAdapter = new SqlDataAdapter(sqlCmd);
DataTable datatable = new DataTable();
sqlAdapter.Fill(datatable);
con.Open();
int i = sqlCmd.ExecuteNonQuery();
con.Close();
if (datatable.Rows.Count > 0)
{
Session["userName"] = tbxUsername.Text.ToString();
datatable.Dispose();
Response.Redirect("Content.aspx");
}
else
{
lblMessage.Text = "Benutzername oder Passwort falsch.";
lblMessage.ForeColor = System.Drawing.Color.DarkOrange;
lblMessage.Visible = true;
}
}
catch(Exception ex)
{
}
(I know that I'm not supposed to do this with the sa account, just to keep it simple... The only thing I do on the web server is to change the name of the sql server instance. Management Studio works fine with this User Id and Password on my web server. I installed the sql server using Plesk and I don't think it is working properly within plesk. Using the Management Studio I can restore backups, queries, create new accounts, etc.)
My Content.asps says Hi (including my name) and shows the Logout-Button. If you enter credentials that are not correct it says so and if you try to go to the content-Page without loggin' in you're redirected to the Login-page. That is what I want. Trouble is, it's not workin' on my webserver. It is simply doin' nothing. No error message, or something else. It takes a while, password is cleared again and username is still there. (Doesn't matter which credentials are used.)
I don't think that it comes to the first line of my code, and I don't know why. Are there DLLs that are needed, or what else did I forget? I'm pretty sure this is a absolute beginner problem but I can't figure it out.
Tried to fill in some code to alter the lblMessage, to find out where the problem starts, but nothing of it is displayed.
I think the trouble started when I checked the pattern web forms while creating the project. In the bin folder there is a "name-of-my-project".dll and a "name-of-my-project".pdb file. Those two are generated if you recreate your project. I'm pretty sure you guys know that - I did not. Or better I do know that they were generated, but not that they are necessary. (As I wrote before, I'm at the very beginning.)
In guess that in this *.pdb and/or *.dll the connection string is stored, too. When I recreate my project with the valid connection string for the web server and upload them, too - everything works as expected. Thank you, guys for your ideas.
I have looked for multiple Solutions for my Problem.
I have a program, that needs to insert/update/select data from a Database nearly all the time. And the program itself works, but the problem is, it should also work in a production system with our staff and this needs to be secure.
One of the main thing is:
How do I manage, that the program can connect to the DataBase from our Staff PC's, without mentioning in the Connection String the Username and Password.
Some People said, I should use Windows Authentication.
But where do I mention the user/password that will be used to connect to the database? I need it to work in a way, people cant see the Login-Data to manipulate the DB-Server, but the programm itself should still be able to connect to it.
How can I do it?
Here are 2 connection strings my Visual Studio generated for me:
"Data Source=domain,Port;Initial Catalog=Zeiterfassung;Persist Security Info=True;User ID=sa;Password=PW"
"Data Source=domain;Initial Catalog=Zeiterfassung;Integrated Security=True"
First one works fine, but the password is visible there. That shouldn't be. Even if I store it somewhere in the program, a decompiler will still make it visible.
Will the second string really work on ANY PC out there, that has internet connection and the program? So no one can see the Information need to Manipulate the program outside of the program or the Admin itself? Right now I can test on authorized PC's, that have a user which is manually added as authorized on the DB-Server, but what is with other users? The should only be able to connect to the DB with the Program, not manually with their Windows Account in MSSMS. Last thing should really be forbidden.
A Simple Code Snippet to clarify how the Connection looks for Example:
class Utility {
private static SqlConnection con;
static Utility() {
con = new SqlConnection();
con.ConnectionString = Properties.Settings.Default.DBPath1;
}
public static DataTableReader getSelectDataTableReader(string selectCommand, SqlParameter[] parameter) {
SqlDataAdapter adapter = new SqlDataAdapter(selectCommand, con);
if (parameter.Length > 0) {
adapter.SelectCommand.Parameters.AddRange(parameter);
}
DataSet ds = new DataSet();
try {
adapter.Fill(ds, "Table");
} catch (Exception ex) {
writeToLog(ex.Message);
return null;
}
return ds.Tables["Table"].CreateDataReader();
}
Below is a concise version of my code as it pertains to db access.
using System;
using System.Collections.Generic;
using System.Data.SqlClient;
namespace DataAccess
{
public class DbConnection
{
public string connString = "Data Source=[Insert IP];Initial Catalog=MOSAIQ;Persist Security Info=True;User ID=[Insert User];Password=[Insert Password]";
public void CreateConnection()
{
using (SqlConnection conn = new SqlConnection(connString))
{
try
{
conn.Open();
}
catch (Exception ex)
{
Console.WriteLine(ex);
}
}
}
}
For security reason I've removed IP and user credentials. That being said I copied the above connection string directly from the properties of the server explorer which successfully connected to my db.
While stepping through this code the following error is caught upon executing conn.Open()
Seems pretty obvious that there is an issue during validation. The credentials supplied are those used for SQL authentication.
Why is it that I can connect via server explorer but not directly via my code? What does Visual Studio's do for me that I can't seemingly do myself?
Ports are open, firewall is not an issue. I'm stumped and as a rookie in this matter would appreciate further guidance.
I'm trying to connect to SQL Server 2008 R2, using Visual Studio's 2013.
As a test try to use the SqlConnectionStringBuilder
System.Data.SqlClient.SqlConnectionStringBuilder builder = new System.Data.SqlClient.SqlConnectionStringBuilder();
builder["Data Source"] = "(local)";
builder["integrated Security"] = true;
//Or Supply User and Password
builder["Connect Timeout"] = 1000;
builder["Initial Catalog"] = "AdventureWorks;NewValue=Bad";
Console.WriteLine(builder.ConnectionString);
If you do that and are still experiencing the error then move on to testing the networking.
<add name="RM_V1.0CS1" connectionString="Data Source=SERVER;Initial Catalog=DB;User ID=sa;Password=Password" providerName="System.Data.SqlClient" />
Edit Explicitly Set Provider:
For those that might experience similar issues. I save my solutions on a network drive through work. Because I was opening and running my solution from this network location for a reason I'm yet unaware of it was using my windows credentials instead of the SQL credentials that I was passing to the SQL server. Once the solution was moved to my local workstation the method ran as expected. Any insight as to what more specifically was occurring would be of interest.
I've just started playing around with SQL on C#, and I'm trying to connect to a remote SQL server. I've added my IP to the list of hosts that have remote access permission.
My code keeps producing this error:
System.InvalidOperationException: Internal Connection Fatal Error.
at System.Data.SqlClient.TdsParserStateObject.TryPocessHeader<>
at System.Data.SqlClient.TdsParserStateObject.TryPrepareBuffer<>
at System.Data.SqlClient.TdsParserStateObject.TryReadByteArray<.Byte[] buff, Int32 offset, Int32 len, Int32& totalRead>
The trace is actually longer than that, but those are the first few lines.
This is the code that's causing the error (My actual connection string has the correct username, password, and database name):
connectionString = "Data Source=173.254.28.27,3306;Network Library=DBMSSOCN;Initial Catalog=myDatabase;User Id=myUserName;Password=myPassword;";
using (SqlConnection myConnection = new SqlConnection(connectionString))
{
try { myConnection.Open(); }
catch (Exception e) { Console.WriteLine(e.ToString()); }
}
Any help would be greatly appreciated.
Thanks!
EDITED
If you are using MySQL Server then your connection string is wrong!
try this connectionString :
_connectionStr = new MySqlConnectionStringBuilder
{
Server = "173.254.28.27",
Database = myDatabase,
UserID = myUserName,
Password = myPassword,
ConnectionTimeout=60,
Port = 3306,
AllowZeroDateTime = true
};
_con = new MySqlConnection(_connectionStr.ConnectionString);
try
{
_con.Open();
}
catch
{
Console.WriteLine("Error, help i can't get connected!");
}
If you are using SQLServer try disabling Connection Pool through connection string!
by adding :
Pooling=false
Good luck!
Create a udl file, if it connects then the problem is the code / application, if it does not connect, then it's your firewall, connections string, dll library etc. Well the important thing here is probably the connection string. Do the following: create an empty text file and rename it "myconnection.udl". Now double click on the file and it will launch an applet. You can configuer the connection to your database and test it. (it will pick up registered connection libraries etc). If it give OK, then open the udl file in notepad, you will see the correct connection string. Paste to your app connection settings. UDL files are generally misunderstood. They are simply a text file that holds the connection settings. They then call the connection dll. If the udl file works then you have a correct connection string 100%
I have a SQL Server database in a C# project.
I use a connection string to connect to it.. I can use the method ExecuteNonQuery to insert data, no problem there.
But when I delete, it only deletes it momentarily, as soon as I restart the application it kind of rolls back the deletion.. Any ideas?
PS: I tested the string in a direct query, and it worked fine there.
public void executeNonQuery(string input)
{
db.Open();
SqlCommand cmd = new SqlCommand(input, db);
cmd.ExecuteNonQuery();
db.Close();
}
EDIT: DELETION CODE:
private void buttonSletPost_Click(object sender, EventArgs e)
{
if(dataGridView1.GetCellCount(DataGridViewElementStates.Selected)>0){
for (int i = 0;i < dataGridView1.GetCellCount(DataGridViewElementStates.Selected); i++)
{
String str1 = String.Format("WARNING about to DELETE:\n {0} \n BE CAREFULL NO TURNING BACK NOW!", Regnskab.getInstance().dbSelectPostID(dataGridView1.SelectedCells[i].Value.ToString())[0].ToString());
if (MessageBox.Show(str1, "Confirm Deletion", MessageBoxButtons.YesNo) == DialogResult.Yes)
{
string str = String.Format("DELETE FROM PostTable WHERE PostID={0}", dataGridView1.SelectedCells[i].Value.ToString());
Database.getInstance().executeNonQuery(str);
Console.WriteLine(str);
}
}
}else {MessageBox.Show("No cells selected");}
}
Which will give following output:
DELETE FROM PostTable WHERE PostID=7
Connection string in app.config:
<connectionStrings>
<add name="EndProject.Properties.Settings.DBtestConnectionString" connectionString="Data Source=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|\DBtest.mdf;Integrated Security=True;Connect Timeout=30;User Instance=True" providerName="System.Data.SqlClient" />
private Database()
{
string connStr = ConfigurationManager.ConnectionStrings["EndProject.Properties.Settings.DBtestConnectionString"].ConnectionString;
db = new SqlConnection(connStr);
}
And then I open and close it, so the connection ain't open each time.
To be honest:
I don't exactly know where to see my DB info, here's some info from properties in VS2010.
Provider: .NET Framework Data Provider for SQL Server
Type: Microsoft SQL Server
Andrew's 3rd: I think they are deleted momentarily because I reloaded the information in my datagridview and from there it is gone. But then when I close the application and start it again, it is back...
Also i just checked with VS2010's server explorer and did a "Show Data" after I deleted (before I shut it down) and it wasn't deleted.
But I'm totally clueless now. :-(
Many applications use Transactions to manage db connections. SQL Server doesn't do it by default, but other factors in your application may be doing this.
Also, if you're really doing this, and your input is coming from a user interface, I can't wait to introduce you to Little Bobby Tables
Use the SQL Server Profiler to run a trace and capture the actual T-SQL statements that are getting executed on the database.
This is the easiest solution.
The behavior you're describing sounds like autocommit is off. Try the following and see if the record(s) stays deleted:
public void executeNonQuery(string input)
{
db.Open();
using (var txn = db.BeginTransaction())
{
SqlCommand cmd = new SqlCommand(input, db);
cmd.Transaction = txn;
cmd.ExecuteNonQuery();
db.Close();
txn.Commit();
}
}
Ok it was apperently me who was mistaken on the inserting part...
Someone suggested that i was because of the Visual Studio databases created every time the applikation ran.
So i installed MS SQL 2008 R2. Created a new DB with same layout.
Changed the connection string
And wuupti woo it seems to work, ill come back to this thread if it breaks down later..
But delete + insert both working greatly now :-)
Thanks to all who tried to help!