Generating token for connecting to azure sql takes too long - azure

I am trying to fetch token using GetAccessTokenAsync in C#, the code works fine and I am able to connect but the issue is it's taking too long to generate token(around 30 sec). Does anyone else facing similar issue?
var conn = (SqlConnection)this.Database.GetDbConnection();
conn.AccessToken = new AzureServiceTokenProvider()
.GetAccessTokenAsync("https://database.windows.net/")
.Result;

Can you please disable telemetry and try? Details are here. I believe it is the collect_telemetry option.

Related

Azure Table Storage query failed with authentication error (Received:Forbidden) from time to time

Environment: Azure app service.
Azure storage SDK: WindowsAzure.Storage (9.3.3)
Invocation (pseudo code):
void QueryAzureTable(){
while(true){
var tableClient = new AzureTable();
var resp = tableClient.Query('table','pk','rk');
// ...
}
}
var tasks = new List<Task>();
for (var i = 0; i < 5; i++)
{
tasks.Add(QueryAzureTable());
}
await Task.WhenAll(tasks).ConfigureAwait(false);
Authorization method for QueryAzureTable: tried with both clientId/secret and managed identity/MSI, same result for both.
Observation:
Around half of the requests failed due to anth issue in QueryAzureTable() (see detailed error msg below).
If I restart the azure app service instance, the auth error will be gone for ~12 hours.
Error Message:
Server failed to authenticate the request. Make sure the value of Authorization header is formed correctly including the signature.
Unexpected response code, Expected:OK or NotFound, Received:Forbidden
I have checked and tried with almost every solutions mentioned in this stackoverflow thread, but no luck.
Guess this specific auth issue might be related with multi-tasks.
Kind of figured out the solution on my own: adding a retry logic to renew the token.
void query(...){
int cnt=0;
while(true){
try{
_client.queryTable(...);
}
catch(AuthException ex){
log.error(ex...);
var token=new Token(...);
_client = new AzureTableClient(token);
cnt++;
if(cnt==3) throw;
}
}
}
The first clue to this solution was whenever there was a app service release, deployment or restart of the app service, the query table function worked well for a while, and then after around 12 hours, errors started showing up. But not 100% failure rate.
If there is any explanation or conclusion that helps to root cause this, please share your opinions. Thanks in advance!
My blind guess is that it has something to do with muti-tasks: WindowsAzure.Storage (9.3.3) does not do a good job of renewing token for muti-tasks.
Hope this could help you.

Connection to Entity Framework works locally, Was working in Azure but now I get "Invalid object name..."

I have looked through various posts related to this problem, but none provide an answer. I created a .Net 5.0 app that accesses an Azure SQL DB using EF 6.4.4 which works with .Net standard libraries. I modified the EF by adding a function that creates the connection string from appsettings.json since .Net 5 apps don't use a web.config file. This also works well in Azure with the configuration settings in an app service.
The connection string looks like this:
metadata=res://*/EF.myDB.csdl|res://*/EF.myDB.ssdl|res://*/EF.myDB.msl;provider=System.Data.SqlClient;provider connection string='Data Source=tcp:mydb.database.windows.net,1433;Initial Catalog=myDB;Integrated Security=False;Persist Security Info=False;User ID=myuserid#mydb;Password="password";MultipleActiveResultSets=True;Connect Timeout=120;Encrypt=True;TrustServerCertificate=True'
I also have a deployment pipeline that will deploy the code after a check-in instead of using the Visual Studio publish feature, but the pipeline deployed code has the same problem.
When I first created the app and published it to the app service, it worked. Recently I updated the app with no changes to the EF connection. Now I get the "Invalid Object name when I reference any table in the model. If I run the same code locally and connect to the Azure SQL DB, the DB is accessed as expected. This problem only occurs when running in the Azure app service. Note that there are no connection strings configured for the app service since the EF string is built from the config settings. I saw this post, but I don't think it applies:
Local works. Azure give error: Invalid object name 'dbo.AspNetUsers'. Why?
even though the problem is the same. I have also read various posts about the format of the EF connection string. Since my model is database first, (and the connection used to work), I'm confident the string has the correct format. I don't think the problem is in the code since it works when running locally with a connection to the Azure SQL DB. It must have something to do with the Azure app service configuration, but I'm not sure what to look for at this point. Unfortunately I don't have a copy of the code and publish files that did work to compare to, but it the pipeline build doesn't work either and that it how the code would normally be deployed. Thanks for any insight you might have!
UPDATE
metadata=res://*/EF.myDB.csdl|res://*/EF.myDB.ssdl|res://*/EF.myDB.msl;provider=System.Data.SqlClient;provider connection string='Data Source=tcp:yourdbsqlserver.database.windows.net,1433;Initial Catalog=yourdb;Persist Security Info=False;User ID=userid;Password=your_password;MultipleActiveResultSets=False;Encrypt=True;TrustServerCertificate=False;Connection Timeout=30'
When the troubleshooting problem is not on the string, our easiest way is to use vs2019 to re-use the generated string.
Your connection string should be like below.
<connectionStrings>
<add name="SchoolDBEntities" connectionString="metadata=res://*/SchoolDB.csdl|res://*/SchoolDB.ssdl|res://*/SchoolDB.msl;provider=System.Data.SqlClient;provider connection string="data source=.\sqlexpress;initial catalog=SchoolDB;integrated security=True;multipleactiveresultsets=True;application name=EntityFramework"" providerName="System.Data.EntityClient"/>
</connectionStrings>
For more details, you can refer my answer in the post and the tutorial.
1. Timeout period elasped prior to obtaining a connection from the pool - Entity Framework
2. Entity Framework Tutorial
The problem was one of my config settings in Azure. The catalog parameter was missing. A simple fix, but the error message was misleading, so I thought I would note that here in case anyone else gets the same "Invalid object name" message when referencing an Azure SQL DB with EF. It would have been more helpful if the message was "catalog name invalid" or "unable to connect to database".
For those who are curious about building an EF connection string, here is example code:
public string BuildEFConnectionString(SqlConnectionStringModel sqlModel, EntityConnectionStringModel entityModel)
{
SqlConnectionStringBuilder sqlString = new SqlConnectionStringBuilder()
{
DataSource = sqlModel.DataSource,
InitialCatalog = sqlModel.InitialCatalog,
PersistSecurityInfo = sqlModel.PersistSecurityInfo,
UserID = sqlModel.UserID, // Blank if using Windows authentication
Password = sqlModel.Password, // Blank if using Windows authentication
MultipleActiveResultSets = sqlModel.MultipleActiveResultSets,
Encrypt = sqlModel.Encrypt,
TrustServerCertificate = sqlModel.TrustServerCertificate,
IntegratedSecurity = sqlModel.IntegratedSecurity,
ConnectTimeout = sqlModel.ConnectTimeout
};
//Build an Entity Framework connection string
EntityConnectionStringBuilder entityString = new EntityConnectionStringBuilder()
{
Provider = entityModel.Provider, // "System.Data.SqlClient",
Metadata = entityModel.Metadata,
ProviderConnectionString = sqlString.ToString()
};
return entityString.ConnectionString;
}
Given what I have learned, the properties should be validated before the string is returned. If the string is created this way, all of the connection string properties can be added to the config settings in the app service. I used the options pattern to get them at runtime. Thanks to everyone for your suggestions.

