WCF Service Problems - c#

I'm having trouble setting up my WCF Service to an IIS server. The current setup I have is a WCF service written in C# that accesses an external database (located on a different server, different location than our IIS server) and an ASP.NET web site that consumes the service on our server, and uses it's methods to query, then display some data.
Before I uploaded the Service and website to our server, I tested it using the default setup done by Visual Studio. This test led to promising results, because when I let visual studio host the service (and whatever else it does in order to setup the environment for testing) and consume it with the website, everything went smoothly, and all of my queries went through flawlessly.
I can upload the service fine, consume it fine with the website, but I have problems when my service makes queries to the external database. I get an "underlying provider failed on open" error when an actual query is made. I've tried a few different things and I couldn't find an answer. For legal reasons , I'm not allowed to upload the code, but I think this problem is due to incorrect setup on the server.

Assuming that you're using Entity Framework, that problem almost always indicates that there is an issue establishing a connection to your database. Check your connection string and make sure that the server and instance names are correct, and that the user your service is running under has access to the database. If you're hosting in IIS, this would usually be a service account (e.g. NETWORK SERVICE) or local system account.

The issue ended up being the connection string in the end. On my local machine, the name of the server was resolved with the Hosts file, but the server had nowhere to resolve the name of the server mentioned in the connection string. This was causing the issue. This has been resolved by updating the server hosts file.

I've gotten this error on new installations of SQL Server, and I fixed it by enabling Named Pipes in SQL Server Configuration Manager. Could be the same issue you're having.

Related

Login failed for user 'sa' in ASP.NET with SQL Server 2019

