CLR webservice call times out at 100 seconds - sql

I have not found this answered anywhere. I have a CLR function that exectues a webmethod call of my .NET application (.asmx). The web service successfully executes when called directly but when called via the CLR it times out after 100 seconds with the following error:
Msg 6522, Level 16, State 1, Line 1
A .NET Framework error occurred during execution of user-defined routine or aggregate "fn_ExecuteReport":
System.Net.WebException: The operation has timed out
System.Net.WebException:
at System.Web.Services.Protocols.WebClientProtocol.GetWebResponse(WebRequest request)
at System.Web.Services.Protocols.HttpWebClientProtocol.GetWebResponse(WebRequest request)
at System.Web.Services.Protocols.SoapHttpClientProtocol.Invoke(String methodName, Object[] parameters)
at DD.WebServices.WebExec.ExecuteReport(String ddBotID, String serverKey, Int32 ddUserID, String reportReportTypeList, String deliverToUserList)
at ExecuteReport.GetResult(Int32 userID, SqlString reportList, SqlString deliverToUserList)
I have increased the web service proxy timeout in fn_ExecuteReport without effect:
WebExec svc = new WebExec();<br/>
svc.Timeout = 3600000; // set timeout to 1 hour<br/>
result = svc.ExecuteReport(userID, reportTypeList.ToString(),
deliverToUserList.ToString());
I want to capture the returned result so executing the webservice asynchronously is not a solution. Where else might I override timeout settings for the SQL CLR call? Thanks for any help you can provide.
Here's the code for the function. I'm able to execute the webservice, the timeout only occurs when executing via the CLR.
ALTER FUNCTION [dbo].[fn_ExecuteReport]
(#UserID int, #ReportTypeList nvarchar(max), #DeliverToUserList nvarchar(max))
RETURNS [nvarchar](255)
WITH EXECUTE AS CALLER AS EXTERNAL NAME [MyCLRLib].[ExecuteReport].[GetResult]
I've tried both synchronous and asynchronous calls to the web service in the CLR function and both end up with the 100 second timeout. Here's both calls that I've tried:
Synchronous:
WebExec svc = new WebExec();
svc.Timeout = 3600000; // set timeout to 1 hour
result = svc.ExecuteReport(userID, reportTypeList.ToString(), deliverToUserList.ToString());
Asynchronous:
WebExec svc = new WebExec();
IAsyncResult result = svc.BeginExecuteReport(userID, reportTypeList.ToString(), deliverToUserList.ToString(), null, null);
result.AsyncWaitHandle.WaitOne();
retStr = svc.EndExecuteReport(result);

Your error message suggests that the timeout is originating at SQL Server.
Have you tried updating your SQL Server statistics (or rebuilding indexes)?
Can you post the code of your CLR function?

Related

Database timeout in Azure SQL

We have a .Net Core API accessing Azure SQL (Gen5, 4 vCores)
Since quite some time,
the API keeps throwing below exception for a specific READ operation
Microsoft.Data.SqlClient.SqlException (0x80131904): Execution Timeout
Expired. The timeout period elapsed prior to completion of the operation or the server is not responding.
The READ operation has code to read rows of data and convert an XML column into a specific output format.
Most of the read operation extracts hardly 4-5 rows # a time.
The tables involved in the query have ~ 500,000 rows
We are clueless on Root Cause of this issue.
Any hints on where to start looking # for root cause?
Any pointer would be highly appreciated.
NOTE : Connection string has following settings, apart from others
MultipleActiveResultSets=True;Connection Timeout=60
Overall code looks something like this.
HINT: The above timeout exception comes # ConvertHistory, when the 2nd table is being read.
HttpGet]
public async Task<IEnumerable<SalesOrders>> GetNewSalesOrders()
{
var SalesOrders = await _db.SalesOrders.Where(o => o.IsImported == false).OrderBy(o => o.ID).ToListAsync();
var orders = new List<SalesOrder>();
foreach (var so in SalesOrders)
{
var order = ConvertSalesOrder(so);
orders.Add(order);
}
return orders;
}
private SalesOrder ConvertSalesOrder(SalesOrder o)
{
var newOrder = new SalesOrder();
var oXml = o.XMLContent.LoadFromXMLString<SalesOrder>();
...
newOrder.BusinessUnit = oXml.BusinessUnit;
var history = ConvertHistory(o.ID);
newOrder.history = history;
return newOrder;
}
private SalesOrderHistory[] ConvertHistory(string id)
{
var history = _db.OrderHistory.Where(o => o.ID == id);
...
}
Microsoft.Data.SqlClient.SqlException (0x80131904): Execution Timeout Expired. The timeout period elapsed prior to completion of the operation or the server is not responding.
From Microsoft Document,
You will get this error in both conditions Connection timeout or Query or command timeout. first identify it from call stack of the error messages.
If you found it as a connection issue you can either Increase connection timeout parameter. if you are still getting same error, it is causing due to a network issue.
from information that you provided It is Query or command timeout error to work around this error you can set CommandTimeout for query or command
command.CommandTimeout = 10;
The default timeout value is 30 seconds, the query will continue to run until it is finished if the time-out value is set to 0 (no time limit).
For more information refer Troubleshoot query time-out errors provided by Microsoft.

