How to create external connection with local database in test project? - c#

I have in Visual Studio two projects: My normal project and my test-project. I have chosen to use SpecFlow for testing and therefore my tests are UI based. So a database connection is not needed for the UI validation.
In some cases I have to set some preconditions to the system, like filling some sample data in the project. I've tried to connect my project-database to my test-project, but it just won't work. I tried to add connectionstrings to my test-project app.config like this:
<connectionStrings>
<add name="MyConnectionString"
connectionString="Data Source=C:\Users\Martijn\Documents\VS11\Projects\Gastouderuren.nl\testprojectl\App_Data\example.sdf"
providerName="Microsoft.SqlServerCe.Client.4.0" />
</connectionStrings>
When I use this connection string in the code as follows:
MyContext context = new MyContext(ConfigurationManager.ConnectionStrings["MyConnectionString"].ConnectionString);
context.Product.Count();
When I run my test, the following error occurs:
The provider did not return a ProviderManifestToken string. -> This operation requires a connection to the 'master' database. Unable to create a connection to the 'master' database because the original database connection has been opened and credentials have been removed from the connection string. Supply an unopened connection. -> 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 searched already for a solution, but couldn't find anything. How can I solve this problem?
Thanks!

You cant connect to a external localdb (file based) like the same way you used to connect to normal SQL database
(connect string)
its because of localdb limits (No more than 1 apps can connect at once)
but i have a soulution : (How to use 2+ applications with 1 localdb)
You have to create a TCP server listener (In pc where LOCALDB is) and
X clients where your other pc(s) are
client pc(s) connect to server pc
So everytime you want to execute a sql command you send command from
CLIENT to SERVER and Server executes it ! (Can send back response to)
you can set some pre definded commands too(i did same thing)
SERVER :
if(CLIENT DATA . equals("ReadProducts"){
sql.execute("SELECT * FROM Products");
//convert...
SendBack(result);
}
CLIENT 1 >SEND> SERVER : "ReadProducts" (Predefinded command)
SERVER >SEND> CLIENT 1 : "Apple,Melon,Orange"
CLIENT 1 :
data = SERVER RESPONSE;
string[] sp=data.split(',');
//add a for loop which add all products to your listview
CLIENT 2 >SEND> SERVER : "INSERT INTO Products(name) VALUES(#name)"
SERVER :
if(CLIENT DATA . contains("INSERT"){
sql.execute(CLIENT DATA);
}
Using algorithm abow you can handle many connections to a single LocalDb file
from another computers but you have to deal with IP problem
get a Static Ip address for server app if you developing something big

Related

I want to create a shared database c# windows form application?

This application that i am trying to create, whose "instances/copies" will be installed on multiple PCs of the client and are able to access the same database from another PC of the same client that has SQL server running all the time through the same network(i.e: they have the same router and static IP of server etc).
I had two ways to do this:
To make applications use the same database through synchronization.
To have multiple localdbs that then share the changes a database server.
By following 1st way,
I tried setting up the Connection String like:
SqlConnection con = new SqlConnection("Data Source =[serverPcIP,Port];Integrated Security=True;Connect Timeout=30");
SqlConnection con = new SqlConnection("SERVER=[serverPcIP]; Port=[portno];Integrated Security=True;Connect Timeout=30");
In Server - Security Settings:
I have allowed "SQL Server and Windows Authentication mode"
In Sql Server Configuration Manager > SQL Server Network Configuration > Protocols for SQLEXPRESS => TCP/IP = Enabled; under IP Addresses -> IP1 -> TCP Port = 1433 (port that i used in my connection-string)
In advanced Firewall Setting:
Have enabled the Incoming & Outgoing rules for port 1433.
The exception that i get:
Additional information: 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: TCP Provider, error: 0 - The wait operation timed out.)
Can someone please tell me what configurations (either in connection-String or in SQL server itself) am i missing?
Your connection string lacks the instance name e.g. data source=<hostname or ip>\SQLEXPRESS. If your database listens on the default port 1433 you don't need to pass that with the connection string
If you setup a SQL server, you can choose between the default SQL Server instance or the named instance. For SQL Express the default is to install a named instance with the name SQLEXPRESS. If you don't use the default instance and install a named instance instead, you have to pass it with the connection string.
The default SQL Server instance ist just a named instance with the well known name MSSQLSERVER. So if you installed the database instance as the default instance you can connect with <host>[,port] or <host>\MSSQLSERVER[,port]
based on your screenshot, under IP1, the ip address is active but not enabled.
also, ip address that starts with 169.x.x.x normally would mean you have set up this network card to use DHCP, but the network card failed to have ip address from the DHCP server.
do you mind try to use static ip address?
Consider following steps:
Since you mention the port number using configuration manager, the service required restart. please restart the service if not done so.
Seems you are able to connect via SSMS, once service restarted verify SQL Error log via SSMS -> Managemnt -> SQL Server Logs, you must find a message as follows:
Server is listening on [ 'any' <ipv4> 1433].
Further details, follow these steps. Also, this..

UWP the application cannot communicate with the remote instance SQL Server

I am currently implementing a UWP program for an existing database. I took this article as a basis.
https://learn.microsoft.com/en-us/windows/uwp/data-access/sql-server-databases
When running, I get an exception:
System.Data.SqlClient.SqlException" в System.Data.SqlClient.dll
Exception:
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: TCP Provider, error: 25 - Connection string is not valid)
This seemed strange to me, since a WPF application with the same connection string works fine. Next, I decided to install a database instance on my computer and export some of the data to a local database. To my surprise, after replacing the connection string from:
Data Source=sqlserver\sqlexpress
to
Data Source=.\sqlexpress
UWP program read this from the database on my computer.
I also read this article to make sure that the remote database is configured correctly. https://www.lansweeper.com/knowledgebase/a-network-related-or-instance-specific-error-occurred/
As I said, WPF programs work with this database perfectly. What are the ways to check why the UWP doesn't want to communicate with the database?
to make it clear whether the remote server is available in principle, I apply the output of the TNC command:
tnc sqlserver -p 1433 -I detailed
ComputerName : sqlserver
RemoteAddress : 192.168.10.11
RemotePort : 1433
NameResolutionResults : 192.168.10.11
MatchingIPsecRules :
NetworkIsolationContext : Private Network
InterfaceAlias : Ethernet
SourceAddress : 192.168.10.20
NetRoute (NextHop) : 0.0.0.0
TcpTestSucceeded : True
Connection string look like:
private string connectionString = #"Data Source=sqlserver\sqlexpress;Initial Catalog=TestCatalog;User ID=*;Password=*";
The same connection string is used in VS. VS shows the contents of the table without problems. I can also delete or add new lines in the VS editor.
I'm talking about a remote database. In VS server Explorer I have a Data Connection where I am connected to a remote database. I can safely edit remote database data in VS (add, delete and update). I see the connection string and originally used it as the connection string in UWP app.
You have already taken a look at this microsoft link here. Long story short, have you followed the proposal below?
Trouble connecting to your database?
In most cases, some aspect of the SQL Server configuration needs to be changed. If you're able to connect to your database from another type of desktop application such as a Windows Forms or WPF application, ensure that you've enabled TCP/IP for SQL Server. You can do that in the Computer Management console.
Check to see if you have followed the rest of the solution properly. You might need to enable the tcp port from the window firewall.
Go to firewall -> Inbound Rules -> Add TCP:1433 in the rule.
Also since the error is about the connection string, try to use only the server name/ ip/ or hostname, without the server instance.
You can also add the port number and see if this works for you. When you add it, sql server ignores the instance name (as different instances require different ports to work, so it can work as a unique identifier).
Edit: How to create a valid connection string:
Look at this answer here: How to get the connection String from a database

