What causes ArgumentOutOfRangeException on SqlConnection.Open()? - c#

In trying to write a simple C# ADO.NET application to connect to my database and manage project entries for my website, I've run into a strange problem that I can not find any information regarding. I've verified that my MySQL server is accepting remote connections, listening on port 3306, the username provided is valid, as is the password, and the hostname resolves correctly. However, when SqlConnection.Open is called, I receive a nonsensical exception.
System.ArgumentOutOfRangeException was unhandled
Non-negative number required.
Parameter name: count
Below is the code that invokes said error, specifically on the call to m_ActiveConnection.Open()
static public void OpenConnection(CConnectionDescription ConnectionDescription)
{
try
{
SqlConnectionStringBuilder ConnectionStringBuilder = new SqlConnectionStringBuilder();
ConnectionStringBuilder.DataSource = ConnectionDescription.Address + "," + ConnectionDescription.PortNumber;
ConnectionStringBuilder.UserID = ConnectionDescription.UserName;
ConnectionStringBuilder.Password = ConnectionDescription.Password;
ConnectionStringBuilder.NetworkLibrary = "DBMSSOCN";
if (m_ActiveConnection != null)
{
if (m_ActiveConnection.State != System.Data.ConnectionState.Closed)
{
m_ActiveConnection.Close();
}
m_ActiveConnection.ConnectionString = ConnectionStringBuilder.ConnectionString;
}
else
{
m_ActiveConnection = new SqlConnection(ConnectionStringBuilder.ConnectionString);
}
m_ActiveConnection.Open();
m_ActiveConnectionDescription = ConnectionDescription;
if (ConnectionChanged != null)
{
ConnectionChanged();
}
}
finally
{
// Error message
}
}
What can cause this exception? I'm not passing any parameters to open and the ConnectionString seems completely valid. I've checked the values of the CConnectionDescription my self. Any help would be appreciated.

As far as I know, SqlConnection is used to connect to SqlServer databases. You should be using MySqlConnection from "MySQL Connector/Net".

Related

Usage of MySQL Parameter for creating new user

So I am using a MySQL Server version 8.0.16 and if I try to let dynamically create a new user, i do receive a Error message what says: >>You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax. to use near '$password' at line 1<<.
What i can't understand, becouse if i replace the Parameters with the actual value and try it with the shell it works perfectly. I let my code connect as root so and checked if the connection is open what it is. So if I stepped into the code and checked if the parameters are correct everything looked fine. I also added >>'<< at the beginning and end of thext strings that should replace the parameters but it didn't changed the error or what happened.
public bool CreateNewUser(string name, string password, string host)
{
string query = "CREATE USER $name#$host IDENTIFIED BY $password;";
List<MySqlParameter> mies = new List<MySqlParameter>
{
new MySqlParameter("$name", name),
new MySqlParameter("$password", password),
new MySqlParameter("$host", host)
};
return InsertIntoQuery(query, mies);
}
//The InsertIntoQuery looks like this
private bool InsertIntoQuery(string sql, List<MySqlParameter> sqlParameters = null)
{
bool retBl = false;
try
{
using (var SqlConnection = new MySqlConnection(ConnectionStr))
{
SqlConnection.Open();
using (var cmd = new MySqlCommand(sql, SqlConnection))
{
if (sqlParameters != null)
foreach (var item in sqlParameters)
cmd.Parameters.AddWithValue(item.ParameterName, item.Value);
cmd.Prepare();
var retValNonQuery = cmd.ExecuteNonQuery();
retBl = (retValNonQuery > 0) ? true : false;
}
}
}
catch (Exception e)
{
MessageBox.Show("Error: " + e.Message);
}
return retBl;
}
I would expect it to create a new user but it doesn't.
No, for CREATE USER command I don't think you can pass command parameter likewise. Rather substitute the value as is like below using string interpolation syntax.
string query = $"CREATE USER '{name}#{host} IDENTIFIED BY {password}";
For an older C# version consider using string.Format()
string query = string.Format("CREATE USER '{0}'#'{1}' IDENTIFIED BY '{2}'",name,host,password);
Per OP's comment: You can't cause it's not a DML operation. If you are worried about SQL Injection probably cause input value is coming from user input then you will have sanitize it someway and moreover if you observe the input are quoted.
Again, I would suggest that this kind of admin operation should go in a DB bootstrap script and not in your application code.

Web service returns different value each time I request

