Can't login to remote SQL server - sql-server

I wrote a little app to test connection to a remote SQL server using the following code:
SqlConnection myConnection = new SqlConnection();
SqlConnectionStringBuilder bu = new SqlConnectionStringBuilder();
bu.DataSource = #"<server>";
bu.InitialCatalog = "<database>";
bu.IntegratedSecurity = false;
bu.UserID = "<user id>";
bu.Password = "<password>";
myConnection.ConnectionString = bu.ConnectionString;
try
{
myConnection.Open();
}
catch (Exception e)
{
Console.WriteLine(e.ToString());
}
I am getting the unhelpful message "login failed for user...". I can login using that user on the server itself so the credentials are correct. I have also set the database to accept remote logins. I can ping back and forth to the server.
Is there a way to further test this to try and diagnose the problem?

Related

How can I connect my javafx application to my sqlserver?

I am trying to connect to a database when I run my application I am getting the error "com.microsoft.sqlserver.jdbc.SQLServerException: The connection string contains a badly formed name or value".
I have tried changing some of the variables around but cannot figure out where my error is. Can anyone help?
try{
DriverManager.registerDriver(new com.microsoft.sqlserver.jdbc.SQLServerDriver());
String dbURL = "jdbc:sqlserver://[myservername];databaseName=[databasename];user=[enteruserdbhere];password[enterpasswordhere];";
Connection conn = DriverManager.getConnection(dbURL);
Statement statement = conn.createStatement();
conn.close();
statement.close();
} catch (SQLException e) {
e.printStackTrace();
}
Try removing the '[]' brackets from the connection string.
The link below shows examples of connection strings for jdbc https://learn.microsoft.com/en-us/sql/connect/jdbc/building-the-connection-url?view=sql-server-ver15
You should remove the brackets [ ] for your connection URL.
String server = "localhost";
String dbName = "myDB";
String username = "root";
String pwd = "";
String dbURL = "jdbc:sqlserver://server;databaseName=dbName;user=username;password=pwd;";
Also import your jdbc driver to the project as well us in the Connection.java file

Azure AD SQL Authentication giving Network-related or instance-specific error occurred while establishing a connection to SQL Server

I am attempting to connect to Azure SQL from a webapi service running on IIS. If I use a connection string with user id and password it works fine.
When I use connection string builder using an access token generated by sending ClientAssertionCertificate to Azure AD, I get the connection error above.
When I create the same code in a Console Application and run it on the same VM as the IIS server, it works fine.
I thought this might be related to permissions since it works in the Console Application. I tried changing the identity used by DefaultAppPool but that did not work.
string accessToken = TokenFactory.GetAccessToken();
var builder = new SqlConnectionStringBuilder();
builder["Data Source"] = $"tcp:{dbServer}.database.windows.net,1433";
builder["Initial Catalog"] = dbName;
builder["Connect Timeout"] = 30;
builder["Persist Security Info"] = false;
builder["TrustServerCertificate"] = false;
builder["Encrypt"] = true;
builder["MultipleActiveResultSets"] = true;
var con = new SqlConnection(builder.ToString());
con.AccessToken = accessToken;
// attempting to use the con from the SqlConnecti
CompanyService _cs = new CompanyService(con);
var company = _cs.GetCompany(1);
return Request.CreateResponse(HttpStatusCode.OK, new { teststring = accessToken } );

AWS Lambda function unable to establish connection to SQL Server RDS instance

