I want to tune Windows login to dbmail (for sending attachment), first step is simple open connection to SQL Server where the dbmail configuration is stored.
I have created an account in Windows named dbmail, and then I created a SQL login for it:
CREATE LOGIN [QQQQQQQ\dbmail] FROM WINDOWS
I set needed permission for this SQL login to (SqlAdministrator).
Permission
Then I try to connect to SQL with this connection string:
ATT_tds_STRING = "Data Source=localhost; Database=YYYYY; uid=QQQQQQQQ\dbmail; pwd=xxxxxxxxxxxx; Integrated Security=SSPI;"
My function placed inside COM-object
Public Function DbMailSendMail(CN As String, DbMailProfileName As String, SmSender As String, SmRecptLst As String, SmCCLst As String, SmBCCLst As String, SmSubject As String, SmMsg As String, SmAttach As String) As String Implements IDbMail.DbMailSendMail
Dim SQLCN As New SqlClient.SqlConnection(CN)
SQLCN.Open()
Try
Dim CMD As New SqlClient.SqlCommand($"EXEC msdb.dbo.sp_send_dbmail #body_format = 'HTML', " &
....
When I call my function from ASP page
Dim Mailer1, Res1
Set Mailer1 = Server.CreateObject("TDS.DbMail")
Res1 = Mailer1.DbMailSendMail (ATT_tds_STRING, "ZZZZZZZ", "", Request.Form("Mailto"), "", "", Request.Form("title"), Request.Form("body"), "C:\www\tdsv5\Images\BeOS_Help.gif")
Unfortunately I get a strange result
.Net SqlClient Data Provider error '80131904'
Login failed for user 'NT AUTHORITY\IUSR'.
I expect Windows authentication in SqlClient.SqlConnection(CN) with login QQQQQQQ\dbmail (because I use exactly Windows login and SSPI security), however Windows appears to be using IIS impersonation account NT AUTHORITY\IUSR to connect to SQL Server.
According advice #Charlieface, I have created login
CREATE LOGIN [NT AUTHORITY\IUSR] FROM WINDOWS
and set up to this login special roles in MSDB
DatabasemailUserRole
After that all working fine. Connection string is
ATT_tds_STRING = "Data Source=localhost; Integrated Security=SSPI"
Related
I'm using .NET 6, Azure Function version 4 and SqlClient in my Azure Function application.
I have a connection string like this
Server=tcp:name.database.windows.net,1433;Initial Catalog=dbName;Persist Security Info=False;User ID=username;Password=password;MultipleActiveResultSets=True;Encrypt=True;TrustServerCertificate=False;Connection Timeout=120;
Normally, I access this database using GlobalProtect by providing it portal, username and password.
Now, I'm developing an Azure Function app which will access this database, but I'm getting this error
System.Private.CoreLib: Exception while executing function:
MyAzurefunction. Core .Net SqlClient Data Provider: Cannot open
server 'serverName' requested by the login. Client with IP address
'MyIpAddress' is not allowed to access the server. To enable
access, use the Windows Azure Management Portal or run
sp_set_firewall_rule on the master database to create a firewall rule
for this IP address or address range. It may take up to five minutes
for this change to take effect.
I know I'm getting this error because my IP Address doesn't have access to the server but how can I connect to it via my Connection String?
I create azure SQL database. connection string of database:
Server=tcp:<serverName>.database.windows.net,1433;Initial Catalog=<database Name>;Persist Security Info=False;User ID=server;Password={your_password};MultipleActiveResultSets=False;Encrypt=True;TrustServerCertificate=False;Connection Timeout=30;
Image for reference:
I created function app with .net 6 in visual studio.
Image for reference:
I published it to Azure.
Image for reference:
Selected the ellipse(...) on the published page and selected Manage Azure App Service settings.
Image for reference:
Click on Add Setting in Application page and add the name of setting.
Image for reference:
In sql_connection enter the connection string of sql db in Local section for remote section click on Insert Value from Local.
Image for reference:
Install System.Data.SqlClient package in Manage Nuget packages of project. I added below code that connects to SQL Database :
using System.Data.SqlClient;
using System.Threading.Tasks;
[FunctionName("DatabaseCleanup")]
public static async Task Run([TimerTrigger("*/15 * * * * *")]TimerInfo myTimer, ILogger log)
{
// Get the connection string from app settings and use it to create a connection.
var str = Environment.GetEnvironmentVariable("sqldb_connection");
using (SqlConnection conn = new SqlConnection(str))
{
conn.Open();
var text = "UPDATE SalesLT.SalesOrderHeader " +
"SET [Status] = 5 WHERE ShipDate < GetDate();";
using (SqlCommand cmd = new SqlCommand(text, conn))
{
// Execute the command and log the # rows affected.
var rows = await cmd.ExecuteNonQueryAsync();
log.LogInformation($"{rows} rows were updated");
}
}
}
Above function runs every 15 seconds to update the Status column based on the ship date.
I added my IP address in database firewall settings.
Image for reference:
At 15 seconds after startup, the function runs.
Output of number of rows updated in the SalesOrderHeader table:
In this way I connected to my SQL database to my function app.
I have a web application where my SSRS reports are served up to the end users.
I had problems with the 401 unauthorized errors when I moved it from my local machine to the web server.
I found this was solved when I passed it my Windows account credentials, but this is not an acceptable long-term solution, as I will need to update the settings every time my network forces me to change my password, and this also puts my network login credentials into the web.config.
I have an SQL user login account created in the SSRS reporting database, with the same rights as my Windows account.
How do I get it to accept those credentials and how do I pass them?
Everything I've looked at talks about Windows authentication. I have located the config file on the database server, and it is set up with the default RSWindowsNTLM setting.
So, if I have the USER set up on the MS SQL reporting database as
User: reportUser
PW: reportUserPassword
How would that look? I'd prefer Visual Basic responses, but I can reverse engineer a C# solution. Thanks in advance.
Not sure if this will work for you, but I connect to an SSRS server from within a WinForms application like this:
Private Sub PrintReport(ByVal ReportParameters As ReportParameter(), ByVal username As String, ByVal password As String, ByVal domain As String)
With ReportViewer1 'The Microsoft.Reporting.WinForms.ReportViewer declared on my form
'Set the processing mode for the ReportViewer to Remote
.ProcessingMode = ProcessingMode.Remote
.ServerReport.ReportServerCredentials.NetworkCredentials = New System.Net.NetworkCredential(username, password, domain)
.ServerReport.ReportServerUrl = New Uri("http://192.168.x.x/server")
.ServerReport.ReportPath = "/SubFolder/" & ReportName
Try
.ServerReport.SetParameters(ReportParameters)
.RefreshReport()
Catch ex1 As System.Net.WebException
MessageBox.Show("Unable to contact Report Server. Check Link to Server", "NETWORK ERROR")
Catch ex As Exception
MessageBox.Show(ex.Message, "ERROR GENERATING REPORT")
End Try
End With
End Sub
So it may be possible for you to use .ServerReport.ReportServerCredentials.NetworkCredentials to specify a single login name for your application to connection to the SSRS server, but I'm not certain. Maybe worth checking out. Hope that helps.
I'm deploying a web application using IIS and ASP.NET CORE.
I setup a "appsetting.json" file that include a connection string to sql server.
So far, any variation I've tried didn't work.
The strange thing about it, is that it works perfectly on a my local machine, but when I deploy it and send an HTTPPost, log file says there's an error using connection to database on server.
Well, I tried all variations I could think of.
Current connection string generated by Visual Studio is :
Data Source=(localdb)\MSSQLLocalDB;Initial Catalog=Swap;Integrated
Security=True;Connect Timeout=30;Encrypt=False;
TrustServerCertificate=False;
ApplicationIntent=ReadWrite;MultiSubnetFailover=False
I've tried changing the "Integrated Security" to False.
I've tried to replace it with User ID and password (of "sa" user).
I've tried adding a "Initial Catalog" property and set it to my database.
I'm preety sure the startup of the app is fine, because when I try to send a GET request to the main page, everything seems fine.
When I send a POST request and asks the DBcontext to Add and SaveChanges, it shows this error :
fail: Microsoft.EntityFrameworkCore.Database.Connection[20004]
An error occurred using the connection to database 'Swap' on server
'(localdb)\MSSQLLocalDB'.
This is the function that I tried to send a HTTPPost request to:
byte[] j = new byte[(int)Request.ContentLength];
Request.Body.Read(j, 0, (int)Request.ContentLength);
string str = Encoding.ASCII.GetString(j);
TokenSet tokenSet = new TokenSet {Token = str };
sqlTokensetData.Add<TokenSet>(tokenSet);
sqlTokensetData.SaveChanges();
HttpClient notificationSender = new HttpClient();
HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Post,
"https://fcm.googleapis.com/fcm/send");
request.Headers.TryAddWithoutValidation("Authorization", "key="
<somekey>);
request.Headers.TryAddWithoutValidation("Sender", "id=<id>");
Message pushNotification = new Message(new string[] { str }, "Success!"
<somestring>);
request.Content = new
StringContent(JsonConvert.SerializeObject(pushNotification)
,Encoding.UTF8,"application/json");
HttpResponseMessage output = await notificationSender.SendAsync(request);
Log file error:
https://anotepad.com/notes/9a8jxa
I hope that the "str" string will be inserted to the database.
Thank you.
Well, Basicly, Thanks to the comments above I've managed to solve it.
What you need to do if you come by the same error:
1.Download SQL Server Express -
https://www.microsoft.com/en-us/sql-server/sql-server-editions-express as said above.
and configure the SQL Server however you see fit.
2.Configure sa user, set password and enable it.
3. If SQL Authentication doesn't work, then in Microsoft SQL Server Management Studio -> Right-click the server -> Properties -> Server Authentication -> Change to SQL Server and Windows Authentication
4. Change connection string to :
Data Source=;Initial Catalog=User ID=sa;
Password=;
Connect Timeout=30;Encrypt=False;TrustServerCertificate=False;
ApplicationIntent=ReadWrite;MultiSubnetFailover=False
It worked for me.
I have an issue similar to this one: SQL Server 2008: ODBC connection problems
But mine is unique because I already have the "Save Password" option checked when I link my tables, AND it works fine unless I try to open more than one query at a time.
Steps to recreate:
1) Link a SQL table to an Access 2003 front-end, my DSN looks like this:
[ODBC]
DRIVER=SQL Server
UID=ACD
WSID=ACD
APP=ACD
SERVER=xx.xx.xxx.xx,1053
Description=ACD Connection to SQL Server
Pwd=XXXXXXXX
At first I didn't have the PWD line, it doesn't seem to make a difference with or without that.
2) Open 1 query that uses the linked table, no login prompt
3) Open 2nd query while first one still open, get this error followed by login prompt:
[Microsoft][ODBC SQL Server Driver][SQL Server]Login failed.
The login is from an untrusted domain and cannot be used with Windows authentication.
I can open as many tables as I want directly and I don't get a password prompt.
If I login once, no more prompts until I restart Access, but this isn't an option for my app.
I'm using SQL server auth only, not setup for Windows auth.
You could try using a DSN-Less connection to your SQL server, microsft have a support page for this: http://support.microsoft.com/kb/892490
This should stop the prompts
You have to save the password in you connection (see parameter dbAttachSavePWD)
Dim MyTable As TableDef
Set MyTable = CurrentDb.CreateTableDef(TableName, dbAttachSavePWD, SourceTableName, ConnectionString)
CurrentDb.TableDefs.Append MyTabl
for example to attach sql table [audit].[Details] as AuditDetails you can use the following code:
Dim MyTable As TableDef
Set MyTable = CurrentDb.CreateTableDef
(
"AuditDetails",
dbAttachSavePWD,
"audit.Details",
"ODBC;DRIVER={SQL Server};APP=TransFlow®;SERVER=sqlServerName;DATABASE=dbName;UID=userName;PWD=password"
)
CurrentDb.TableDefs.Append MyTabl
I am using SQL Server Workgroup Edition on Windows Server 2003 R2
My classic ASP pages access my production database using a system DSN. All working here.
Code like this...
<%
dbName= "ProdDB"
userID = "PublicUser"
pwd = "PublicUserPW"
Set objConn = Server.createObject("ADODB.Connection")
objConn.connectionString = "DSN=MySystemDSN"
objConn.open dbName, userID, pwd
%>
For development and testing, I created a copy of ProdDB in Enterprise Manager by
Backing up ProdDB
Restoring from the ProdDB backup set to a new database called TestDB
My understanding was that the restored database would contain an exact copy of the data as well as users, roles etc. Comparing both databases in Enterprise Manager seemed to back up this assumption.
So... I assumed I can access the test copy using the same credentials and only change the dbName, like so...
<%
dbName= "TestDB"
userID = "PublicUser"
pwd = "PublicUserPW"
Set objConn = Server.createObject("ADODB.Connection")
objConn.connectionString = "DSN=MySystemDSN"
objConn.open dbName, userID, pwd
%>
However, now my page returns
[Microsoft][ODBC Driver Manager] Data
source name not found and no default
driver specified
I have even tried creating a new System DSN, with a default database pointing at TestDB. Still no joy.
I'm sure I'm doing something simple and silly. Any assistance gratefully received.
The documentation for the open method says it's declared:
connection.Open ConnectionString, UserID, Password, Options
So it looks like you're passing in TestDB as the connection string. I usually call open without specifying any arguments. Grab a connection string from connectionstrings dot com, and:
objConn.ConnectionString = "Data Source=localhost;Initial Catalog=testdb;" & _
"User Id=myUsername;Password=myPassword;"
objConn.Open