LSP4J : Language Server method call never ends

I have created a Java-based LSP client, but none of the method calls are completed & it waits indefinitely.
Socket socket = new Socket("localhost", 6008);
Launcher<LanguageServer> createClientLauncher = LSPLauncher.createClientLauncher (languageClient,
socket.getInputStream(), socket.getOutputStream());
LanguageServer server = createClientLauncher.getRemoteProxy();
createClientLauncher.startListening();
InitializeResult result = server.initialize(new InitializeParams()).get();
System.out.println("end");
initialize method never returns. The Language Server is working fine when tested with the VSCode instance.
Seems like requests are not reaching the server as nothing is printed in trace logs of server.

Azure SQL Serverless Database return code when paused

Description:
I have an application that connects to an Azure Serverless Database. The database can be in a paused state and in an online state. The database auto-pauses when there has been no activity for one hour. This means that when my application tries to open a connection to the database when it is paused, the connection times out and gives a timeout exception.
Azure states in their documentation that:
If a serverless database is paused, then the first login will resume the database and return an error stating that the database is unavailable with error code 40613. Once the database is resumed, the login must be retried to establish connectivity. Database clients with connection retry logic should not need to be modified. source
I am able to get this error code 40613 returned when I try to connect to the database via SQL Management Studio. But when I try to open a connection to the database from my application I only get a timeout exception, hence I don't know whether or not the database is not available or if the database is in fact resuming.
Code example:
public IDbConnection GetConnection()
{
var connection = new SqlConnection(_connectionString);
try
{
connection.Open();
return connection;
}
catch (SqlException e)
{
if (e.Number == 40613)
{
//Database is resuming
}
}
finally
{
connection.Close();
}
}
Exception example:
When I run my application and the database is in paused state I get this exception:
Snippet of exception in Visual Studio
Does anyone know why I don't get the error code 40613 that Azure states in their documentation?
Indeed you may get timeout errors when the Azure database is unavailable. In fact you may get the following errors:
HTTP error GatewayTimeout : The gateway did not receive a response
from ‘Microsoft.Sql’ within the specified time period
HTTP error ServiceUnavailable : The request timed out
SQLException : Execution Timeout Expired. The timeout period elapsed prior to completion of the operation or the server is not responding.
You may get also error 40613 but you can capture some transient errors like below too:
•Database on server is not currently available. Please retry the connection later. If the problem persists, contact customer support, and provide them the session tracing ID of
•Database on server is not currently available. Please retry the connection later. If the problem persists, contact customer support, and provide them the session tracing ID of . (Microsoft SQL Server, Error: 40613)
•An existing connection was forcibly closed by the remote host.
•System.Data.Entity.Core.EntityCommandExecutionException: An error occurred while executing the command definition. See the inner exception for details. ---> System.Data.SqlClient.SqlException: A transport-level error has occurred when receiving results from the server. (provider: Session Provider, error: 19 - Physical connection is not usable)
•An connection attempt to a secondary database failed because the database is in the process of reconfguration and it is busy applying new pages while in the middle of an active transation on the primary database.
Because of those errors and more explained here, it is necessary to create a retry logic on applications that connect to Azure SQL Database.
public void HandleTransients()
{
var connStr = "some database";
var _policy = RetryPolicy.Create < SqlAzureTransientErrorDetectionStrategy(
retryCount: 3,
retryInterval: TimeSpan.FromSeconds(5));
using (var conn = new ReliableSqlConnection(connStr, _policy))
{
// Do SQL stuff here.
}
}
More about how to create a retry logic here.

Entity Framework SQL Timeout after x number of WCF requests