I have written the following small Lambda function in .NET core for testing purposes. It is triggered on a PUT in an S3 bucket, and should show the object name in CloudWatch and insert the object name into a table in an RDS instance.
Here is the code:
public async Task<string> FunctionHandler(S3Event evnt, ILambdaContext context)
{
context.Logger.LogLine("context.Logger.LogLine function begin");
var s3Event = evnt.Records?[0].S3;
if(s3Event == null)
{
context.Logger.LogLine("No S3 Events recorded");
return null;
}
try
{
var response = await this.S3Client.GetObjectMetadataAsync(s3Event.Bucket.Name, s3Event.Object.Key);
context.Logger.LogLine("S3 Key: " + s3Event.Object.Key.ToString());
var connectionString = Environment.GetEnvironmentVariable("ConnectionString");
SqlConnection c = new SqlConnection(connectionString);
c.Open();
SqlCommand cmd = new SqlCommand("INSERT INTO LambdaTestTable (ValueText) VALUES('" + s3Event.Object.Key + "')", c);
cmd.ExecuteNonQuery();
c.Close();
return response.Headers.ContentType;
}
catch(Exception e)
{
context.Logger.LogLine($"Error getting object {s3Event.Object.Key} from bucket {s3Event.Bucket.Name}. Make sure they exist and your bucket is in the same region as this function.");
context.Logger.LogLine(e.Message);
context.Logger.LogLine(e.StackTrace);
throw;
}
}
I get the following output in CloudWatch:
START RequestId: 15c5eddb-8171-11e7-af34-251688cfddb2 Version: $LATEST
Console.WriteLine function begin context.Logger.LogLine function begin
S3 Key: TaskTemplate.dp Error found Error getting object
TaskTemplate.dp from bucket api-dev-dpstorage-s3. Make sure they exist
and your bucket is in the same region as this function. 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: 40 - Could not open a connection to SQL Server)
Two errors I am unclear on here. Firstly, while CloudWatch successfully shows my object key once the file is PUT to the bucket, it then has an error saying it can't find the object? Secondly, it has a network / instance error trying to connect to the SQL RDS instance. I am using a connection string which is used successfully within an EC2 instance by another application.

SSIS Send email from package that is off the domain

I have a SSIS package that is deployed to server that is not on a domain but it is within our network perimeter. I would like to be able to send an email on package failure but being off the domain presents a challenge that I have not faced before.
Using a dummy gmail account is not acceptable to the business.
I would like to use the company SMTP server (mail.somecompany.com) but I do not know how to do this while off the domain. Can someone please tell me if this is possible and what steps I need to take.
Useful information:
SQL Server 2016
Project Deployment mode
Visual Studio 2015
Many thanks in advance.
You can use script task for sending mail.
This might can help you:
MailMessage Mymsg = new MailMessage();
SmtpClient smptserver = new SmtpClient();
System.Net.Mail.Attachment attach;
Mymsg.From = new MailAddress("aa#abc.com");
String Tolist = Convert.ToString("a#aa.com");
String CClist = Convert.ToString("a#xse.com");
String BCClist = Convert.ToString("ba#aas.com");
if (!String.IsNullOrEmpty(Tolist))
Mymsg.To.Add(Tolist);
if (!String.IsNullOrEmpty(CClist))
Mymsg.CC.Add(CClist);
if (!String.IsNullOrEmpty(BCClist))
Mymsg.Bcc.Add(BCClist);
Mymsg.Subject = "Subject!";
Mymsg.Body = "Hi, Your message!";
Mymsg.IsBodyHtml = true;
try
{
smptserver.Send(Mymsg);
Console.WriteLine("OK");
}
catch (System.Net.Mail.SmtpException ex)
{
Console.WriteLine(ex.StatusCode.ToString());
}
Dts.TaskResult = (int)ScriptResults.Success;
smptserver = null;
Mymsg = null;

Reseting SQL Application role after the connection has been closed

I'm using sql application roles from a .net application. I have an issue which occurs when the connection is lost. So as an example I have this block of code which opens a connection, sets the app role, does a select from the database and the disposes my connection. If I run this code a 2nd time it fails when trying to set the app role again (the ExecuteNonQuery() line for the sys.sp_setapprole).
The exception is an SqlException: A severe error occurred on the current command. The results, if any, should be discarded.
I've tried using the #fCreateCookie parameter and calling sys.sp_unsetapprole to reset the role but this makes no difference.
Help please?
using (SqlConnection connection = new SqlConnection(myConnectionString))
{
connection.Open();
using (SqlCommand command = new SqlCommand("sys.sp_setapprole", connection))
{
command.CommandType = CommandType.StoredProcedure;
command.Parameters.AddWithValue("#rolename", "MyRole");
command.Parameters.AddWithValue("#password", "MyPassword");
command.ExecuteNonQuery();
}
try
{
DataSet ds = new DataSet();
using (SqlCommand command = new SqlCommand("dbo.MyProcedure", connection))
using (SqlDataAdapter adapter = new SqlDataAdapter(command))
{
command.CommandType = CommandType.StoredProcedure;
adapter.Fill(ds);
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}

Resources