How to access connection string & connect to database - c#

So I'm working on a project involving an external API and a database. This API uses an API specific project type called an Add In and is compiled as a library, then added to the API's source program. This way, I can create self-created 'actions' within in the Add in for the program and call them remotely from a MVC web project. This action contains code also related to updating a database uploaded on a server. When I tried to call this action remotely, I would get this error within the application the add in was added to:
A network-related or instance-specific error occurred while establishing a connection to SQL server. The server was not found or was not accessible. Verify that the instance name is correct and that SQL server is configured to allow remote connections. (provider: SQL Network Interfaces, error: 26 - Error Locating Server/Instance Specified)
I've gotten help with my mentor and troubleshooted the connection string inside the Add Ins app.config. It's verified to be correct (I can access the database directly from the web MVC project). I tried reading the connection string using var connectionString = ConfigurationManager.ConnectionStrings["DefaultConnection"].ConnectionString; in the project, and it just can't be found. When the action is called I get a null object reference error.
Here's my app config for the Add In:
<?xml version="1.0" encoding="utf-8"?>
<configuration>
<connectionStrings>
<add name="DefaultConnection" connectionString="Data Source=PROD4W\PROD4W;Initial Catalog=EplanInterfaceDb;user id = SomeID; password=SomePassword;Integrated Security=False" providerName="System.Data.SqlClient"/>
</connectionStrings>
</configuration>
Here's my code related to the database inside my add In project:
//Here is where my mentor tried to pull the connection string from the //app.config.This is where the object reference error
var connectionString = ConfigurationManager.ConnectionStrings["DefaultConnection"].ConnectionString;
//Output the connection string to the screen on outside app
new Decider().Decide(EnumDecisionType.eOkDecision, "Connection: " + connectionString, "", EnumDecisionReturn.eOK, EnumDecisionReturn.eOK);
//Access the database and add a test
using (var context = new DataContext())
{
//Throws network related error mentioned above
context.Macros.Add(new Macro { Name = "test" });
context.SaveChanges();
//Output to the screen if the savechanges was successful
new Decider().Decide(EnumDecisionType.eOkDecision, "Save Changes Called ", "", EnumDecisionReturn.eOK, EnumDecisionReturn.eOK);
}

Using what Mason recommended below you can simply hard code your connection string instead of pulling it from the app.config if it is giving you issues.. Here is an example:
var connectionString = "Hard code connection string";
//Make sure your DataContext has a constructor that takes in a connection string
using (var context = new DataContext(connectionString))
{
context.Macros.Add(new Macro { Name = "test" });
context.SaveChanges();
//Output to the screen if the savechanges was successful
new Decider().Decide(EnumDecisionType.eOkDecision, "Save Changes Called ", "", EnumDecisionReturn.eOK, EnumDecisionReturn.eOK);
}

Related

SQL Server Connection String in Trusted Connection format doesn't work

first time using sql with C# and I seem to be running into an unbreakable wall. I'm trying to connect to my database which is on a different server on the same domain. This is all within a winform app. Also the windows account I am using for running this winform application has read and write permissions to the sql database already (Same domain account). I've set my connection string in my app.config as follows following the advice from connectionstrings.com
<connectionStrings>
<add name="my_db" connectionString="Server=10.xx.xx.xx;Database=my_db;Trusted_Connection=True;" providerName="System.Data.SqlClient" />
</connectionStrings>
I have the following method in Helper.cs where I am setting the Connection string from the config file.
public static string CnnVal(string name)
{
return ConfigurationManager.ConnectionStrings[name].ConnectionString;
}
Lastly, I have the following method in its own class, DbConnect.cs, and this method is called when I click a button on a form.
public void TestConnection()
{
try
{
using (var connection = new SqlConnection(Helper.CnnVal("my_db")))
{
var query = "Select 1";
System.Diagnostics.Debug.WriteLine($"Executing {query}");
var command = new SqlCommand(query, connection);
System.Diagnostics.Debug.WriteLine($"successful connection");
command.ExecuteScalar();
System.Diagnostics.Debug.WriteLine($"Successful query");
}
}
catch (Exception ex)
{
System.Diagnostics.Debug.WriteLine($"failure {ex.Message}");
}
}
I set breakpoints on "var command" and "command.ExecuteScalar();" lines and when looking at my Watch tab in visual studio, I can see that my connection is not opened and this leads to an InvalidOperationException from SqlCommand. I'm not sure why this is happening. I used sql server migration assistant this morning to migrate the server from mysql over to sql and my info all worked then (windows auth, ip, database name). What could the outlier be here? Do I have to put the port number in my connection string somewhere? I'm using the default 1433 port. Any help would be appreciated. Thanks