Getting Connection Reset Issue while Fetching Azure Access Token

hope everyone is well.
I am using azure library to fetch access token using the below code snippet, but getting an error
Execution of class com.microsoft.aad.msal4j.AcquireTokenByAuthorizationGrantSupplier failed.
com.microsoft.aad.msal4j.MsalClientException: java.net.SocketException: Connection reset
When I enclose the code in try catch, it gets catched as an ExecutionException.
Below is the code snippet.
ConfidentialClientApplication app = ConfidentialClientApplication.builder("XXX", ClientCredentialFactory.createFromCertificate(XXX, "")).authority("https://login.microsoftonline.com/XXX").build();
ClientCredentialParameters clientCredentialParam = ClientCredentialParameters.builder(Collections.singleton(String.format(https://graph.microsoft.com/.default))).build();
CompletableFuture future = app.acquireToken(clientCredentialParam);
//call to future.get() function
I appreciate if anyone could help me in this issue as I am unable to find any solution for this for the past 2 weeks, tried so many ways but no success.
Thanks

TransactionScope in azure webjobs

I have a webjob running in azure that is processing data sent to an event hub.
In the eventprocessor I want to save information to a SQL server. To make sure that everything is inserted correctly I want to use transactions.
When I run the code locally everything works perfect. But when running in Azure nothing happens, no error is thrown.
What I have read it should be possible to use TransactionScope. This example code below is not working.
using (TransactionScope scope = new TransactionScope())
{
dataImportDao.StartProcessingMessage(mappedMessage);
scope.Complete();
}
Any suggestions how to solve it or if I should go with a different approach is very appreciated.

topicClient.Send timeout exception

I have a topicClient created from messagingfactory using connectionString
MessagingFactory.CreateFromConnectionString(connectionString)
MessagingFactory.CreateQueueClient(topicName).
In low band networks i get a timeout exception when sending messages to Azure Topic. Is there a way to change the timeout property?
I know there is a way when we use MessagingFactory.Create() method.
Thanks in advance
Here's the Code Snippet:
MessagingFactorySettings settings = new MessagingFactorySettings {
settings.OperationTimeout = TimeSpan.FromSeconds(120)
};
MessagingFactory messagingFactory = MessagingFactory.Create(connection, settings);
and more over - if you need performance critical messaging - ServiceBus also supports the standard Protocol for Messaging - AMQP.
settings.TransportType = TransportType.Amqp;
BTW, I guess a typo, but just in case - in your code snippet use : CreateTopicClient (not createQueueClient)
Hope it helps!
Sree
For those of you who stumbled here through google. I got a similar problem while using the 'Microsoft.Azure.ServiceBus' package in .NET core. I got a time out error when trying
await client.SendAsync(message);
In my case the problem was that my company was blocking port 5671.
Switching to AmqpWebSockets resolved my issue.
Put this after your connection string.
;TransportType=AmqpWebSockets

Resources