SQL Server problems to connect

I am developing a program with C# and WPF. I want the data to be stored in an SQL Server database. I made a connection string with the instance name in my PC, and that worked. But when I want to connect through the Internet with an IP address, I get some errors:
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. (TCP Provider,
error 0 - No connection could be made because the target machine
actively refused it.)
I enabled TCP/IP, allowed remote connection in SQL Configuration Manager, opened a port of 1433 in my firewall, but still I am getting this error.
My connection string is this:
String connString = #"Network Library=dbmssocn;
Network Address=127.0.0.1,1433;
Integrated security=SSPI;
Initial Catalog=db";
SqlConnection conn = new SqlConnection(connString);
conn.Open( );
Where is my mistake?
There is very slight error in your connection string and honestly I can't blame you for that as it is very weird way in which SQL Sever is behaving. I'm not sure if this error lies in connection provider side or SQL Server instance side. Name of Network Library that your application is using to connect to the SQL Server using dbmssocn(Win32 Winsock TCP/IP) should always be mentioned in capital letters. Though I didn't see any relevant MSDN documentation from MS to support my statement but it actually worked when I did so. Here is the connection string that you should be using to fix the error.
String connString = #"Network Library=DBMSSOCN;
Network Address=127.0.0.1,1433;
Integrated security=SSPI;
Initial Catalog=db";
Seriously, I got freaked out in reproducing your issue as instead of copying the connection string from your question I copied it from some other blog :). But all is well that ends well. I've also assumed that a database named "db" actually exists on the default (NOT named instance) instance of the sql server you are connecting to when typing this answer. If changing the casing of network library name in connection string doesn't help then double check that database "db" must exist for a sql server default instance to which you are connecting to. In case you are using a named instance of sql server in your installation then that instance name should also come in the connection string.
Configure your SQL Server to allow TCP/IP connections. Go to SQL Server Configuration Manager -> network then protocols for your SQL Server named instance -> TCP/IP.
See this image!