Entity Framework 6 connection string questions

I have a C# ASP.NET MVC code first project that works as intended to connect to my database. It has the connection string set in the web.config file and all seems to work great.
<connectionStrings>
<add name="HorstMFGContext" connectionString="Data Source=(LocalDb)\MSSQLLocalDB;AttachDbFilename=|DataDirectory|HorstMFG.mdf;Initial Catalog=aspnet-HorstMFG;Integrated Security=True" providerName="System.Data.SqlClient" />
</connectionStrings>
Now I need to connect to the same database from a different application that needs to be a WinForms based class library. I don't have access to the source code of the program that uses my dll because my application is just a plug-in for Autodesk Vault.
There are numerous examples such as this one that show how to set the connection string in the application that calls the dll, but that obviously won't work in my case.
This link here seems to very close to what I need, but I haven't been able to get it to work. Here is my version of the 'Create' function.
public static HorstMFGEntities Create(string nameOrConnectionString)
{
var entityBuilder = new EntityConnectionStringBuilder();
// use your ADO.NET connection string
entityBuilder.ProviderConnectionString = nameOrConnectionString;
// Set the Metadata location.
entityBuilder.Metadata = #"res://*/HorstMFG.ssdl|res://*/HorstMFG.msl";
return new HorstMFGEntities(entityBuilder.ConnectionString);
}
Here is the line that calls the function:
using (var db = HorstMFGEntities.Create(#"data source=(localdb)\MSSQLLocalDB;attachdbfilename=C:\Users\lorne\source\repos\HorstMFG\HorstMFG\App_Data\HorstMFG.mdf;integrated security=True;MultipleActiveResultSets=True;App=EntityFramework"))
{
foreach (string l in lineList3)
{
....
....
Here is the actual line that throws the exception.
// calculate material
Material mat = db.Materials.Where(m => m.StructuralCode == l.Split('\t')[6]).FirstOrDefault();
The exception message "Error: Keyword not supported: 'metadata'.
Any help to point me in the right direction is appreciated. Thanks.
I updated my code as per the first comment, and also added the 'provider' that I had missed as well.
public static HorstMFGEntities Create(string nameOrConnectionString)
{
var entityBuilder = new EntityConnectionStringBuilder();
// use your ADO.NET connection string
entityBuilder.ProviderConnectionString = nameOrConnectionString;
entityBuilder.Provider = "System.Data.SqlClient";
// Set the Metadata location.
entityBuilder.Metadata = #"res://*/HorstMFG.csdl|res://*/HorstMFG.ssdl|res://*/HorstMFG.msl";
return new HorstMFGEntities(entityBuilder.ConnectionString);
}
Now I get the error "Error: Unable to load the specified resource."
I now followed the instructions in the link you provided. I think I must be getting close, but I'm a little foggy on the metadata format yet. There seems to be a portion commented out in the example. I replaced it with this:
entityBuilder.Metadata = "res://*/HorstMFG.csdl|res://*/HorstMFG.ssdl|res://*/HorstMFG.msl";
Now I get the error: "Unable to load the specified metadata resource"
I confirmed that the files I am referencing do exist, they are in the ...\obj\Debug\edmxResourcesToEmbed\ folder in my project. I also changed the 'build action' for the 'HorstMFG.edmx' object from 'None' to 'Embedded Resource'. That didn't help anything.

Entity Framework: The context is being used in Code First mode with code that was generated from an EDMX file

I am developing an WPF application with EF 6 database first approach, I am have 1 project in my solutions, if i run my project this error always appear.
The context is being used in Code First mode with code that was generated from an EDMX file for either Database First or Model First development. This will not work correctly. To fix this problem do not remove the line of code that throws this exception. If you wish to use Database First or Model First, then make sure that the Entity Framework connection string is included in the app.config or web.config of the start-up project. If you are creating your own DbConnection, then make sure that it is an EntityConnection and not some other type of DbConnection, and that you pass it to one of the base DbContext constructors that take a DbConnection. To learn more about Code First, Database First, and Model First see the Entity Framework documentation here: http://go.microsoft.com/fwlink/?LinkId=394715
My mistake was using standard connection string in constructor
(Server = test\test; Database = DB; User Id = test_user;Password = test),
but Entity Framework needs different format
(metadata=res://*/DBModel.csdl|res://*/DBModel.ssdl|res://*/DBModel.msl;provider=System.Data.SqlClient;provider connection string="data source=test\test;initial catalog=DB;integrated security=True;MultipleActiveResultSets=True;App=EntityFramework""" providerName = ""System.Data.EntityClient)
Edit: Changed code to be formatted as code so it's easier to read.
EF makes assumptions based on the presence or absence of a metadata section in the connection string. If you receive this error you can add the metadata section to the connection string in your config file.
E.g. if your connection string looks like this:
<add name="MyModel" connectionString="data source=SERVER\INSTANCE;initial catalog=MyModel;integrated security=True;MultipleActiveResultSets=True;App=EntityFramework" providerName="System.Data.SqlClient" />
Prepend metadata=res://*/MyModel.csdl|res://*/MyModel.ssdl|res://*/MyModel.msl; so that it looks like this:
<add name="MyModel" connectionString="metadata=res://*/MyModel.csdl|res://*/MyModel.ssdl|res://*/MyModel.msl;data source=SERVER\INSTANCE;initial catalog=MyModel;integrated security=True;MultipleActiveResultSets=True;App=EntityFramework" providerName="System.Data.SqlClient" />
One thing you can do is... (if is Database first)
Open the .edmx[Diagram] -> right click -> "Update Model from database"
And see if the will appear the "Add", "Refresh" and "Delete" tabs.
If doesn't... probably your connection is broken and the dialog for VS creates a new connection string will appear instead. =)
You shouldnt use generated connection string, now you have all metadata files included in your solution. Instead try use in connection string section of app.config:
"data source=localhost\sqlexpress; initial catalog=sample; integrated security=True;MultipleActiveResultSets=True;"
None of the above solutions worked for me. But I did find the SqlConnectionBuilder class here which did work: https://learn.microsoft.com/en-us/dotnet/api/system.data.entityclient.entityconnectionstringbuilder?view=netframework-4.8
Its the same as specifying the string as some of the other suggestions here but it builds the string for you.
// Specify the provider name, server and database.
string providerName = "System.Data.SqlClient";
string serverName = ".";
string databaseName = "AdventureWorks";
// Initialize the connection string builder for the
// underlying provider.
SqlConnectionStringBuilder sqlBuilder =
new SqlConnectionStringBuilder();
// Set the properties for the data source.
sqlBuilder.DataSource = serverName;
sqlBuilder.InitialCatalog = databaseName;
sqlBuilder.IntegratedSecurity = true;
// Build the SqlConnection connection string.
string providerString = sqlBuilder.ToString();
// Initialize the EntityConnectionStringBuilder.
EntityConnectionStringBuilder entityBuilder =
new EntityConnectionStringBuilder();
//Set the provider name.
entityBuilder.Provider = providerName;
// Set the provider-specific connection string.
entityBuilder.ProviderConnectionString = providerString;
// Set the Metadata location.
entityBuilder.Metadata = #"res://*/AdventureWorksModel.csdl|
res://*/AdventureWorksModel.ssdl|
res://*/AdventureWorksModel.msl";
Console.WriteLine(entityBuilder.ToString());
using (EntityConnection conn =
new EntityConnection(entityBuilder.ToString()))
{
conn.Open();
Console.WriteLine("Just testing the connection.");
conn.Close();
}
I also faced this exact same message, but workig with a web MVC project. This message is fired when I try to auto generate the Controller from the imported model. It seems that it is not working because "that was generated from an EDMX file".
The good news is that it works if I generate the model based in the "Code First" instead of "EF Designer". The bad news is that I can't use the EF Designer if I want that the automatically controller generation works. Does not matter which from those two ways you generates your model. Once the model is generated, you use it in the same way.
Tries to remove all your emdx objects from your project and recreate the model based in the Code First instead of EF Designer. Worked for me!
Very much late but still helpful. I got stuck in a similar problem. Posted a question about on SO and was able to find a solution. You can refer to Connection String errors in C# Web Api.
My situation was I had two connection strings in web.config (you'll get to know why when go to the link). Commenting one string was raising the error you got while commenting the other one was raising error as below:
An error occurred when trying to create a controller of type 'AccountController'. Make sure that the controller has a parameterless public constructor.
what i did was: I named my first connection string as DefaultConnection and in ApplicationDbContext class constructor I gave this DefaultConnection. Now my AccountController uses this connection string and all other controllers use second connection string.
This solved my problem.
I have two projects:
One is for the generated EDMX file and all related models.
The other one is the ASP.NET MVC Web.
I encountered this issue since the connection string that I am using on the ASP.NET MVC Web project is the normal string that I use using ADO.NET connection. So what I did is the following:
Open the app.config on your EDMX project files.
Copy its connection string.
Paste it on the WEB project since this will be used when you start
the application.

Unable to read local SQL Server file when running as exe. Works in IDE

This is the first time that I am trying to use a SQL Server File type database. It works when I run in the IDE but when I double click on the exe or right mouse click "Run Elevated," I get an error when trying to connect.
The message box displays the same connection string when running in both modes.
What might be the issue? Some sort of permissions issue?
MessageBox.Show(ApplicationParameter.LocalDatabaseConnectionString);
databaseConnection = new SqlConnection(ApplicationParameter.LocalDatabaseConnectionString);
databaseConnection.Open();
I get the following SqlException:
A network-related or instance-specific error occurred while establishing a connection to SQL Server. The server was not found or was not accessible. Verify that the instance name is correct and that SQL Server is configured to allow remote connections. (provider: SQL Network Interfaces, error: 50 - Local Database Runtime error occurred. Error occurred during LocalDB instance startup: SQL Server process failed to start.
Here is the connectionstring from the app.config file:
<connectionStrings>
<add name="LocalDatabase" connectionString="Data Source=(localdb)\v11.0;Initial Catalog=C:\MYCODE\MyCompany.DISKMONITOR\MyCompany.DISKMONITOR\DATA\DATABASE.MDF;Integrated Security=True;Connect Timeout=15;Encrypt=False;TrustServerCertificate=False"/>
</connectionStrings>
And my class for reading the app config:
class ApplicationParameter
{
public static string LocalDatabaseConnectionString
{
get
{
return ConfigurationManager.ConnectionStrings["LocalDatabase"].ConnectionString;
}
}
}
Update:
I ran as Administrator and got the same result.
Connections.Classified contains information specific to the location of the db, what instance to use and username/password information. Will not be posted...
Here is my SQLConnections.cs class that I use in all of my apps (well mine is oracle I've just updated it to work with SQL):
private String connectionString = "Server=" + SERVER + "\\" + INSTANCE + ";Database=" + DATABASE + ";User Id="+ USER + ";Password=" + PASSWORD + ";"
protected SQLConnection getConnection()
{
return new SQLConnection(connectionString);
}
In use in a repo class that extends the Connections.SQLConnections:
SQLConnection connection = getConnection();
A lot less clutter and easier for someone else, reading your code, to understand.

Can't connect to database server

I'm encountering a problem with my database connection.
I started with a new blank solution, then I added a WCF library project, and last but not least a WCF website (service).
In the website i added a reference to the library where I have the interface (data contract), the class that implements the interface and the dataclasses.
what I'm trying to do is to connect to a database on a server and try to retrieve some data from there.
So the connection string looks like:
<add name="myConnectionString" connectionString="Data Source=MyServer; Initial Catalog=MyDatabase; User Id=me; Password=me123;" providerName="System.Data.SqlClient" />
and this is how I'm trying to connect with the database:
public List<string> GetEngagements(string id)
{
string sql = "SELECT myColumn FROM myTable WHERE Id = '" + id + "'";
string connString = string.Empty;
SqlConnection connDB;
connString = ConfigurationManager.ConnectionStrings["myConnectionString"].ConnectionString;
connDB = new SqlConnection(connString);
SqlCommand command = new SqlCommand(sql, connDB);
connDB.Open();
SqlDataReader rdr = command.ExecuteReader();
List<string> numbers = new List<string>();
while (rdr.Read())
{
numbers.Add(rdr[0].ToString());
}
rdr.Close();
return numbers;
}
I'm getting an exception on connDB.Open().
Then exception message says:
Failed to generate a user instance of SQL Server due to a failure in starting the process for the user instance. The connection will be closed.
I've been getting this message for 2 days now, I've googled a lot and deleted the C:\Documents and Settings\username\Local Settings\Application Data\Microsoft\Microsoft SQL Server Data\SQLEXPRESS directory but it didn't work for me..
Any solution???? help please
The error message:
Failed to generate a user instance of SQL Server due to a failure in starting the process for the user instance.
Suggests that you're using user instancing, and therefore your connection string will point to an .mdf file on disk rather than the name of a database.
So I'll assume that you want to connect to a file instance rather than a server instance.
I'll also assume that you're using SqlExpress rather than the full fat version.
In which case your connection string is wrong. It should look more like this:
"Data Source=.\SQLEXPRESS;
AttachDbFilename=fileOnDisk.mdf;
Integrated Security=True;
User Instance=True;"
User instancing means that this server instance and the DB inside will only be visible to the application opening the connection string.
You don't have to use user instancing - you can set User Instance=False or just leave it out. Then once the application has made the connection you can connect other tools to the server instance and connect to the DB yourself.

Categories

Resources