Generating connection string for EF code first program - c#

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

Related

C# login failed when connecting to SQL Server database for unit testing

I'm working on a project and when attempting to run a unit test to check progress, I get an error:
Initialization method UnitTestProject.UnitTest1.Init threw exception. System.Data.SqlClient.SqlException: Cannot open database "database" requested by the login. The login failed.
Login failed for user 'User\User1'
I've checked that User1 is owner in SQL Server and think I have the connection string right but I must be missing something obvious, please let me know :)
My repository class:
public class Repository
{
private string _connectionString;
public Repository()
{
_connectionString = configurationManager.ConnectionStrings["database"].ConnectionString;
}
public IEnumerable<Person> GetPeople()
{
var people = new List<Person>();
using (SqlConnection connection = new SqlConnection(_connectionString))
{
string commandText = "SELECT dbo.People.Id"
+ ", dbo.People.FirstName"
+ ", dbo.People.LastName"
+ ", dbo.People.Height"
+ ", dbo.People.Weight"
+ "FROM dbo.People";
SqlCommand command = new SqlCommand(commandText, connection);
try
{
connection.Open();
SqlDataReader reader = command.ExecuteReader();
while (reader.Read())
{
people.Add(new Person()
{
Id = reader.GetInt32(0),
FirstName = reader.GetString(1),
LastName = reader.GetString(2),
Height = reader.GetDouble(3),
Weight = reader.GetDouble(4)
});
}
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
}
return people;
}
}
My connection string in App.config:
add name="database"
connectionString="Data Source=localhost;Initial Catalog=database;Integrated Security=true"
My unit test:
public class UnitTest1
{
private Repository _repo;
[TestInitialize]
public void Init()
{
_repo = new Repository();
_repo.ResetDatabase();
}
[TestMethod]
public void GetPeople()
{
int count = _repo.GetPeople().Count();
Assert.IsTrue(count > 0);
}
}
Try adding the element to clear any connection strings that maybe previously defined:
<connectionStrings>
<clear />
<add name="DBConnection" connectionString="Data Source=xxxxxxxxxxx\xxxxxxxxx;Initial Catalog=xxxxx;Persist Security Info=True;User ID=xxxxxxxx;Password=xxxxxxxx"
providerName="System.Data.SqlClient" />
</connectionStrings>
It seems that creating a SQL server login with SQL authentication, i.e. user ID and password has allowed me to solve the login issue.
I then also had to update the connection string security from:
Integrated Security=true
to:
User id=admin;Password=password
Unfortunately I am now seeing this error when running the test:
Initialization method UnitTestProject.UnitTest1.Init threw exception.
System.Data.SqlClient.SqlException: A connection was successfully
established with the server, but then an error occurred during the
login process. (provider: Shared Memory Provider, error: 0 - No
process is on the other end of the pipe.) --->
System.ComponentModel.Win32Exception: No process is on the other end
of the pipe.
However there are existing solutions I'll be trying from:
No process is on the other end of the pipe (SQL Server 2012)

Connection string for local database not working

I have a database on my local machine on SQL Server Management studio.
The database connection information is as follows.
In my c# application, I have a connection string to connect to this database. I get an error though saying my connection string is incorrect. I have tried a number of different ones.
This is my function to connect to a database.
public virtual void openConnection()
{
con = new SqlConnection();
con.ConnectionString = "Server=DESKTOP-8UDMQUI\\WILLIAMSQL;Initial Catalog=team3db;TrustServerCertificate=true;";
try
{
con.Open();
}
catch (Exception ex)
{
Console.WriteLine(ex);
}
}
I have two \ in the server name because when I only have one, it has a red squiggle line under it throwing me an error on visual studio.
What should my connection string be? Note there is no password on this database.
Replace TrustServerCertificate = true; with Integrated Security = true

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();
}
}
}

What causes ArgumentOutOfRangeException on SqlConnection.Open()?

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".

Categories

Resources