I got a web service running on c# but recently, something strange happened. Even when I query from a simple table with only 1 value like this:
string str = "";
using (SqlConnection connection = new SqlConnection(ConfigurationSettings.AppSettings["Main.ConnectionStringTD"]))
{
connection.Open();
try
{
SqlCommand selectCommand = new SqlCommand
{
CommandType = CommandType.Text,
Connection = connection,
CommandText = "select Version from TN_Version"
};
str = selectCommand.ExecuteScalar().ToString();
}
catch (Exception exception)
{
str = "ERROR:" + exception.Message + "_" + exception.InnerException.Message;
Console.WriteLine(exception.Message ?? "");
}
return str;
}
This always returns correct value when I debug on local but an error message returned whenever I publish this service on host and execute it:
There is no row at position 0.
It's really strange cuz this is a simple table and absolute nothing changes or delete its value...
Error
And I have to execute the service 3 or 4 times until it gets me the correct value:
<string xmlns="http://webservice.com/">6.7</string>
Please, someone helps me, this have been bugging me to no end. Thanks you so much (really)
The error message simply means that no rows were returned by your query. so maybe, after you hosted the app, either IIS or a firewall causing this problem in the connection. Check with the firewall turned off and check the rights of your IIS user account.

Generating connection string for EF code first program

I'm using code first approach with EF. Need to generate connection string from user input when program is started for first time.
Here's simple method to check if it can connect right now I'm trying to get some data because it happened that it was possible to open/close connection during test but getting any data was throwing exceptions:
public static bool IsConnectionValid(string connectionString)
{
if (string.IsNullOrWhiteSpace(connectionString)) return false;
using (var context = new HolidayCalendarContext(connectionString))
{
try
{
context.Database.Connection.Open();
var contex = context.Employees.ToList();
context.Database.Connection.Close();
return true;
}
catch (Exception e)
{
return false;
}
}
}
Now here I generate connection string, UserName and Password are optional, password may be provided as parameter later on:
private string GenerateConnectionString()
{
var builder = new SqlConnectionStringBuilder
{
DataSource = Source,
InitialCatalog = Catalog,
IntegratedSecurity = true,
ConnectTimeout = CONNECTION_TIMEOUT
};
if (!string.IsNullOrWhiteSpace(UserName))
{
builder.UserID = UserName;
}
if (!string.IsNullOrWhiteSpace(Password))
{
builder.Password = Password;
}
return builder.ToString();
}
The method I test is an action bound to "Login to db" button. SaveConnection simply stores correct connection string in config file and ChangeUtility is just navigation stuff irrelevant at this point.
private void LoginToDatabaseExecute(object obj)
{
if (ValidateInput())
{
var connectionString = GenerateConnectionString();
if (TestConnection(connectionString))
{
SaveConnection(connectionString);
ChangeUtility(new LoginViewModel(MainViewModel));
}
}
}
So I've got the test for generating those strings, the test passes. Checked with debugger, it connects and gets Employees correctly:
[TestMethod]
public void SuccessfulConnectionStoresConnectionStringInSettings()
{
SetCorrectConnectionString();
_viewModel.LoginToDatabaseCommand.Execute(null);
var connectionString = SettingsHelper.GetConnectionString();
Assert.IsFalse(string.IsNullOrWhiteSpace(connectionString));
}
private void SetCorrectConnectionString()
{
_viewModel.Source = "YOGER\\SQLEXPRESS";
_viewModel.Catalog = "HolidayCalendar";
_viewModel.UserName = "";
_viewModel.Password = "";
}
And here's the problem. After test passed I launched program, set the same input, got identical connection string as from the test "Data Source=YOGER\\SQLEXPRESS; Initial Catalog=HolidayCalendar; Integrated Security=True; Connect Timeout=5" but connection failed at the point where IsConnectionValid tries to open it, throwing "Keyword not supported: 'initial catalog'." System.ArgumentException
Exception thrown: 'System.ArgumentException' in System.Data.SqlServerCe.dll
Exception thrown: 'System.ArgumentException' in System.Data.dll
I've been already tried EntityConnectionStringBuilder but it required Metadata, which I found code first doesn't have so I coulnd't get it working.
You are trying to connect to a SQL Express, but the exception is thrown from SqlServerCe.dll. It indicates, that your program uses the provider for SQL CE.
I would check entityFramework.defaultConnectionFactory section in your app.config` file. For SQL Express it should be set to
<defaultConnectionFactory type="System.Data.Entity.Infrastructure.SqlConnectionFactory, EntityFramework">
Exception thrown:
'System.ArgumentException' in System.Data.SqlServerCe.dll
Exception thrown:
'System.ArgumentException' in System.Data.dll
means till you are point out on SQL Server CE database not on SQL Server Express

C# MySql.Data.MySqlClient.MySqlException Error for no reason

For the past month I've been getting data with a C# program in tandem with a company's API. Just yesterday all the sudden it would no longer work, even though I haven't changed the code at all. Here's the code:
public string GetMatchCode()
{
//this could be loaded from config file or other source
string connectString = "Server=123.123.1.23;Database=blah_users;Uid=blah_data;Pwd=blahblah;";
string sql = "SELECT MAX(match_id) FROM `data_blah`";
using (var connect = new MySqlConnection(connectString))
using (var command = new MySqlCommand(sql, connect))
{
connect.Open();
return command.ExecuteScalar().ToString();
}
}
And I get this error:
An unhandled exception of type 'MySql.Data.MySqlClient.MySqlException' occurred in MySql.Data.dll
Additional information: Access denied for user 'blah_data'#'cpe-86-80-21-54.san.res.rr.com' (using password: YES)
Any idea what could have happened and how to fix it? The only thing I think could've happened is that my support ticket dealing with node.js compatibility was executed wrong by support employees. Thanks!
Your db user's permission has failed. The user may have been removed; the permissions may have been modified. Contact the db owner.
So it looks like you are not authenticating: Either incorrect credentials or server needs a different method. Try disabling "sslmode" like below:
public string GetMatchCode()
{
//this could be loaded from config file or other source
string connectString = "Server=123.123.1.23;Database=blah_users;Uid=blah_data;Pwd=blahblah;sslmode=none;";
string sql = "SELECT MAX(match_id) FROM `data_blah`";
using (var connect = new MySqlConnection(connectString))
using (var command = new MySqlCommand(sql, connect))
{
connect.Open();
return command.ExecuteScalar().ToString();
}
}
That should do it
string sql = "SELECT MAX(match_id) FROM `data_blah`";
Isn't it supposed to be " ' " instead of " ` " surrounding "data_blah"?