I am trying to connect my .NET project to SQL Server developer edition 2019 (named instance), but it always throw the error:
Login failed for user 'sa'.
It however connects perfectly through SSMS without any issues.
I tried all possible things as suggested over internet but could not make my website run, is it actually the named instance which causes this issue, or it's issue at large.
I am able to connect my project if i connect to my database located on the remote server. but the one on my local machine just does not works.
Here's how my connection string looks like
server=[machine]\\[instance]; Integrated Security=SSPI; initial catalog=[database];Connection Timeout=1000
I also tried the same with SQL Server authentication
server=[machine]\\[instance]; uid=sa; pwd=[password]; initial catalog=[database];Connection Timeout=1000
None of the above worked out.
Ok, SSMS can connect using direct.
However, from asp.net, you in most cases have to turn on networking.
For reasons of secuirty, by default, your local instance of SQL server express has this feature turned off by default.
so, you need to do two things - and this was NOT required with older versions of sql server, but for recent versions - starting around 2012, you need to:
Turn on the browser service. This "translates" the sql "instance" to your IP address. (on startup, sql server assigns a IP address to that instance, but it will NOT be the same IP as your computer). But, the NAT translator thus has to be running.
That IP translator? It called the SQL browser service, and as noted, you need to have that running now, where as in the past you did not. That is this setting - launch the sql configuration, and you see this:
So, make sure the SQL Server Browser service is running - it is NOW required and as noted was not in the past.
Next up:
You need to turn on networking for SQL server. SSMS (sql studio) is able to connect using memory pipes - applications using the sql server provider in .net cannot!!!
So, once you ensured and checked the above browser service is running?
Then click on SQL server Networking Configuration, and turn on network connections (again, they are not turned on by default). That is this:
Now, after doing above, you probably should re-start sql server, and then the browser service. (just right click on sql server again, and choose this:
So, while SQL studio can connect using shared memory, .net and asp.net sites can't.
So, start the sql browser service - it is required to "resolve" the instance of sql server. in most cases, that will be SQLEXPRESS.
And consider using the built in connection builder in Visual Studio - it will not only build the connection string for you, but will also test the connection - and this can be done long before you even run any code.

SQL Server connection errors when moving .net app to new server

I have a number of .NET web apps on a Server 2008 machine that I'm trying to migrate to a Server 2019 machine, and some of them are giving me problems connecting to SQL Server 2016 instance on another server after moving them.
The error I get is
System.Data.SqlClient.SqlException (0x80131904): 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: 25 - Connection string is not valid) ---> System.ComponentModel.Win32Exception (87): The parameter is incorrect
This one is a .NET Core 2.2 web app. (.net core 2.2 server package installed on server) the connection string is like
"Server=mysqlserver\myinstance,3050;Database=Idea;Trusted_Connection=True;"
and is using Entity Framework/DbContext to connect.
The app in IIS has an app pool created for this app, set up the same as it was running on the old server: No Managed Code, Identity set as a domain user "domain\user".
Ping from new app server to database server works. Running SSMS as the domain user on the new server connects to the database fine and can view data through management studio.
So I don't know if there is something different in Server 2019 about the way it's trying to connect to SQL Server or what? I've been banging my head on this for a few days now. .NET 4.0 apps are also having the same errors trying to connect to other databases on this same instance.
The weird thing, is some other apps work fine, connecting to a different SQL 2016 instance on a different server, but they are also different .net versions, like older .NET 4.0 web apps, but they are running as app pools with different domain accounts for each app fine.
It seems all .NET Core or .net 4.0 web apps on this server are having trouble connecting to this one database instance from this server, but back on the old web app server they work fine.
Any ideas of anything else I can check?
Edit: I found the error is actually when connecting to a new SQL Server, even from the old app server it still gets the same error. I have 2 connections in this application, so I thought it was the first one, but it was actually the 2nd one. So it's something more to do with the new SQL server instance. Again, connections from SSMS work fine with this user, but not from the web app.
Edit2: After more testing, it's definitely something to do if there is Server 2019 in the mix. From 2019 app server to 2019 db server fails. From 2008 app server to 2019 db server fails. From 2019 app server to 2016 db server fails. From 2008 app server to 2016 db server succeeds.
Edit 3: I feel like I'm going crazy here. One of the apps, I tried to change ASPNETCORE_ENVIRONMENT to Development so that I could see more detailed errors on screen, so I set the appsettings.Development.json to the exact same as the appsettings.Production.json and then the connection works! Switching it back to production it gets the error again. The entire file is the exact same text. How does that even make any sense? I even tried explicitly setting the environment variable to Production instead of letting it just pick it up as the default.
Edit 4: I've solved half of the problems I've been having now.
For whatever reason, the connection string that I copied from one of the spreadsheets in the beginning had crazy hidden characters in it so that’s why it was saying the sql server didn’t exist.
I can’t see them at all in any editor and only found it by VS Code compare saying the line was different but not seeing any difference I broke it into chunks and found the spot. We found when we opened it in WordPad, that was the only place that would show it, see below.
I'm fairly sure the solution is to remove the instance name from the connection string...
"Server=mysqlserver,3050;Database=Idea;Trusted_Connection=True;"
Refer to these questions question1 & question2
"It's not necessary to specify an instance name when specifying the port."
Problem was due to hidden characters in the connection string. See my Edit 4. Other problems leftover were unrelated.
Try to create an user in the database using the same AppPool name that you used to configure your application in IIS.
Here's a "how to" create the user in the database:
https://engram404.net/grant-sql-permissions-to-iis-apppool-user/
It worked for me.
Otherwise here's an "why" it happends:
You're telling in your connectionString that it will be using an trusted connection "Trusted_Connection=True;"
If you do not want to create the user as described earlier, you should remove the Trusted_Connection=True; and use your connection string like this:
Server=mysqlserver\myinstance,3050;Database=Idea;User Id=SetYourUser;Password=SetYourPassword"
I know you happened to solve this, but still..
You can't connect to a MySQL database with System.Data.SqlClient - It is configured for an SQL database, not MySQL
You can find the MySQL Data Connector Here. (You can otherwise download it from Nuget)
If you downloaded it from Nuget, then skip this step.
After downloading the package, you can add it as a reference in your project, by right-clicking the References item in the Solution Explorer, then click Add Reference... - The Reference Manager window will then open. Click the Browse item in the left-menu, then click the Browse button, and navigate to the directory of which the package was saved.
Now, after successfully downloading and installing the package, add this line to your code:
using MySql.Data.MySqlClient;
The correct syntax for connecting to your MySQL Database, using MySql.Data.MySqlClient;, would be:
string connectionInfo = #"Server=localhost;Database=your_database;User ID=root;Password=123456";
So, overall, your code would look like:
using(MySqlConnection con = new MySqlConnection(connectionInfo))
{
con.Open();
MessageBox.Show("Successful Connection!");
}
(Code / part of answer is derived from here.)
I hope I could help anyone else with this problem :)