There are around 300 clients each making requests to a WCF service every ten minutes. They are not all making requests at exactly the same time.
This LINQ query in a Service class is trying to get configFeedItems that the client has not already received (note: I'm using Ninject to inject the Repository into my Service class):
var configFeedItems = (from feedItem in configFeedItemRepository.All
where feedItem.Id > lastReceivedFeedItemId &&
(feedItem.TargetUserId == userId || feedItem.TargetUserId == null) &&
!feedItem.ConfigFeedItemReceipts.Any(x => x.User.Id == userId)
select feedItem)
.ToList();
Which causes this exception to be thrown:
[SqlException (0x80131904): Timeout expired. The timeout period elapsed prior to completion of the operation or the server is not responding.]
This is the SQL that gets generated:
exec sp_executesql N'SELECT
[Extent1].[Id] AS [Id],
[Extent1].[Action] AS [Action],
[Extent1].[TargetId] AS [TargetId],
[Extent1].[TargetCommand] AS [TargetCommand],
[Extent1].[CreatedOn] AS [CreatedOn],
[Extent1].[TargetUserId] AS [TargetUserId],
[Extent1].[ChannelToUpdate] AS [ChannelToUpdate],
[Extent1].[CreatedBy_Id] AS [CreatedBy_Id]
FROM [dbo].[ConfigFeedItem] AS [Extent1]
WHERE ([Extent1].[Id] > #p__linq__0) AND ([Extent1].[TargetUserId] = #p__linq__1 OR [Extent1].[TargetUserId] IS NULL) AND ( NOT EXISTS (SELECT
1 AS [C1]
FROM [dbo].[ConfigFeedItemReceipt] AS [Extent2]
WHERE ([Extent1].[Id] = [Extent2].[ConfigFeedItem_Id]) AND ([Extent2].[User_Id] = #p__linq__2)))',N'#p__linq__0 int,#p__linq__1 uniqueidentifier,#p__linq__2 uniqueidentifier',#p__linq__0=0,#p__linq__1='E3D4044F-497E-4EEC-890C-021F72826505',#p__linq__2='E3D4044F-497E-4EEC-890C-021F72826505'
If I stop and restart the AppPool in IIS, it's fine for about five minutes and then it happens again.
If I change the LINQ query so it's not pulling in the ConfigFeedItemReceipts, I don't get any timeout.
It only seems to happen when I try to query the child collection.
I've tried using joins instead and EF generates a query with a simple LEFT OUTER JOIN but I still get a timeout.
It's like there is a lock or something or the connections are maxed out.
I tried SET TRANSACTION ISOLATION LEVEL READ UNCOMMITTED; before executing the LINQ query but this didn't make a difference
Any ideas what is causing the SQL timeout?
UPDATE: not all requests cause a timeout, some work some don't even though it's the same query.
I assume that you're using sql server with code first approach. If so, try to change the default command timeout value during initiating the instance of dbcontext as stated below. Your db operations might take longer than the default timeout.
public class YourContext : DbContext
{
public YourContext()
: base("YourConnectionStringName")
{
((IObjectContextAdapter)this).ObjectContext.CommandTimeout = 300;
}
}

SOAP Notification not delivered - "Collection is read-only"

I'm trying to send a WorkItemChanged notification from TFS to my WCF Service. On my development machine everything works perfectly fine, the notification is delivered (and processed by my programm) almost immediatly.
But now as I wanted to test my software on another system with a "freshly" installed TFS 2012, the notifications are not delivered. I looked into it and found the following error:
elapsed time: 00:00:00.2376893, sql calls: 19, sql connect time: 00:00:00, sql execute time: 00:00:00.1560000, non-sql time: 00:00:00.0816893 (34%), cpu time: 00:00:00.0156001 ( 6.6%), avg connect time: 0.00 ms, avg execute time: 8.2 ms. All methods quick. 0 slowest sql calls: prc_ReadGroupMembership(47 ms) set nocount on
declare #NowUtc as datetime; set #NowUtc=getutcdate()
declare #PersonId as int
declare #rebuildOK as int
declare #PersonN(30 ms) CollectionError: CreateEvent != TransformEvents. CollectionError: CreateEvent != ExpandEvents. CollectionError: AfterReadSubscription != SendNotifications.
There were errors or warnings during notification delivery.
0/0 emails delivered.
0/1 soap notifications delivered.
1 errors.
0 warnings.
-------------------------------
Notification not delivered.
Notification: WorkItemChangedEvent (DeliveryType: Soap; Address: http://localhost:8733/NAMEOFMYSERVICEENDPOINT)
Exception: System.NotSupportedException: Collection is read-only.
at System.Collections.ObjectModel.Collection`1.Clear()
at Microsoft.TeamFoundation.Client.Channels.TfsHttpClientBase.HandleReply(TfsClientOperation operation, TfsMessage message, Object[]& outputs)
at Microsoft.TeamFoundation.Client.Channels.TfsHttpClientBase.Invoke(TfsClientOperation operation, Object[] parameters, Object[]& outputs)
at Microsoft.TeamFoundation.Client.Channels.TfsHttpClientBase.Invoke(TfsClientOperation operation, Object[] parameters)
at Microsoft.TeamFoundation.JobService.Extensions.Core.NotificationJobExtension.SendSoapNotification(TeamFoundationRequestContext requestContext, TeamFoundationNotification notification)
I don't really understand what exactly the problem is or where it comes from. What "Collection" is this error referring to? Is it something on my services side or is it related to a wrong configuration or some missing administrative rights on the TFS's side?
Edit
Almost forgot this question ;)
Well apparently it was caused by an error subscribing to the notification via BisSubscribe.exe. After deleting the notification and re-subscribing, the error was gone.