Related
I'm try to configure integration between Business Central on premise 19.6 with Azure AD.
User authentication work fine
But when I try the configuration for OAuth2 service to service follow the instruction
https://learn.microsoft.com/en-us/dynamics365/business-central/dev-itpro/administration/automation-apis-using-s2s-authentication
I cannot connect to service.
I get the token from the
https://login.microsoftonline.com//oauth2/v2.0/token
but when i pass to Business Central api as Berear token I get the error:
"error": {
"code": "Unknown",
"message": "IDX10501: Signature validation failed. Unable to match key: \nkid: 'System.String'.\nExceptions caught:\n 'System.Text.StringBuilder'. \ntoken: 'System.IdentityModel.Tokens.Jwt.JwtSecurityToken'. CorrelationId: <Guid>."
}
On the server event viewer I have the error:
<Event xmlns="http://schemas.microsoft.com/win/2004/08/events/event">
<System>
<Provider Name="Microsoft-DynamicsNAV-Server" Guid="{85423fd1-c021-5a63-f214-c4819f8809f3}" />
<EventID>216</EventID>
<Version>1</Version>
<Level>2</Level>
<Task>13</Task>
<Opcode>0</Opcode>
<Keywords>0x4000f00000000001</Keywords>
<TimeCreated SystemTime="2022-08-29T16:17:45.774819400Z" />
<EventRecordID>437</EventRecordID>
<Correlation />
<Execution ProcessID="4064" ThreadID="5832" />
<Channel>Microsoft-DynamicsNAV-Server/Admin</Channel>
<Computer>The computer FQDN</Computer>
<Security UserID="Business Central Service User Id" />
</System>
- <EventData>
<Data Name="serverInstanceName">BC190</Data>
<Data Name="navTenantId" />
<Data Name="environmentName" />
<Data Name="environmentType" />
<Data Name="message">Type: Microsoft.IdentityModel.Tokens.SecurityTokenSignatureKeyNotFoundException Message: IDX10501: Signature validation failed. Unable to match key: kid: 'System.String'. Exceptions caught: 'System.Text.StringBuilder'. token: 'System.IdentityModel.Tokens.Jwt.JwtSecurityToken'. StackTrace: at System.IdentityModel.Tokens.Jwt.JwtSecurityTokenHandler.ValidateSignature(String token, TokenValidationParameters validationParameters) at System.IdentityModel.Tokens.Jwt.JwtSecurityTokenHandler.ValidateToken(String token, TokenValidationParameters validationParameters, SecurityToken& validatedToken) at Microsoft.Dynamics.Nav.Runtime.NavJwtSecurityTokenFactory.CreateAndValidateWithAudienceList(String serializedToken, FederationMetadataProvider federationMetadataProvider, IEnumerable`1 allowedAudiences, String tokenId, NavDiagnostics diagnostics) at Microsoft.Dynamics.Nav.Service.WebServiceBearerAuthenticator.TryAuthenticateUser(String authorizationHeader, Uri requestUrl) at Microsoft.Dynamics.Nav.Service.ServiceAuthenticationHelper.AuthenticateForServiceCall(Uri uri, String authorizationValue, Func`3 createException, IEnumerable`1 bearerValidationExtensions, String userAadObjectIdToImpersonate) at Microsoft.Dynamics.Nav.Service.OwinAuthenticationHelper.AuthenticateForServiceCall(IOwinRequest request, Func`3 createException, IEnumerable`1 bearerValidationExtensions) at Microsoft.Dynamics.Nav.Service.OData.Extensions.HttpRequestMessageExtensions.Authenticate(HttpRequestMessage request) at System.Lazy`1.CreateValue() at System.Lazy`1.LazyInitValue() at Microsoft.Dynamics.Nav.Service.OData.NavServiceEnvironment.CreateNavService(NavCancellationToken cancellationToken) at Microsoft.Dynamics.Nav.Service.OData.Modeling.NavODataCachedModelBuilder`2.Build(INavServiceEnvironment serviceEnvironment) at Microsoft.Dynamics.Nav.Service.OData.V4.NavODataV4RouteBuilder.GetEdmModelWithLogging(IServiceProvider serviceProvider) at lambda_method(Closure , ServiceProviderEngineScope ) at Microsoft.Extensions.DependencyInjection.ServiceProviderServiceExtensions.GetRequiredService(IServiceProvider provider, Type serviceType) at Microsoft.Extensions.DependencyInjection.ServiceProviderServiceExtensions.GetRequiredService[T](IServiceProvider provider) at Microsoft.AspNet.OData.Routing.DefaultODataPathHandler.Parse(String serviceRoot, String odataPath, IServiceProvider requestContainer, Boolean template) at Microsoft.AspNet.OData.Routing.DefaultODataPathHandler.Parse(String serviceRoot, String odataPath, IServiceProvider requestContainer) at Microsoft.Dynamics.Nav.Service.OData.V4.NavODataV4PathHandler.Parse(String serviceRoot, String odataPath, IServiceProvider requestContainer) at Microsoft.Dynamics.Nav.Service.OData.V4.NavODataV4RouteConstraint.Match(HttpRequestMessage request, IHttpRoute route, String parameterName, IDictionary`2 values, HttpRouteDirection routeDirection) at System.Web.Http.Routing.HttpRoute.ProcessConstraint(HttpRequestMessage request, Object constraint, String parameterName, HttpRouteValueDictionary values, HttpRouteDirection routeDirection) at System.Web.Http.Routing.HttpRoute.ProcessConstraints(HttpRequestMessage request, HttpRouteValueDictionary values, HttpRouteDirection routeDirection) at System.Web.Http.Routing.HttpRoute.GetRouteData(String virtualPathRoot, HttpRequestMessage request) at System.Web.Http.HttpRouteCollection.GetRouteData(HttpRequestMessage request) at System.Web.Http.Dispatcher.HttpRoutingDispatcher.SendAsync(HttpRequestMessage request, CancellationToken cancellationToken) at System.Net.Http.DelegatingHandler.SendAsync(HttpRequestMessage request, CancellationToken cancellationToken) at System.Web.Http.HttpServer.<SendAsync>d__24.MoveNext() Source: System.IdentityModel.Tokens.Jwt HResult: -2146233088 StackTrace: at System.IdentityModel.Tokens.Jwt.JwtSecurityTokenHandler.ValidateSignature(String token, TokenValidationParameters validationParameters) at System.IdentityModel.Tokens.Jwt.JwtSecurityTokenHandler.ValidateToken(String token, TokenValidationParameters validationParameters, SecurityToken& validatedToken) at Microsoft.Dynamics.Nav.Runtime.NavJwtSecurityTokenFactory.CreateAndValidateWithAudienceList(String serializedToken, FederationMetadataProvider federationMetadataProvider, IEnumerable`1 allowedAudiences, String tokenId, NavDiagnostics diagnostics) at Microsoft.Dynamics.Nav.Service.WebServiceBearerAuthenticator.TryAuthenticateUser(String authorizationHeader, Uri requestUrl) at Microsoft.Dynamics.Nav.Service.ServiceAuthenticationHelper.AuthenticateForServiceCall(Uri uri, String authorizationValue, Func`3 createException, IEnumerable`1 bearerValidationExtensions, String userAadObjectIdToImpersonate) at Microsoft.Dynamics.Nav.Service.OwinAuthenticationHelper.AuthenticateForServiceCall(IOwinRequest request, Func`3 createException, IEnumerable`1 bearerValidationExtensions) at Microsoft.Dynamics.Nav.Service.OData.Extensions.HttpRequestMessageExtensions.Authenticate(HttpRequestMessage request) at System.Lazy`1.CreateValue() at System.Lazy`1.LazyInitValue() at Microsoft.Dynamics.Nav.Service.OData.NavServiceEnvironment.CreateNavService(NavCancellationToken cancellationToken) at Microsoft.Dynamics.Nav.Service.OData.Modeling.NavODataCachedModelBuilder`2.Build(INavServiceEnvironment serviceEnvironment) at Microsoft.Dynamics.Nav.Service.OData.V4.NavODataV4RouteBuilder.GetEdmModelWithLogging(IServiceProvider serviceProvider) at lambda_method(Closure , ServiceProviderEngineScope ) at Microsoft.Extensions.DependencyInjection.ServiceProviderServiceExtensions.GetRequiredService(IServiceProvider provider, Type serviceType) at Microsoft.Extensions.DependencyInjection.ServiceProviderServiceExtensions.GetRequiredService[T](IServiceProvider provider) at Microsoft.AspNet.OData.Routing.DefaultODataPathHandler.Parse(String serviceRoot, String odataPath, IServiceProvider requestContainer, Boolean template) at Microsoft.AspNet.OData.Routing.DefaultODataPathHandler.Parse(String serviceRoot, String odataPath, IServiceProvider requestContainer) at Microsoft.Dynamics.Nav.Service.OData.V4.NavODataV4PathHandler.Parse(String serviceRoot, String odataPath, IServiceProvider requestContainer) at Microsoft.Dynamics.Nav.Service.OData.V4.NavODataV4RouteConstraint.Match(HttpRequestMessage request, IHttpRoute route, String parameterName, IDictionary`2 values, HttpRouteDirection routeDirection) at System.Web.Http.Routing.HttpRoute.ProcessConstraint(HttpRequestMessage request, Object constraint, String parameterName, HttpRouteValueDictionary values, HttpRouteDirection routeDirection) at System.Web.Http.Routing.HttpRoute.ProcessConstraints(HttpRequestMessage request, HttpRouteValueDictionary values, HttpRouteDirection routeDirection) at System.Web.Http.Routing.HttpRoute.GetRouteData(String virtualPathRoot, HttpRequestMessage request) at System.Web.Http.HttpRouteCollection.GetRouteData(HttpRequestMessage request) at System.Web.Http.Dispatcher.HttpRoutingDispatcher.SendAsync(HttpRequestMessage request, CancellationToken cancellationToken) at System.Net.Http.DelegatingHandler.SendAsync(HttpRequestMessage request, CancellationToken cancellationToken) at System.Web.Http.HttpServer.<SendAsync>d__24.MoveNext()</Data>
</EventData>
</Event>
Any idea how to solve or investigate the problem ?
Thanks
Lorenzo
Trento - Italy
Had the same error today.
Finally we managed to solve this issue. We are now able to communicate with BC on Prem. It was a configuration error in our app registration. So first you have to check your requests with postman and solve these errors.
In the app registration under "Expose an API" we had to add a scope "default". Also we had to add this scope under "API Permissions". In BC we had to "grant access" under "Azure Active Directory Applications". In your request you have to set the scope to "api://YOURAPPID/"
The solution was to first make it work with postman. If you try it directly from your application you will get errors which will lead you to wrong assumptions.
I am using the below code and every time I run the code, I do see the break point hitting in LogErrorToDatabase method. However sometimes I see the log entry for the ErrorGuid in the database and sometimes I do not see any log entries. The ErrorGuid gets returned to the client side but missing DB entry.
public async Task<ActionResult<IEnumerable<Location>>> Get()
{
try {
Log.Information("Inside Locations Get");
int a = int.Parse("?"); //Uncomment to test error handling
return await Repo.Get<Location>().ToListAsync();
}
catch (Exception ex)
{
//Log error
var id = Guid.NewGuid();
await LogErrorToDatabase(ex, id);
return BadRequest(new ErrorDetail()
{
ErrorGuid = id
});
}
}
public async Task LogErrorToDatabase(Exception ex, Guid id)
{
await Task.Run(() => Log.ForContext("ErrorGuid", id)
.Error(ex, "Error occured with getting the Location List"));
}
I have no clue on this randomness. Any help will be appreciated.
There are several steps you can take troubleshoot why messages are not being written to the Serilog Sink. You can see a number of them on another answer here in SO:
Serilog MSSQL Sink doesn't write logs to database
Update: String or binary data would be truncated is a common SQL Server exception that happens when you're trying to store a value that is larger than the table field can store. For example, if you have an nvarchar(4) field and try to store abcde (5 characters) you'll get the same kind of exception.
You either have to increase the size of the fields in the database you're using to store information, or you have to limit the number of characters you're logging in your C# code.
Thanks Calo. Your response was helpful. I turned the Audit on by switching from WriteTo to AuditTo, set "period": 1 and added Log.CloseAndFlush(); and get the below error logged to my SQL database. Help will be appreciated.
System.AggregateException: Failed to emit a log event. (String or binary data would be truncated.
The statement has been terminated.)
---> System.Data.SqlClient.SqlException (0x80131904): String or binary data would be truncated.
The statement has been terminated.
at System.Data.SqlClient.SqlConnection.OnError(SqlException exception, Boolean breakConnection, Action`1 wrapCloseInAction)
at System.Data.SqlClient.SqlInternalConnection.OnError(SqlException exception, Boolean breakConnection, Action`1 wrapCloseInAction)
at System.Data.SqlClient.TdsParser.ThrowExceptionAndWarning(TdsParserStateObject stateObj, Boolean callerHasConnectionLock, Boolean asyncClose)
at System.Data.SqlClient.TdsParser.TryRun(RunBehavior runBehavior, SqlCommand cmdHandler, SqlDataReader dataStream, BulkCopySimpleResultSet bulkCopyHandler, TdsParserStateObject stateObj, Boolean& dataReady)
at System.Data.SqlClient.SqlCommand.FinishExecuteReader(SqlDataReader ds, RunBehavior runBehavior, String resetOptionsString)
at System.Data.SqlClient.SqlCommand.RunExecuteReaderTds(CommandBehavior cmdBehavior, RunBehavior runBehavior, Boolean returnStream, Boolean async, Int32 timeout, Task& task, Boolean asyncWrite, SqlDataReader ds)
at System.Data.SqlClient.SqlCommand.RunExecuteReader(CommandBehavior cmdBehavior, RunBehavior runBehavior, Boolean returnStream, TaskCompletionSource`1 completion, Int32 timeout, Task& task, Boolean asyncWrite, String method)
at System.Data.SqlClient.SqlCommand.InternalExecuteNonQuery(TaskCompletionSource`1 completion, Boolean sendToPipe, Int32 timeout, Boolean asyncWrite, String methodName)
at System.Data.SqlClient.SqlCommand.ExecuteNonQuery()
at Serilog.Sinks.MSSqlServer.MSSqlServerAuditSink.Emit(LogEvent logEvent)
at Serilog.Core.Sinks.AggregateSink.Emit(LogEvent logEvent)
ClientConnectionId:c0e1f1a4-b655-4be1-b655-c8954f44d299
Error Number:8152,State:2,Class:16
--- End of inner exception stack trace ---
at Serilog.Core.Sinks.AggregateSink.Emit(LogEvent logEvent)
at Serilog.Core.Logger.Dispatch(LogEvent logEvent)
at Serilog.Core.Logger.Serilog.Core.ILogEventSink.Emit(LogEvent logEvent)
at Serilog.Core.Logger.Dispatch(LogEvent logEvent)
at Serilog.Core.Logger.Serilog.Core.ILogEventSink.Emit(LogEvent logEvent)
at Serilog.Core.Logger.Dispatch(LogEvent logEvent)
at Serilog.Core.Logger.Write(LogEventLevel level, Exception exception, String messageTemplate, Object[] propertyValues)
at Serilog.Core.Logger.Write(LogEventLevel level, String messageTemplate, Object[] propertyValues)
at Serilog.Core.Logger.Write[T0,T1,T2](LogEventLevel level, String messageTemplate, T0 propertyValue0, T1 propertyValue1, T2 propertyValue2)
at Serilog.Core.Logger.Error[T0,T1,T2](String messageTemplate, T0 propertyValue0, T1 propertyValue1, T2 propertyValue2)
at MCF.API.ExtensionHelpers.ExceptionMiddleware.InvokeAsync(HttpContext httpContext) in
We are using TransactionScope for the transaction,
IsolationLevel = System.Transactions.IsolationLevel.ReadCommitted
Timeout = 20 min
TransactionScopeOption = TransactionScopeOption.RequiresNew
can not understand this exception
Exception Message of System.Reflection.TargetInvocationException:
System.Reflection.TargetInvocationException: Exception has been thrown
by the target of an invocation. --->
System.Transactions.TransactionException: The operation is not valid
for the state of the transaction. ---> System.TimeoutException:
Transaction Timeout --- End of inner exception stack trace ---
at
System.Transactions.TransactionState.EnlistPromotableSinglePhase(InternalTransaction
tx, IPromotableSinglePhaseNotification
promotableSinglePhaseNotification, Transaction atomicTransaction, Guid
promoterType) at
System.Transactions.Transaction.EnlistPromotableSinglePhase(IPromotableSinglePhaseNotification
promotableSinglePhaseNotification, Guid promoterType) --- End of
inner exception stack trace --- at
System.RuntimeMethodHandle.InvokeMethod(Object target, Object[]
arguments, Signature sig, Boolean constructor) at
System.Reflection.RuntimeMethodInfo.UnsafeInvokeInternal(Object obj,
Object[] parameters, Object[] arguments) at
System.Reflection.RuntimeMethodInfo.Invoke(Object obj, BindingFlags
invokeAttr, Binder binder, Object[] parameters, CultureInfo culture)
at
System.Data.SqlClient.SqlInternalConnection.EnlistNonNull(Transaction
tx) at
System.Data.SqlClient.SqlInternalConnection.Enlist(Transaction tx)
at
System.Data.ProviderBase.DbConnectionInternal.ActivateConnection(Transaction
transaction) at
System.Data.ProviderBase.DbConnectionPool.PrepareConnection(DbConnection
owningObject, DbConnectionInternal obj, Transaction transaction)
at
System.Data.ProviderBase.DbConnectionPool.TryGetConnection(DbConnection
owningObject, UInt32 waitForMultipleObjectsTimeout, Boolean
allowCreate, Boolean onlyOneCheckConnection, DbConnectionOptions
userOptions, DbConnectionInternal& connection) at
System.Data.ProviderBase.DbConnectionPool.TryGetConnection(DbConnection
owningObject, TaskCompletionSource1 retry, DbConnectionOptions
userOptions, DbConnectionInternal& connection) at
System.Data.ProviderBase.DbConnectionFactory.TryGetConnection(DbConnection
owningConnection, TaskCompletionSource1 retry, DbConnectionOptions
userOptions, DbConnectionInternal oldConnection, DbConnectionInternal&
connection) at
System.Data.ProviderBase.DbConnectionInternal.TryOpenConnectionInternal(DbConnection
outerConnection, DbConnectionFactory connectionFactory,
TaskCompletionSource1 retry, DbConnectionOptions userOptions) at
System.Data.SqlClient.SqlConnection.TryOpenInner(TaskCompletionSource1
retry) at
System.Data.SqlClient.SqlConnection.TryOpen(TaskCompletionSource1
retry) at System.Data.SqlClient.SqlConnection.Open() at
Dapper.SqlMapper.ExecuteCommand(IDbConnection cnn, CommandDefinition&
command, Action2 paramReader) at
Dapper.SqlMapper.ExecuteImpl(IDbConnection cnn, CommandDefinition&
command) at Dapper.SqlMapper.Execute(IDbConnection cnn, String
sql, Object param, IDbTransaction transaction, Nullable1
commandTimeout, Nullable1 commandType).
also, get below error
System.Data.SqlClient.SqlException (0x80131904): Execution Timeout Expired. The timeout period elapsed prior to completion of the operation or the server is not responding.
Exception Message of Execution Timeout Expired:
System.Data.SqlClient.SqlException (0x80131904): Execution Timeout
Expired. The timeout period elapsed prior to completion of the
operation or the server is not responding. --->
System.ComponentModel.Win32Exception (0x80004005): The wait operation
timed out at
System.Data.SqlClient.SqlConnection.OnError(SqlException exception,
Boolean breakConnection, Action1 wrapCloseInAction) at
System.Data.SqlClient.TdsParser.ThrowExceptionAndWarning(TdsParserStateObject
stateObj, Boolean callerHasConnectionLock, Boolean asyncClose) at
System.Data.SqlClient.TdsParser.TryRun(RunBehavior runBehavior,
SqlCommand cmdHandler, SqlDataReader dataStream,
BulkCopySimpleResultSet bulkCopyHandler, TdsParserStateObject
stateObj, Boolean& dataReady) at
System.Data.SqlClient.SqlDataReader.TryConsumeMetaData() at
System.Data.SqlClient.SqlDataReader.get_MetaData() at
System.Data.SqlClient.SqlCommand.FinishExecuteReader(SqlDataReader ds,
RunBehavior runBehavior, String resetOptionsString, Boolean
isInternal, Boolean forDescribeParameterEncryption, Boolean
shouldCacheForAlwaysEncrypted) at
System.Data.SqlClient.SqlCommand.RunExecuteReaderTds(CommandBehavior
cmdBehavior, RunBehavior runBehavior, Boolean returnStream, Boolean
async, Int32 timeout, Task& task, Boolean asyncWrite, Boolean inRetry,
SqlDataReader ds, Boolean describeParameterEncryptionRequest) at
System.Data.SqlClient.SqlCommand.RunExecuteReader(CommandBehavior
cmdBehavior, RunBehavior runBehavior, Boolean returnStream, String
method, TaskCompletionSource1 completion, Int32 timeout, Task& task,
Boolean& usedCache, Boolean asyncWrite, Boolean inRetry) at
System.Data.SqlClient.SqlCommand.RunExecuteReader(CommandBehavior
cmdBehavior, RunBehavior runBehavior, Boolean returnStream, String
method) at
System.Data.SqlClient.SqlCommand.ExecuteReader(CommandBehavior
behavior, String method) at
Dapper.SqlMapper.ExecuteReaderWithFlagsFallback(IDbCommand cmd,
Boolean wasClosed, CommandBehavior behavior) at
Dapper.SqlMapper.d__1381.MoveNext() at
System.Collections.Generic.List1..ctor(IEnumerable1 collection)
at System.Linq.Enumerable.ToList[TSource](IEnumerable1 source) at
Dapper.SqlMapper.Query[T](IDbConnection cnn, String sql, Object param,
IDbTransaction transaction, Boolean buffered, Nullable1
commandTimeout, Nullable1 commandType)
I am getting an exception when I access my DB via Azure mobile services. The error appears below my question. I haven't found any way to change the timeout for mobile services, and the query is running against my localhost. I reindexed everything in my table and am still getting this error.
This error only appears on my largest table (~6.6 million records). I'm hoping it isn't size related, but I would love any suggestions.
{
"message": "An error has occurred.",
"exceptionMessage": "Exception has been thrown by the target of an invocation.",
"exceptionType": "System.Reflection.TargetInvocationException",
"stackTrace": " at System.RuntimeMethodHandle.InvokeMethod(Object target, Object[] arguments, Signature sig, Boolean constructor)\r\n at System.Reflection.RuntimeMethodInfo.UnsafeInvokeInternal(Object obj, Object[] parameters, Object[] arguments)\r\n at System.Reflection.RuntimeMethodInfo.Invoke(Object obj, BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture)\r\n at System.Reflection.MethodBase.Invoke(Object obj, Object[] parameters)\r\n at System.Web.Http.OData.Query.ODataQueryOptions.LimitResults(IQueryable queryable, Int32 limit, Boolean& resultsLimited)\r\n at System.Web.Http.OData.Query.ODataQueryOptions.ApplyTo(IQueryable query, ODataQuerySettings querySettings)\r\n at System.Web.Http.OData.EnableQueryAttribute.ApplyQuery(IQueryable queryable, ODataQueryOptions queryOptions)\r\n at System.Web.Http.OData.EnableQueryAttribute.ExecuteQuery(Object response, HttpRequestMessage request, HttpActionDescriptor actionDescriptor)\r\n at System.Web.Http.OData.EnableQueryAttribute.OnActionExecuted(HttpActionExecutedContext actionExecutedContext)\r\n at System.Web.Http.Filters.ActionFilterAttribute.OnActionExecutedAsync(HttpActionExecutedContext actionExecutedContext, CancellationToken cancellationToken)\r\n--- End of stack trace from previous location where exception was thrown ---\r\n at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)\r\n at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)\r\n at System.Runtime.CompilerServices.TaskAwaiter.GetResult()\r\n at System.Web.Http.Filters.ActionFilterAttribute.<CallOnActionExecutedAsync>d__5.MoveNext()\r\n--- End of stack trace from previous location where exception was thrown ---\r\n at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)\r\n at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)\r\n at System.Runtime.CompilerServices.TaskAwaiter`1.GetResult()\r\n at System.Web.Http.Filters.ActionFilterAttribute.<ExecuteActionFilterAsyncCore>d__0.MoveNext()\r\n--- End of stack trace from previous location where exception was thrown ---\r\n at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)\r\n at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)\r\n at System.Runtime.CompilerServices.TaskAwaiter`1.GetResult()\r\n at System.Web.Http.Filters.ActionFilterAttribute.<CallOnActionExecutedAsync>d__5.MoveNext()\r\n--- End of stack trace from previous location where exception was thrown ---\r\n at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()\r\n at System.Web.Http.Filters.ActionFilterAttribute.<CallOnActionExecutedAsync>d__5.MoveNext()\r\n--- End of stack trace from previous location where exception was thrown ---\r\n at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)\r\n at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)\r\n at System.Runtime.CompilerServices.TaskAwaiter`1.GetResult()\r\n at System.Web.Http.Filters.ActionFilterAttribute.<ExecuteActionFilterAsyncCore>d__0.MoveNext()\r\n--- End of stack trace from previous location where exception was thrown ---\r\n at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)\r\n at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)\r\n at System.Runtime.CompilerServices.TaskAwaiter`1.GetResult()\r\n at System.Web.Http.Controllers.ActionFilterResult.<ExecuteAsync>d__2.MoveNext()\r\n--- End of stack trace from previous location where exception was thrown ---\r\n at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)\r\n at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)\r\n at System.Runtime.CompilerServices.TaskAwaiter`1.GetResult()\r\n at System.Web.Http.Filters.AuthorizationFilterAttribute.<ExecuteAuthorizationFilterAsyncCore>d__2.MoveNext()\r\n--- End of stack trace from previous location where exception was thrown ---\r\n at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)\r\n at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)\r\n at System.Runtime.CompilerServices.TaskAwaiter`1.GetResult()\r\n at System.Web.Http.Controllers.AuthenticationFilterResult.<ExecuteAsync>d__0.MoveNext()\r\n--- End of stack trace from previous location where exception was thrown ---\r\n at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)\r\n at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)\r\n at System.Runtime.CompilerServices.TaskAwaiter`1.GetResult()\r\n at System.Web.Http.Controllers.ExceptionFilterResult.<ExecuteAsync>d__0.MoveNext()\r\n--- End of stack trace from previous location where exception was thrown ---\r\n at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()\r\n at System.Web.Http.Controllers.ExceptionFilterResult.<ExecuteAsync>d__0.MoveNext()\r\n--- End of stack trace from previous location where exception was thrown ---\r\n at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)\r\n at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)\r\n at System.Runtime.CompilerServices.TaskAwaiter`1.GetResult()\r\n at System.Web.Http.Dispatcher.HttpControllerDispatcher.<SendAsync>d__1.MoveNext()",
"innerException": {
"message": "An error has occurred.",
"exceptionMessage": "An error occurred while executing the command definition. See the inner exception for details.",
"exceptionType": "System.Data.Entity.Core.EntityCommandExecutionException",
"stackTrace": " at System.Data.Entity.Core.EntityClient.Internal.EntityCommandDefinition.ExecuteStoreCommands(EntityCommand entityCommand, CommandBehavior behavior)\r\n at System.Data.Entity.Core.Objects.Internal.ObjectQueryExecutionPlan.Execute[TResultType](ObjectContext context, ObjectParameterCollection parameterValues)\r\n at System.Data.Entity.Core.Objects.ObjectQuery`1.<>c__DisplayClass7.<GetResults>b__6()\r\n at System.Data.Entity.Core.Objects.ObjectContext.ExecuteInTransaction[T](Func`1 func, IDbExecutionStrategy executionStrategy, Boolean startLocalTransaction, Boolean releaseConnectionOnSuccess)\r\n at System.Data.Entity.Core.Objects.ObjectQuery`1.<>c__DisplayClass7.<GetResults>b__5()\r\n at System.Data.Entity.SqlServer.DefaultSqlExecutionStrategy.Execute[TResult](Func`1 operation)\r\n at System.Data.Entity.Core.Objects.ObjectQuery`1.GetResults(Nullable`1 forMergeOption)\r\n at System.Data.Entity.Core.Objects.ObjectQuery`1.<System.Collections.Generic.IEnumerable<T>.GetEnumerator>b__0()\r\n at System.Data.Entity.Internal.LazyEnumerator`1.MoveNext()\r\n at System.Collections.Generic.List`1..ctor(IEnumerable`1 collection)\r\n at System.Web.Http.OData.Query.TruncatedCollection`1..ctor(IQueryable`1 source, Int32 pageSize)\r\n at System.Web.Http.OData.Query.ODataQueryOptions.LimitResults[T](IQueryable`1 queryable, Int32 limit, Boolean& resultsLimited)",
"innerException": {
"message": "An error has occurred.",
"exceptionMessage": "Timeout expired. The timeout period elapsed prior to completion of the operation or the server is not responding.",
"exceptionType": "System.Data.SqlClient.SqlException",
"stackTrace": " at System.Data.SqlClient.SqlConnection.OnError(SqlException exception, Boolean breakConnection, Action`1 wrapCloseInAction)\r\n at System.Data.SqlClient.SqlInternalConnection.OnError(SqlException exception, Boolean breakConnection, Action`1 wrapCloseInAction)\r\n at System.Data.SqlClient.TdsParser.ThrowExceptionAndWarning(TdsParserStateObject stateObj, Boolean callerHasConnectionLock, Boolean asyncClose)\r\n at System.Data.SqlClient.TdsParser.TryRun(RunBehavior runBehavior, SqlCommand cmdHandler, SqlDataReader dataStream, BulkCopySimpleResultSet bulkCopyHandler, TdsParserStateObject stateObj, Boolean& dataReady)\r\n at System.Data.SqlClient.SqlDataReader.TrySetMetaData(_SqlMetaDataSet metaData, Boolean moreInfo)\r\n at System.Data.SqlClient.TdsParser.TryRun(RunBehavior runBehavior, SqlCommand cmdHandler, SqlDataReader dataStream, BulkCopySimpleResultSet bulkCopyHandler, TdsParserStateObject stateObj, Boolean& dataReady)\r\n at System.Data.SqlClient.SqlDataReader.TryConsumeMetaData()\r\n at System.Data.SqlClient.SqlDataReader.get_MetaData()\r\n at System.Data.SqlClient.SqlCommand.FinishExecuteReader(SqlDataReader ds, RunBehavior runBehavior, String resetOptionsString)\r\n at System.Data.SqlClient.SqlCommand.RunExecuteReaderTds(CommandBehavior cmdBehavior, RunBehavior runBehavior, Boolean returnStream, Boolean async, Int32 timeout, Task& task, Boolean asyncWrite, SqlDataReader ds)\r\n at System.Data.SqlClient.SqlCommand.RunExecuteReader(CommandBehavior cmdBehavior, RunBehavior runBehavior, Boolean returnStream, String method, TaskCompletionSource`1 completion, Int32 timeout, Task& task, Boolean asyncWrite)\r\n at System.Data.SqlClient.SqlCommand.RunExecuteReader(CommandBehavior cmdBehavior, RunBehavior runBehavior, Boolean returnStream, String method)\r\n at System.Data.SqlClient.SqlCommand.ExecuteReader(CommandBehavior behavior, String method)\r\n at System.Data.SqlClient.SqlCommand.ExecuteDbDataReader(CommandBehavior behavior)\r\n at System.Data.Common.DbCommand.ExecuteReader(CommandBehavior behavior)\r\n at System.Data.Entity.Infrastructure.Interception.DbCommandDispatcher.<Reader>b__c(DbCommand t, DbCommandInterceptionContext`1 c)\r\n at System.Data.Entity.Infrastructure.Interception.InternalDispatcher`1.Dispatch[TTarget,TInterceptionContext,TResult](TTarget target, Func`3 operation, TInterceptionContext interceptionContext, Action`3 executing, Action`3 executed)\r\n at System.Data.Entity.Infrastructure.Interception.DbCommandDispatcher.Reader(DbCommand command, DbCommandInterceptionContext interceptionContext)\r\n at System.Data.Entity.Internal.InterceptableDbCommand.ExecuteDbDataReader(CommandBehavior behavior)\r\n at System.Data.Common.DbCommand.ExecuteReader(CommandBehavior behavior)\r\n at System.Data.Entity.Core.EntityClient.Internal.EntityCommandDefinition.ExecuteStoreCommands(EntityCommand entityCommand, CommandBehavior behavior)",
"innerException": {
"message": "An error has occurred.",
"exceptionMessage": "The wait operation timed out",
"exceptionType": "System.ComponentModel.Win32Exception",
"stackTrace": null
}
}
}
}
Azure Mobile Services is based on Entity Framework, which means you can enable SQL logging in your backend. Check out the following blog post: http://blog.oneunicorn.com/2013/05/08/ef6-sql-logging-part-1-simple-logging/
A good method is to send the log to stdout / the console, then go to the Logs section - they should appear there.
I have written an application in code-first approach (ASP.NET MVC), and now I am trying to deploy my application on a server (Windows Server 2012). When I test it in Visual Studio 2013 for WEB everything goes fine. After the implementation, when I access website for web, i cannot for example add next user because:
Failed to update database "MyDatabase" because the database is read-only.
I checked the instances in LocalDB folder, and they are really read-only. The change of it in properties menu doesn't work.
This is stack tree:
[SqlException (0x80131904): Failed to update database "MyDatabase" because the database is read-only.]
System.Data.SqlClient.SqlConnection.OnError(SqlException exception, Boolean breakConnection, Action1 wrapCloseInAction) +388
System.Data.SqlClient.TdsParser.ThrowExceptionAndWarning(TdsParserStateObject stateObj, Boolean callerHasConnectionLock, Boolean asyncClose) +815
System.Data.SqlClient.TdsParser.TryRun(RunBehavior runBehavior, SqlCommand cmdHandler, SqlDataReader dataStream, BulkCopySimpleResultSet bulkCopyHandler, TdsParserStateObject stateObj, Boolean& dataReady) +4515
System.Data.SqlClient.SqlCommand.FinishExecuteReader(SqlDataReader ds, RunBehavior runBehavior, String resetOptionsString) +6553853
System.Data.SqlClient.SqlCommand.RunExecuteReaderTds(CommandBehavior cmdBehavior, RunBehavior runBehavior, Boolean returnStream, Boolean async, Int32 timeout, Task& task, Boolean asyncWrite, SqlDataReader ds) +6556619
System.Data.SqlClient.SqlCommand.RunExecuteReader(CommandBehavior cmdBehavior, RunBehavior runBehavior, Boolean returnStream, String method, TaskCompletionSource1 completion, Int32 timeout, Task& task, Boolean asyncWrite) +586
System.Data.SqlClient.SqlCommand.InternalExecuteNonQuery(TaskCompletionSource1 completion, String methodName, Boolean sendToPipe, Int32 timeout, Boolean asyncWrite) +742
System.Data.SqlClient.SqlCommand.ExecuteNonQuery() +287
WebMatrix.Data.Database.Execute(String commandText, Object[] args) +178
WebMatrix.WebData.SimpleMembershipProvider.CheckPassword(IDatabase db, Int32 userId, String password) +455
WebMatrix.WebData.SimpleMembershipProvider.ValidateUser(String username, String password) +238
WebMatrix.WebData.WebSecurity.Login(String userName, String password, Boolean persistCookie) +73
MvcApplication4.Controllers.AccountController.Login(LoginModel model, String returnUrl) +132
lambda_method(Closure , ControllerBase , Object[] ) +179
System.Web.Mvc.ReflectedActionDescriptor.Execute(ControllerContext controllerContext, IDictionary2 parameters) +258
System.Web.Mvc.ControllerActionInvoker.InvokeActionMethod(ControllerContext controllerContext, ActionDescriptor actionDescriptor, IDictionary`2 parameters) +39
System.Web.Mvc.Async.<>c__DisplayClass42.b__41() +34
System.Web.Mvc.Async.<>c__DisplayClass39.b__33() +124
System.Web.Mvc.Async.<>c__DisplayClass4f.b__49() +786611
System.Web.Mvc.Async.<>c__DisplayClass4f.b__49() +786611
System.Web.Mvc.Async.<>c__DisplayClass37.b__36(IAsyncResult asyncResult) +15
System.Web.Mvc.Async.<>c__DisplayClass2a.b__20() +33
System.Web.Mvc.Async.<>c__DisplayClass25.b__22(IAsyncResult asyncResult) +787092
System.Web.Mvc.<>c__DisplayClass1d.b__18(IAsyncResult asyncResult) +28
System.Web.Mvc.Async.<>c__DisplayClass4.b__3(IAsyncResult ar) +15
System.Web.Mvc.Controller.EndExecuteCore(IAsyncResult asyncResult) +65
System.Web.Mvc.Async.<>c__DisplayClass4.b__3(IAsyncResult ar) +15
System.Web.Mvc.Controller.EndExecute(IAsyncResult asyncResult) +51
System.Web.Mvc.<>c__DisplayClass8.b__3(IAsyncResult asyncResult) +42
System.Web.Mvc.Async.<>c__DisplayClass4.b__3(IAsyncResult ar) +15
System.Web.Mvc.MvcHandler.EndProcessRequest(IAsyncResult asyncResult) +51
System.Web.CallHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute() +606
System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously) +288
Since this is a SQLExpress DB, take a look at this answer. It looks to be the same issue you are having.
Failed to update .mdf database because the database is read-only (Windows application)
Update
For the .mdf and .idf files, give write and modify access to NETWORK SERVICE user, ASPNET user, and IIS_IUSRS group.
I Changed the permissions of the entire folder where the website was hosted. I added all permissions for Users to be broad and it worked. Try this first to be sure and then narrow it down to specific users.
A restart of the IIS was not required.