AdomdConnection throwing "Check that 'SQL Browser' service is running" error

I have the following code that I am trying to get working:-
using (AdomdConnection conn = new AdomdConnection(_connString))
{
conn.Open();
Console.WriteLine(conn.ConnectionString);
Console.WriteLine(conn.Cubes.Count);
}
The following error is thrown with and without the conn.Open() line:-
A connection cannot be made to redirector. Ensure that 'SQL Browser' service is running.
I don't have a SQL Browser service available on the client machine I'm using. But what's vexing me is this exact same connection string works from Excel and pulls back a set of OLAP Cube measures which I can pivot as required.
The connection string is as follows:-
Provider=MSOLAP.4;Integrated Security=SSPI;Persist Security Info=True;Initial Catalog=RaptorMarketRiskSummary;Data Source=ssasp-raptor\plnqic01_as;MDX Compatibility=1;Safety Options=2;MDX Missing Member Mode=Error
Does anyone have any ideas?
Many thanks.
Did you try this?
This error seems to related only to named instances. The reason is SQL client is not able to resolve instance because SQL client has no access SQL Browser Service. SQL Browser Service resolves instance name
1.Ensure SQL browser service is running
2.Ensure the port on which SQL browser service runs, is not blocked from PC (default port 2382)
Alternatively, you can bypass SQL Browser Service, by mentioning "Server:Port" instead of "Server\instance name", in the client connection properties
This is an old answer from :
a connection cannot be made to redirector. Ensure that 'sql browser' service is running
Look a the Alternatively point :)
It turns out that this error
A connection cannot be made to redirector. Ensure that 'SQL Browser' service is running
can be caused by problems which have nothing to do with whether the SQL Browser is running or not. (This is intuitively the case given that I could connect from Excel.)
At my workplace each employee has a personal space on a network drive. Because I intended my app to be a quick proof-of-concept to demonstrate .Net's ability to connect to OLAP cubes, I used a folder on my personal network drive as a scratch area. I then tried connecting to another database (directly, not through a cube) and discovered I had a permission issue. I compiled the binary (from Visual Studio) and placed it on another network drive so that a colleague could test from his machine. In checking the binary would throw an error, I ran it from the second network drive and it connected fine and brought back some data.
Changing the app back to connect to my OLAP cube and moving the Visual Studio solution to my local C: drive has resulted in being able to connect to the cube fine and pull back the data I want!
So: the 'Check SQL Browser service is running' error is a catch-all piece of advice which covers a multitude of sins underneath. Permissions can depend on where the app is running from (i.e. which network drive, not just whether the drive is network or local).
Hope this helps :)

Entity framework unable to connect to network database

I have a SQL Server 2008 database on my desktop that I'd like to access on a project developped from my laptop.
I tested the connection to the database from the laptop using the Server Explorer window (Data Connection > Add connection) and everything runs fine. The database is found, and I can access my tables and see the data insde.
I then added an ADO.NET Entity Data Model (= Entity Framework). The integration worked fine: it created the correct classes, I can edit the model, update it regarding the modification I'll pass from the server, ...
Then when I run my project, it needs to read a few data using the classes created by Entity Framework, but it crashes:
Connection Timeout Expired. The timeout period elapsed while attempting to consume the pre-login handshake acknowledgment. This could be because the pre-login handshake failed or the server was unable to respond back in time. The duration spent while attempting to connect to this server was - [Pre-Login] initialization=63057;handshake=2;
I looked a bit and found some people having issues with the TCP/IP configuration from the Sql Server Configuration Manager, as explained here. Made the modification, restarted all my services, but it didn't fix my issue.
Does anybody have an idea on how I can fix this (note that I tried with no firewall so it seems not to come from this). Also, if helpful, take into consideration the folowing:
the laptop connects through a wifi router (internet box)
the project is hosted on the server hardrives
the project runs well from the server
I found the solution by checking on the option offered in the "Advanced" part of the connection wizard. The Network Library (TCP/IP, Named Pipes, Shared Memory or VIA) can be forced, while it is blank by default (and I guess auto chosen to a wrong option).
I tried all of them, and only the "Named Pipes" worked for me.
The modification can be done manually in the connection string by adding
;network library=dbnmpntw
Make sure before you run the project that you have detached the database. Do this by right clicking on the database, which is located in the AppData folder, and click on Detach