How to test connection to a data source in SSAS using C#

I have a database in Analysis Services on a remote server. This contains a data source for another database located on another remote server.
I am trying to write a connectivity test using C# which will check the database connection between the two databases.
I have been unable to do this using ADOMD.NET. I'm currently looking at using SMO to do this but I haven't had any luck so far.
I would greatly appreciate any advice or suggestions.
Update:
After further research, I have come up with the below test (Please note that I intend to add more try..catch blocks and Assertions later).
Also, this uses C:\Program Files\Microsoft SQL Server\100\SDK\Assemblies\Microsoft.AnalysisServices.DLL to access the Server, Database and
DataSource classes.
class ConnectivityTests
{
// Variables
String serverName = "";
String databaseName = "";
String dataSourceName = "";
[Test]
public void TestDataSourceConnection()
{
// Creates an instance of the Server
Server server = new Server();
server.Connect(serverName);
// Gets the Database from the Server
Database database = server.Databases[databaseName];
// Get the DataSource from the Database
DataSource dataSource = database.DataSources.FindByName(dataSourceName);
// Attempt to open a connection to the dataSource. Fail test if unsuccessful
OleDbConnection connection = new OleDbConnection(dataSource.ConnectionString);
try
{
connection.Open();
}
catch (OleDbException e)
{
Assert.Fail(e.ToString());
}
finally
{
connection.Close();
}
}
I believe that this test is sufficient for my testing (Once I've added some more try..catch blocks and Assertions). If the test passes, it means there are no connectivity issues between my machine and both servers, which implies that there shouldn't be any connectivity issues between the servers.
However, I have been unable to work out how to test the connection between the two servers directly and I am interested if anyone knows a way of doing this.
The best solution I have come across to doing this connectivity test is below:
Please note that this requires the Microsoft.AnalysisServices.DLL to be added as a reference.
class ConnectivityTests
{
// Variables
String serverName = "";
String databaseName = "";
String dataSourceName = "";
[Test]
public void TestDataSourceConnection()
{
try
{
// Creates an instance of the Server
Server server = new Server();
server.Connect(serverName);
// Gets the Database from the Server
Database database = server.Databases[databaseName];
// Get the DataSource from the Database
DataSource dataSource = database.DataSources.FindByName(dataSourceName);
// Attempt to open a connection to the dataSource. Fail test if unsuccessful
OleDbConnection connection = new OleDbConnection(dataSource.ConnectionString);
connection.Open();
}
catch (Exception e)
{
Assert.Fail(e.ToString());
}
finally
{
connection.Close();
}
}
}

Categories

Resources