Server cannot connect to SQL server - c#

I have a C# Service project where I am connectiong to SQL and retrieving data.
When I debug locally eg: in the Visual Studion Developement Server it works nice.
But when I upload to the server(simply localhost/MyProject/) The SqlCommand() is throws an exception. Are there way to get more information on SqlCommand()?
What permissions I should set to run web service on the server?
Maybe mode details:
The project within VS2008 envirenoment is works nice:
http://localhost:50301/GetJpeg.aspx?ra=224.5941&dec=-1.09&width=1000&height=1000&scale=1
but on the http://localhost/GetJpeg.aspx?ra=224.5941&dec=-1.09&width=1000&height=1000&scale=1 no.
The exception is not really exception the:
SqlDataReader reader does not return any result in second case:
reader = cmdCenter.ExecuteReader();
if (reader.Read())
{
//Do Something
reader.Close();
}
else
{
throw new Exception("Request is failed");
}
Thanks Arman.
EDIT
Just for information:
In one case the code is debugged via ASP.NET Developement Server and the second one is running on IIS 7.0
UPDATE
After deep digging I discovered: The connection is open and connected, usual queries is ok, but queries with stored functions are failing... can be that IIS miss configuration ?

If you are using the SqlCommand control (drag-dropped onto a page) instead of the SqlCommand object (code), your best bet will be to add a page-level error handler (http://msdn.microsoft.com/en-us/library/ed577840.aspx).
Most likely, the problem is that your connection string uses SSPI for authenticating to the SQL Server (integrated/domain security). That would allow you to connect via Visual Studio, but not once it is deployed. You might want to look at this article (http://msdn.microsoft.com/en-us/library/bsz5788z.aspx). The answers in that article are not ideal, but they will get you moving along. The better approaches can get pretty complicated. Read-up on those once you get your app working again.

You can attach the Debugger in VS to IIS on your box and continue debugging. To do this, go to Debug->Attach to Process and then find the W3wp.exe process that is running the Application Pool your application is running in.

try
{
using (SqlConnection connection = new SqlConnection("Your connection string here"))
{
using (SqlCommand command = new SqlCommand("your sql here", connection))
{
connection.Open();
using (SqlDataReader reader = command.ExecuteReader())
{
}
}
}
}
catch (Exception exception)
{
System.Diagnostics.Debug.WriteLine(exception);
}
Breakpoint in the catch to see the exception in your debugger.

Related

C# MVC Core 5 Site throws encoding error when trying to open a connection to Azure SQL DB

As stated above. Under IIS Express on VS2019 I have no issues. When opening the site after deployment to Azure I get:
"The character encoding of the plain text document was not declared. The document will render with garbled text in some browser configurations if the document contains characters from outside the US-ASCII range. The character encoding of the file needs to be declared in the transfer protocol or file needs to use a byte order mark as an encoding signature."
I initially tried adding every permutation of
<meta charset="UTF-8"/> I found to no avail. Eventually I tracked the error down (by removing lines of code until the error no longer appeared) to firing when I tried to open a SqlConnection.
public DataTable FillDatatable(SqlCommand cmd)
{
DataTable dt = new DataTable();
using (SqlConnection connect = new SqlConnection(CONST.CONN))
using (SqlDataAdapter da = new SqlDataAdapter(cmd))
{
cmd.Connection = connect;
connect.Open(); //-- Error throws when this is in the code
da.Fill(dt); //-- Error throws when this is in the code as this calls the
//-- line prior innately.
}
return dt;
}
Cannot figure out why for the life of me.
TL;DR - Encoding error thrown on SqlConnection.Open() when running from published Azure Web App but works perfectly under IIS Express in VS2019.
EDIT-
Quick and dirty connection string:
public const string CONN = "Data Source=MYDBADDRESS;Initial Catalog=Primary;Persist Security Info=True;User ID=USERNAME;Password=PWD;";
appsettings.json has only Logging information and "AllowedHosts"="*"
I never set any Firewall policies. Looking at Firewalls in the Portal there are none.
Site is very, very basic. Just trying to get it up and running before I continue any further and this data blocker is bringing me no joy. :/
Sql server needs to set firewall policy be default, so I assume that after deploying app to azure web app, ip address must change and may lead to some error.
#Destroigo here met the firewall problem. Congratulations to solve it :)

Running SQL script as part of visual studio 2010 Setup Project

Good day,
My goal is to create a msi for a windows service and during installation various sql scripts must run.
What I want to do is create a msi that, when the user runs it, it installs the service on the pc and runs 3 .sql scripts, one for creating the database, one for population, and one to add a stored procedure.
I am able to add create a setup project for the service using the msdn overview
My problem is that I have no idea how to run a sql script during the install (and how to specify the sql connection)
Is there any way to do this in visual studio, or will I need to resort to batch files/purchasing InstallShield?
Any help is appreciated,
Regards
Jeff
EDIT: I am using visual studio 2010 Professional and SQLServer 2012
You can run the SQL script during the installation exactly the same way you'd do it in any other C# application.
In the MSDN overview you've mentioned in the question, there is reference to writing your own code during the installation, so I'll assume you already know how to do that.
There are many ways to do this. Here's just one example out of many, quoted from here:
string queryString = "SELECT tPatCulIntPatIDPk, tPatSFirstname, tPatSName, tPatDBirthday FROM [dbo].[TPatientRaw] WHERE tPatSName = #tPatSName";
string connectionString = "Server=.\PDATA_SQLEXPRESS;Database=;UserId=sa;Password=2BeChanged!;";
using (SqlConnection connection = new SqlConnection(connectionString))
{
SqlCommand command = new SqlCommand(queryString, connection);
command.Parameters.AddWithValue("#tPatSName", "Your-Parm-Value");
connection.Open();
SqlDataReader reader = command.ExecuteReader();
try
{
while (reader.Read())
{
Console.WriteLine(String.Format("{0}, {1}",
reader["tPatCulIntPatIDPk"], reader["tPatSFirstname"]));// etc
}
}
finally
{
// Always call Close when done reading.
reader.Close();
}
}

SQLCacheDependency not working in Load balanced environment with sql server 2008

We have implemented sqlcachedependency in our application. We have multiple caches depending on one database table and set the sql cache policy with a sql monitor as shown below.
policy = new CacheItemPolicy();
//connection string name
var connectionString = connectionstring;
//SQlDependency Cache
SqlDependency.Start(connectionString);
SqlChangeMonitor monitor = null;
using (var connection = new SqlConnection(connectionString))
{
using (var command = new SqlCommand("SELECT col1,col2 FROM dbo.table1", connection))
{
var dependency = new SqlDependency(command);
connection.Open();
command.ExecuteReader();
monitor = new SqlChangeMonitor(dependency);
}
}
policy.ChangeMonitors.Add(CreateMonitor());
This method is called while adding multiple cache. Everything is working fine when we check on the development machine. But once we upload the application in load balanced QA machine(QA1,QA2,QA3) it is not working.
All the grant permissions and sql broker enabling is done on the database.
When we check the sql profiler, we see that subscriptions are being registered in the database. But the notification from the sql broker and not working back in the application when an update is done on the table. We see the following error in profiler
**Cannot find the remote service &apos;SqlQueryNotificationService-
ab49a23a-9beb-4a6f-a8b0-299bcfddbeda&apos; because it does not
exist.
and
This message has been dropped because the TO service could not be
found. Service name: "SqlQueryNotificationService-58237ce1-
aa4d-4999-9fd8-d0b78c1d932b". Message origin: "Local".**
Any help regarding this will be highly appreciable.
Finally, was able to find the answer. Basically it is the permission issue. Below link helped me grant permissions which fixed the issue
http://social.msdn.microsoft.com/Forums/sqlserver/en-US/bd195da8-93b2-43c6-8f59-674f5fb9d618/cannot-find-the-queue-sqlquerynotificationserviceguid?forum=sqlservicebroker

SqlClient.SqlException: The wait operation timed out

I'm currently trying to create a large amount of test data with numerous insert statements using code similar to below...
using (var connection = new SqlConnection(_connectionString))
{
using (var command = new SqlCommand(query.ToString(), connection))
{
try
{
connection.Open();
command.ExecuteNonQuery();
return true;
}
catch (Exception e)
{
......
}
}
}
My problem is that I keep getting an error
The wait operation timed out
and yet when I run the SQL statement that failed from within SQL Server Management Studio, it executes in less than 100ms. The error always seems to occur whilst inserting into the largest table which currently has 47,738,476 rows and is 1,970,696Kb in size.
I'm using:
Microsoft SQL Server 2012 (SP1) - 11.0.3128.0 (X64)
Express Edition (64-bit) on Windows NT 6.1 <X64> (Build 7601: Service Pack 1)
Any, help would be most appreciated.
Disclaimer: It may not be an answer but it solves the problem :)
Use Redgate Sql Data Generator
http://www.red-gate.com/products/sql-development/sql-data-generator/
It is not free but it is fully functional trial for some days and it will do the work for you what i want to
achieve.
It had lot of option and generate real looking data.

SQL Server Azure "Login failed for User"

I am using the following code to perform SQL commands to my azure DB. The I do two calls inside my ASP.NET MVC action method. One to delete from Table A, and the second call to delete from Table B.
using (System.Data.SqlClient.SqlConnection conn = new System.Data.SqlClient.SqlConnection(ConnectionString))
{
using (System.Data.SqlClient.SqlCommand command = conn.CreateCommand())
{
conn.Open();
command.CommandText = statement;
command.ExecuteNonQuery();
}
}
For whatever reason when I make the second call to this code (I have it in a Helper service class, it bombs with the following Azure error.
Additional information: Login failed for user 'MyUser'.
Is there something I'm not doing correctly but not perhaps closing a connection or something that Azure is having issues with this?
You need allow your IP Address to access azure database. click in configure and add your IP.
I just needed add to the connection string
Persist Security Info=False;
when you publish your project into azure from visual studio, there is a 'settings' tab on the left.
go to the settings. it will show you the connection string that you're using in the web.config.
what worked for me is I unchecked the check box that says 'Use this connection string at runtime (update destination web.config)' and everything went well for me.

Categories

Resources