Web App to SQL Server Not Connecting ( Error Locating Server/Instance Specified)

I know this is an often asked question, but I'm still receiving this error and I have tried:
Using localhost, the IP address and the instance name in the
connection string
Changing the SQL Server Configuration Manager so
Named Pipes and TCP are both enabled Ensured the database is set to
allow remote connections
Opened 1433 & 1434 for UDP & TCP in Windows Firewall, in fact I
tried turning off the firewall for a moment to see if it would
connect
Ensured the browser & the MSSQLSERVER service are both up and
running using NETWORK SERVICE
Now for some oddness. The SQL Server instance and the IIS running the website are on the same machine.
If I open a browser and browse to the website I get the error. If I open a browser on my local machine and browse to the website I get the error. If I change the connection string in my development PC to the IP address of the remote server running SQL server and debug the application it connects and runs without error!
I am totally at a loss now as to what could be the error.
This is SQL Server 2008 RC2.
I'm on the verge of giving up - I very much appreciate the efforts you guys have made, I have tried all the suggestions here and I am coming to the conclusion that something must have gone awry in the set-up of the server, the website or the database. Just to reiterate if you remote desktop onto the server and connect to the website using http://gdservers you can login and it all works fine, if you use http://gdservers.<domain>.co.uk the login fails. The error in the event log is a membership credentials failure, not blocked by firewall or anything like that. If there's any other suggestions I'd love to hear them, thanks again.
If your web app intends to use SQL Server Authentication with a SQL login/password then make sure that your connection string explicitly states Integrated Security=False. Otherwise your connection may default to Windows Authentication and not behave as expected.
Edit
Also, be sure that the connection string you're tweaking is the one that is actually being used to make the connection. Sometimes things can get confusing when an application has multiple components that may have their own configuration settings. For example, the problem in the thread here turned out to be:
I was updating the connection string on the web.config but, it's a multitier application, the data access component is in a separate .dll and has its own connection string.
Edit
I'm beginning to wonder if the SQL Membership Provider is using Windows Authentication to connect to the SQL Server even if your data connections aren't. Check out the video here and perhaps review your settings (especially the authentication setting in the provider setup steps).
I don't think anyone spotted it and I only spotted it on Wednesday and then realised I'd made another error. If someone has mentioned it above let me know and I'll change the award and give them the points.
The applicationName was missing from the membership provider. I spotted it on Wednesday and added one in, what I didn't realise I'd done is made a spelling mistake when adding the applicationName in, so when I did this, it didn't fix it, so I thought it wasn't the problem.
Yesterday whilst reviewing the code I noticed I spelt the applicationName 'GSServers' instead of 'GDServers' when I changed it, it all started working.
Not a very satisfactory conclusion and I apologise.
Thank you to everyone who tried to solve this problem and sticking with it.
As I said if someone did mention this in an answer or comment somewhere let me know and they can have the points.
Stupid question but, have you checked the credentials of the login? I'm still very much a noob in this area but I found out thru backing up and restoring a database (at least in MS SQL Server) that the restored user login doesn't work.
I've had to delete the user from the database and add it back in, then everything works fine. Could it be you are accessing a different version of the database on the non-working machine?
How are you indicating the Data Source/server name in your connection string? I've encountered situations where there was a hosts file on the server redirecting elsewhere, or the server was indicated by a domain name which resolved to the external IP address of the server, or other similar oddness.
Also, if you have SQL Serve installed on the server, do you also have Management Studio installed there? It's the quickest way to rule out code or permission errors, just trying variations through Management Studio until you find login details that work (or know that none do).
Usually the easiest and most secure way is using integrated security:
<connectionStrings>
<add name="HitCounterContext"
connectionString="Data Source=(local)\SQLEXPRESS;Initial Catalog=db;Integrated Security=True"
providerName="System.Data.SqlClient" />
</connectionStrings>
Make sure you use the correct instance name, which per default is "SQLExpress". I don't know how IDEs work with that, but using this connection string with IIS should at least connect successfully (which is not equal to authentication).
Maybe the authentication fails because your database must have a user for the app pool account. If you disable custom errors in your web.config so you get .net error messages, the error message should tell you that the authentication failed for the app pool user (the message actually tells you which user is used). For instance: If you create a new website called "yoursite.com" using IIS 7, per default it creates a new app pool with the name "yoursite.com". With that you'll have to add a user to the database for IIS APPPOOL/yoursite.com (might not be in the users list) and let it be the db_owner for testing.
Add the user for the app pool using "SQL Server Management Studio" like that (sorry it's german. This actually is the form after the user was added, but it should look the same while adding):
After that, your users list should look like
and the servers login list like
where each app pool has its own login for the server and user for the respective database.
By the way: Connecting from the Management Studio works just the same like from your asp.net app, except that you normally use your current user with SMS:
So, if this works, the connection from your app should do as well. The rest relies on the user for the app pool.
The fact that it's trying to login as sa locally suggests you're not using the connection string in your code; I don't think it's a SQL server problem, but an app problem.
In your app, make sure you're actually using the value of the connection string. Don't use the default constructor. E.g.
using(SqlConnection conn = new SqlConnection(WebConfigurationManager.ConnectionStrings["myconnectionstring"].ConnectionString)){ /* .. code */ }
not
using(SqlConnection conn = new SqlConnection()){ /* .. code .. */ }
If I change the connection string in my development PC to the IP address of the remote server running SQL server and debug the application it connects and runs without error!
It's possible you're dev box has been added an authenticated login, and it's automagically "working".
Comment: Using SSPI with a windows user account is preferable from a security perspective.
Answer:
Port 1433 is used for SSL by the default (unnamed) instance.
Ensure that your named instance has an SSL port properly assigned:
http://blogs.msdn.com/b/sqlexpress/archive/2005/05/05/415084.aspx
Try these connect strings (note that they don't use 'localhost' - which is case sensitive, I believe):
'Provider=SQLOLEDB;Data Source=COMPUTERNAME\SQLEXPRESS;Initial Catalog=Test;User ID=COMPUTERNAME\USERNAME; Password=PASSWORD;Integrated Security=False'
'Provider=SQLOLEDB;Data Source=.\SQLEXPRESS;Initial Catalog=Test;User ID=COMPUTERNAME\USERNAME; Password=PASSWORD;Integrated Security=False'
'Provider=SQLOLEDB;Data Source=.\SQLEXPRESS;Initial Catalog=Test;User ID=COMPUTERNAME\USERNAME; Password=PASSWORD;Integrated Security=SSPI'
ADDITIONAL EDIT:
Whenever client is run on same machine as SQL Server, the error occurs. When client is run from dev machine, no error. You may be failing to resolve the machine name because DNS does not support any of the names.
Suggestion: Connect using localhost. Ensure you can ping localhost and/or telnet localhost 1433. Ensure your hosts file (e.g. C:\Windows\System32\drivers\etc\hosts) has entry:
127.0.0.1 localhost
Alternatively, use: (local)\INSTANCENAME
Run SQLCMD –L to list installations (confirming correct browser operation).
Ensure you don't have older versions of the management tools ensured on the same server. E.g. 2008 & 2005 tools cannot coexist - but 2008 tools are backwards compatible, so you can delete both and just cleanly install 2008.

Categories

Resources