Connection string is not valid or Error Locating Server/Instance

I reinstaled my PC and now I have problems with my SQL connection string or with SQL Server 2012 Enterprise
Error I get:
"... (provider: SQL Network Interfaces, error: 25 - Connection string is not valid)" or
"... (provider: SQL Network Interfaces, error: 26 - Error Locating Server/Instance Specified)"
In SQL Server Management Studio server instance looks like this:
TOM-PC (SQL Server 11.0.3128 - Tom-PC\Tom)
And My SQL connection string in ASP.NET XML config. file:
<add name="ApplicationServices" connectionString="Data Source=.\TOM-PC;Database=D:\Programming\InvoiceManager\invocemanagerSQL.mdf;" providerName="System.Data.SqlClient" />
Tried everything, in firewall added port 1434 or 1433 tested both, not working, "SQL Server Browser" Service is running, TCP/IP Enabled, Allow remote connections to this server, even tried 4 different connection strings, nothing worked.
Before it worked like a charm, not fully but worked. Why not fully? Because I couldn't work on my local machine with both studios "VS2010" and "SQL Management studio" at the same time, if I needed change something in database manually, I needed to stop or restart SQL Server process and service, then I get in database, and read tables. Now, nothing is working!
What I do or did wrong? Where seems to be the problem? Why always are problems with SQL servers and it's connectionstrings?
What you are seeing in Management Studio is as follows:
Instance Name (SQL Server version - Domain\LoggedInUser)
You are logged in using integrated authentication (i.e. your windows logon account) but not specifying it in the connection string. This will try to use the currently logged on user for the ASP.Net application, which will almost certainly not be running as your windows account. It will either be one of the local or network service accounts or a built-in ASP.Net user.
You're also using the wrong variable name to attach the database file, if this is actually what you want rather than connecting to an actual database on the server.
What I suggest you do is enable SQL Server authentication on your instance, create a new user and give it permissions to the database as required.
You would then log in using the following format:
Server=myServerAddress; Database=myDataBase; User Id=myUsername; Password=myPassword;
Where myServerAddress would be localhost or TOM-PC; Database would be the name of the database as it appears in Management Studio; User Id would be the username for the user you just created and Password would be the password you set for them during creation.
If you do actually want to attach a database file then your connection string changes to use this format:
Server=myServerAddress; AttachDbFilename=C:\Path\To\Database\File.mdf; Database=myDataBase; Trusted_Connection=Yes;
Typically, you can get most connection string variants that you will need from: http://www.connectionstrings.com/sql-server/

Connection string to SQL by EntityFramework and MVC

I write web page in MVC, which use Entity Framework as ORM mapper. I put my connection string to web.config file. Here is it:
<add name="JP_CMS" connectionString="Data Source=.;Initial Catalog=JP_CMS;
User Id=CmsWebUser;Password=abcd1234abcd1234;"
providerName="System.Data.SqlClient"/>
I try to get data by this C# code
public DataBaseContext()
: base("JP_CMS")
{
Database.SetInitializer(new DropCreateDatabaseIfModelChanges<DataBaseContext>());
}
//------------------------------
var db = new DataBaseContext();
var result = db.Articles.ToList(); //<- here is thrown exception
//------------------------------
My local SQL server is running, this table is exists, but I get excepion like in this:
I think it is the most important expection: "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: Named Pipes Provider, error: 40 - Could not open a connection to SQL Server)"
Could you help my by give some idea what I make wrong?
"The system cannot find the file specified" error. Check carefully your connection string.
hi Error indicates EF tried to connect to the server but failed.
Could you Checkk,
1) SQL Server should be up and running.
Go to All Programs >> Microsoft SQL Server 2008 >> Configuration Tools >> SQL Server Configuration Manager >> SQL Server Services, and check if SQL Server service status is “Running”.
In addition, ensure that your remote server is in the same network. Run “sqlcmd -L” in your command prompt to ascertain if your server is included in your network list.
2) Enable TCP/IP in SQL Server Configuration
For more info you can go here
Instead of DataSource =. try DataSource = .\sqlInstanceName. Also DataSource=(local) might work.

Categories

Resources