2sxc general exception errors in admin log - dotnetnuke

We are encountering lot of "General Exception" errors related to DNN search and 2sxc, sometimes the site even stops loading.
I'm attaching one of the errors from the admin log, but there are plenty can anyone help?
We're using Evoq 8.5, 2sxc 8.5.4.
<log LogGUID="e8a0d5ca-12f6-4865-a184-f440611ad3d5" LogFileID="" LogTypeKey="GENERAL_EXCEPTION" LogUserID="-1" LogEventID="212842" LogUserName="" LogPortalID="-1" LogPortalName="" LogCreateDate="3/5/2017 2:02:57 AM" LogCreateDateNum="0" BypassBuffering="False" LogServerName="RD0003FF6E964E" LogConfigID="4">
<LogProperties>
<LogProperty>
<PropertyName>AbsoluteURL</PropertyName>
<PropertyValue />
</LogProperty>
<LogProperty>
<PropertyName>DefaultDataProvider</PropertyName>
<PropertyValue>DotNetNuke.Data.SqlDataProvider, DotNetNuke</PropertyValue>
</LogProperty>
<LogProperty>
<PropertyName>ExceptionGUID</PropertyName>
<PropertyValue>d5db1b63-65bb-424e-9284-d6bdeb597078</PropertyValue>
</LogProperty>
</LogProperties>
<Exception>
<AssemblyVersion />
<PortalId>-1</PortalId>
<UserId>-1</UserId>
<TabId>-1</TabId>
<RawUrl />
<Referrer />
<UserAgent />
<ExceptionHash>h7DfzrR5N2NZPGujVU3A9A==</ExceptionHash>
<Message>Search: Error while indexing module 3429 on tab 1311, portal 14</Message>
<StackTrace> at ToSic.SexyContent.Environment.Dnn7.DnnBusinessController.GetModifiedSearchDocuments(ModuleInfo moduleInfo, DateTime beginDate) in C:\Projects\2SexyContent\Web\DesktopModules\ToSIC_SexyContent\Environment\Dnn7\DnnBusinessController.cs:line 32
at DotNetNuke.Services.Search.ModuleIndexer.IndexSearchDocuments(Int32 portalId, ScheduleHistoryItem schedule, DateTime startDateLocal, Action`1 indexer)</StackTrace>
<InnerMessage>The underlying provider failed on Open.</InnerMessage>
<InnerStackTrace> at System.Data.EntityClient.EntityConnection.OpenStoreConnectionIf(Boolean openCondition, DbConnection storeConnectionToOpen, DbConnection originalConnection, String exceptionCode, String attemptedOperation, Boolean& closeStoreConnectionOnFailure)
at System.Data.EntityClient.EntityConnection.Open()
at System.Data.Objects.ObjectContext.EnsureConnection()
at System.Data.Objects.ObjectQuery`1.GetResults(Nullable`1 forMergeOption)
at System.Data.Objects.ObjectQuery`1.System.Collections.Generic.IEnumerable<T>.GetEnumerator()
at System.Linq.Enumerable.FirstOrDefault[TSource](IEnumerable`1 source)
at ToSic.Eav.BLL.EavDataController.InitZoneApp(Nullable`1 zoneId, Nullable`1 appId) in C:\Projects\eav-server\ToSic.Eav\BLL\EavDataController.cs:line 145
at ToSic.SexyContent.Internal.AppManagement.EnsureAppIsConfigured(Int32 zoneId, Int32 appId, String appName) in C:\Projects\2SexyContent\Web\DesktopModules\ToSIC_SexyContent\SexyContent\Internal\AppManagement.cs:line 106
at ToSic.SexyContent.App.InitializeResourcesSettingsAndMetadata(Boolean allowSideEffects) in C:\Projects\2SexyContent\Web\DesktopModules\ToSIC_SexyContent\SexyContent\App.cs:line 110
at ToSic.SexyContent.App..ctor(Int32 zoneId, Int32 appId, PortalSettings ownerPortalSettings, Boolean allowSideEffects) in C:\Projects\2SexyContent\Web\DesktopModules\ToSIC_SexyContent\SexyContent\App.cs:line 103
at ToSic.SexyContent.ContentBlock.ModuleContentBlock..ctor(ModuleInfo moduleInfo, IEnumerable`1 overrideParams) in C:\Projects\2SexyContent\Web\DesktopModules\ToSIC_SexyContent\SexyContent\ContentBlock\ModuleContentBlock.cs:line 55
at ToSic.SexyContent.Search.SearchController.GetModifiedSearchDocuments(ModuleInfo moduleInfo, DateTime beginDate) in C:\Projects\2SexyContent\Web\DesktopModules\ToSIC_SexyContent\SexyContent\Search\SearchController.cs:line 48
at ToSic.SexyContent.Environment.Dnn7.DnnBusinessController.GetModifiedSearchDocuments(ModuleInfo moduleInfo, DateTime beginDate) in C:\Projects\2SexyContent\Web\DesktopModules\ToSIC_SexyContent\Environment\Dnn7\DnnBusinessController.cs:line 28</InnerStackTrace>
<Source>ToSic.SexyContent</Source>
<FileName />
<FileLineNumber>0</FileLineNumber>
<FileColumnNumber>0</FileColumnNumber>
<Method />
</Exception>
</log>

This sounds like a DB error which probably has nothing to do with 2sxc. I recommend to do some DB maintenance and see if it solves everything.
So it's no known issue ATM

Denis updated 2sxc and I've investigated the log files and found this error that might help narrow it down:
2017-11-14 12:35:46,608 [H10][Thread:76][ERROR] DotNetNuke.Services.Exceptions.Exceptions - System.Exception: [Indexing: Behavior SiteSearch (#1)] Error reading content source DNN Modules Indexer ---> ToSic.SexyContent.Search.SearchIndexException: Search: Error while indexing module 5242 on tab 1901, portal 0 ---> System.Collections.Generic.KeyNotFoundException: The given key was not present in the dictionary.
at System.ThrowHelper.ThrowKeyNotFoundException()
at System.Collections.Generic.Dictionary2.get_Item(TKey key)
at ASP._Page_Portals_0_2sxc_Documents__Environment_Filter_App_cshtml.CustomizeData() in \Portals\0\2sxc\Documents\_Environment Filter App.cshtml:line 11
at ToSic.SexyContent.Engines.RazorEngine.CustomizeData() in C:\Projects\2SexyContent\Web\DesktopModules\ToSIC_SexyContent\2Sexy Content Razor\RazorEngine.cs:line 109
at ToSic.SexyContent.Engines.EngineBase.Init(Template template, App app, ModuleInfo hostingModule, IDataSource dataSource, InstancePurposes instancePurposes, SxcInstance sxcInstance, Log parentLog) in C:\Projects\2SexyContent\Web\DesktopModules\ToSIC_SexyContent\SexyContent\Engines\EngineBase.cs:line 64
at ToSic.SexyContent.Search.SearchController.GetModifiedSearchDocuments(ModuleInfo moduleInfo, DateTime beginDate) in C:\Projects\2SexyContent\Web\DesktopModules\ToSIC_SexyContent\SexyContent\Search\SearchController.cs:line 143
at ToSic.SexyContent.Environment.Dnn7.DnnBusinessController.GetModifiedSearchDocuments(ModuleInfo moduleInfo, DateTime beginDate) in C:\Projects\2SexyContent\Web\DesktopModules\ToSIC_SexyContent\Environment\Dnn7\DnnBusinessController.cs:line 85
--- End of inner exception stack trace ---
at ToSic.SexyContent.Environment.Dnn7.DnnBusinessController.GetModifiedSearchDocuments(ModuleInfo moduleInfo, DateTime beginDate) in C:\Projects\2SexyContent\Web\DesktopModules\ToSIC_SexyContent\Environment\Dnn7\DnnBusinessController.cs:line 89
at DnnSharp.Common2.Services.Dnn.ModuleService.<GetSearchItems>d__4.MoveNext()
at DnnSharp.SearchBoost.Core.ContentSource.DnnModules.<GetIndexingJobsForTabModules>d__26.MoveNext()
at DnnSharp.SearchBoost.Core.ContentSource.DnnModules.<GetIndexingJobs>d__25.MoveNext()
at DnnSharp.SearchBoost.Core.ContentSource.DnnModules.<Query>d__20.MoveNext()
at DnnSharp.SearchBoost.Core.Services.QueryContentSourcesService.QueryAllContentSourcesToCache(SearchBehavior behavior, List1 cache, CancellationTokenSource cancellationToken)
--- End of inner exception stack trace ---

Related

Business Central : Oauth2 authentication

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.

ERROR NHibernate.Util.ADOExceptionReporter The requested operation cannot be completed because the connection has been broken

I have an ASP.NET MVC app featuring nHibernate as ORM (using SQL Server as database).
Every 5-6 requests, an exception is thrown containing random error described with the title above.
This is only happening on GET requests and starts with:
ERROR While preparing SELECT ..
These issues started ever since I've upgraded NHibernate 4.x to NHibernate 5.0.3 (5.1.1 now). During this process I've also updated the target framework, used to be .NET 4.5.2 now is .NET 4.7.2.
I've checked literally everything, made sure there aren't any connection leaks or timeouts against the DB but the error still persists. Tried switching the "TransparentNetworkIPResolution" and "Enlist" features off from the connection string - the problem is still here.
Any idea regarding the solution of the problem would be more than welcome.
This is the line that is the culprit for the exception below (DepartmentService:838):
var department = _departmentRepository.Get(departmentId);
The scenario is the following, I have multiple grids thus multiple requests are fired towards the same action. Every 5th-6th refresh of the same page, one of the many requests would fail (the one request that fails is random, i.e. sometimes it's the 1st, sometimes the 2nd, and so on).
Here is full exception snippet from my logs:
2020-06-26 13:25:16,297 [50] ERROR NHibernate.Util.ADOExceptionReporter [(null)] - While preparing SELECT department0_.DepartmentId as departmentid1_22_0_, department0_.CreatedAt as createdat4_22_0_, department0_.ModifiedAt as modifiedat5_22_0_, department0_.Name as name2_22_0_, department0_.Status as status6_22_0_, department0_.CreatedBy as createdby7_22_0_, department0_.ModifiedBy as modifiedby8_22_0_, department0_.SiteId as siteid3_22_0_ FROM dbo.Departments department0_ WHERE department0_.DepartmentId=#p0 an error occurred
2020-06-26 13:25:16,298 [50] ERROR NHibernate.Util.ADOExceptionReporter [(null)] - The requested operation cannot be completed because the connection has been broken.
2020-06-26 13:25:16,300 [50] ERROR [(null)] - NHibernate.ADOException: While preparing SELECT department0_.DepartmentId as departmentid1_22_0_, department0_.CreatedAt as createdat4_22_0_, department0_.ModifiedAt as modifiedat5_22_0_, department0_.Name as name2_22_0_, department0_.Status as status6_22_0_, department0_.CreatedBy as createdby7_22_0_, department0_.ModifiedBy as modifiedby8_22_0_, department0_.SiteId as siteid3_22_0_ FROM dbo.Departments department0_ WHERE department0_.DepartmentId=#p0 an error occurred ---> System.InvalidOperationException: The requested operation cannot be completed because the connection has been broken.
at System.Data.SqlClient.SqlInternalConnectionTds.ExecuteTransaction(TransactionRequest transactionRequest, String name, IsolationLevel iso, SqlInternalTransaction internalTransaction, Boolean isDelegateControlRequest)
at System.Data.SqlClient.SqlDelegatedTransaction.Initialize()
at System.Transactions.TransactionStatePSPEOperation.PSPEInitialize(InternalTransaction tx, IPromotableSinglePhaseNotification promotableSinglePhaseNotification, Guid promoterType)
at System.Transactions.TransactionStateActive.EnlistPromotableSinglePhase(InternalTransaction tx, IPromotableSinglePhaseNotification promotableSinglePhaseNotification, Transaction atomicTransaction, Guid promoterType)
at System.Transactions.Transaction.EnlistPromotableSinglePhase(IPromotableSinglePhaseNotification promotableSinglePhaseNotification, Guid promoterType)
at System.Transactions.Transaction.EnlistPromotableSinglePhase(IPromotableSinglePhaseNotification promotableSinglePhaseNotification)
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(TaskCompletionSource`1 retry)
at System.Data.SqlClient.SqlConnection.Open()
at NHibernate.Connection.DriverConnectionProvider.GetConnection()
at NHibernate.AdoNet.ConnectionManager.GetConnection()
at NHibernate.AdoNet.AbstractBatcher.Prepare(DbCommand cmd)
--- End of inner exception stack trace ---
at NHibernate.AdoNet.AbstractBatcher.Prepare(DbCommand cmd)
at NHibernate.AdoNet.AbstractBatcher.ExecuteReader(DbCommand cmd)
at NHibernate.Loader.Loader.GetResultSet(DbCommand st, QueryParameters queryParameters, ISessionImplementor session, IResultTransformer forcedResultTransformer)
at NHibernate.Loader.Loader.DoQuery(ISessionImplementor session, QueryParameters queryParameters, Boolean returnProxies, IResultTransformer forcedResultTransformer)
at NHibernate.Loader.Loader.DoQueryAndInitializeNonLazyCollections(ISessionImplementor session, QueryParameters queryParameters, Boolean returnProxies, IResultTransformer forcedResultTransformer)
at NHibernate.Loader.Loader.LoadEntity(ISessionImplementor session, Object id, IType identifierType, Object optionalObject, String optionalEntityName, Object optionalIdentifier, IEntityPersister persister)
at NHibernate.Loader.Entity.AbstractEntityLoader.Load(ISessionImplementor session, Object id, Object optionalObject, Object optionalId)
at NHibernate.Loader.Entity.AbstractEntityLoader.Load(Object id, Object optionalObject, ISessionImplementor session)
at NHibernate.Persister.Entity.AbstractEntityPersister.Load(Object id, Object optionalObject, LockMode lockMode, ISessionImplementor session)
at NHibernate.Event.Default.DefaultLoadEventListener.LoadFromDatasource(LoadEvent event, IEntityPersister persister, EntityKey keyToLoad, LoadType options)
at NHibernate.Event.Default.DefaultLoadEventListener.DoLoad(LoadEvent event, IEntityPersister persister, EntityKey keyToLoad, LoadType options)
at NHibernate.Event.Default.DefaultLoadEventListener.Load(LoadEvent event, IEntityPersister persister, EntityKey keyToLoad, LoadType options)
at NHibernate.Event.Default.DefaultLoadEventListener.ProxyOrLoad(LoadEvent event, IEntityPersister persister, EntityKey keyToLoad, LoadType options)
at NHibernate.Event.Default.DefaultLoadEventListener.OnLoad(LoadEvent event, LoadType loadType)
at NHibernate.Impl.SessionImpl.FireLoad(LoadEvent event, LoadType loadType)
at NHibernate.Impl.SessionImpl.Get(String entityName, Object id)
at NHibernate.Impl.SessionImpl.Get[T](Object id)
at Codera.Data.NHibernate.NHRepository1.Get(Object id) at Castle.Proxies.Invocations.NHRepository1_Get_10.InvokeMethodOnTarget()
at Castle.DynamicProxy.AbstractInvocation.Proceed()
at ISOQuest.Data.NHibernate.Interceptors.MethodInterceptor.Intercept(IInvocation invocation) in C:\Projects\ISOQuestGen6\ISOQuest.Data.NHibernate\Interceptors\MethodInterceptor.cs:line 49
at Castle.DynamicProxy.AbstractInvocation.Proceed()
at Castle.Proxies.DepartmentRepositoryProxy.Get(Object id)
at ISOQuest.Business.Services.DepartmentService.GetDepartmentAdministrators(Guid departmentId, Int32 type) in C:\Projects\ISOQuestGen6\Modules\ISOQuest\ISOQuest.Business\Services\Department\DepartmentService.cs:line 838
at ISOQuest.Web.Controllers.Api.DepartmentsController.LoadDepartmentAdministrators(Guid departmentId, Int32 type) in C:\Projects\ISOQuestGen6\Modules\ISOQuest\ISOQuest.Web\Controllers\Api\DepartmentsController.cs:line 454
at lambda_method(Closure , ControllerBase , Object[] )
at System.Web.Mvc.ReflectedActionDescriptor.Execute(ControllerContext controllerContext, IDictionary2 parameters) at System.Web.Mvc.ControllerActionInvoker.InvokeActionMethod(ControllerContext controllerContext, ActionDescriptor actionDescriptor, IDictionary2 parameters)
at System.Web.Mvc.Async.AsyncControllerActionInvoker.b__39(IAsyncResult asyncResult, ActionInvocation innerInvokeState)
at System.Web.Mvc.Async.AsyncResultWrapper.WrappedAsyncResult2.CallEndDelegate(IAsyncResult asyncResult) at System.Web.Mvc.Async.AsyncControllerActionInvoker.EndInvokeActionMethod(IAsyncResult asyncResult) at System.Web.Mvc.Async.AsyncControllerActionInvoker.AsyncInvocationWithFilters.<InvokeActionMethodFilterAsynchronouslyRecursive>b__3d() at System.Web.Mvc.Async.AsyncControllerActionInvoker.AsyncInvocationWithFilters.<>c__DisplayClass46.<InvokeActionMethodFilterAsynchronouslyRecursive>b__3f() at System.Web.Mvc.Async.AsyncControllerActionInvoker.AsyncInvocationWithFilters.<>c__DisplayClass46.<InvokeActionMethodFilterAsynchronouslyRecursive>b__3f() at System.Web.Mvc.Async.AsyncControllerActionInvoker.EndInvokeActionMethodWithFilters(IAsyncResult asyncResult) at System.Web.Mvc.Async.AsyncControllerActionInvoker.<>c__DisplayClass21.<>c__DisplayClass2b.<BeginInvokeAction>b__1c() at System.Web.Mvc.Async.AsyncControllerActionInvoker.<>c__DisplayClass21.<BeginInvokeAction>b__1e(IAsyncResult asyncResult) at System.Web.Mvc.Async.AsyncControllerActionInvoker.EndInvokeAction(IAsyncResult asyncResult) at System.Web.Mvc.Controller.<BeginExecuteCore>b__1d(IAsyncResult asyncResult, ExecuteCoreState innerState) at System.Web.Mvc.Async.AsyncResultWrapper.WrappedAsyncVoid1.CallEndDelegate(IAsyncResult asyncResult)
at System.Web.Mvc.Controller.EndExecuteCore(IAsyncResult asyncResult)
at System.Web.Mvc.Async.AsyncResultWrapper.WrappedAsyncVoid1.CallEndDelegate(IAsyncResult asyncResult) at System.Web.Mvc.Controller.EndExecute(IAsyncResult asyncResult) at System.Web.Mvc.MvcHandler.<BeginProcessRequest>b__5(IAsyncResult asyncResult, ProcessRequestState innerState) at System.Web.Mvc.Async.AsyncResultWrapper.WrappedAsyncVoid1.CallEndDelegate(IAsyncResult asyncResult)
at System.Web.Mvc.MvcHandler.EndProcessRequest(IAsyncResult asyncResult)
at System.Web.HttpApplication.CallHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute()
at System.Web.HttpApplication.ExecuteStepImpl(IExecutionStep step)
at System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously)
After trying everything, I circled back to nHibernate 5.X change logs, ended up here: https://nhibernate.info/doc/nhibernate-reference/transactions.html, and found this little note at the very end of the changelog:
As of NHibernate v5.0, FlushMode.Commit requires the configuration setting transaction.use_connection_on_system_prepare to be true for flushing from transaction scope commit. Otherwise, it will be your responsibility to flush the session before completing the scope.
Using transaction.use_connection_on_system_prepare can cause undesired transaction promotions to distributed: it requires using a dedicated connection for flushing, and it delays session disposal (if done inside the scope) to the scope disposal. If you want to avoid this, set this setting to false and manually flush your sessions.
For new applications, it is recommended to set transaction.use_connection_on_system_prepare to false, and to flush explicitly your sessions before scope completion. For old applications, consider checking how sessions are flushed, and if possible switch it to false too.
Basically, the one setting we had changed while migrating to nHibernate 5 was the FlushMode from "Auto" to "Commit", but somehow missed this flag (transaction.use_connection_on_system_prepare = false).
Hope this will help other people with legacy systems trying to upgrade!

NLog Configuration for SQLCipher Database

We are attempting to use NLog (https://github.com/NLog/NLog) to log certain things to a table named Logs that is contained within our SQLCipher (https://github.com/sqlcipher/sqlcipher) Database. We are receiving several different errors, but the one that is currently relevant is shown in the NLog internal logging file below
2019-08-15 11:46:15.4789 Info Message Template Auto Format enabled
2019-08-15 11:46:15.5587 Info Adding target DatabaseTarget(Name=DBLog)
2019-08-15 11:46:15.6265 Info Found 38 configuration items
2019-08-15 11:46:15.7622 Info Configuration initialized.
2019-08-15 11:46:15.7751 Info NLog, Version=4.0.0.0, Culture=neutral, PublicKeyToken=5120e14c03d0593c. File version: 4.6.6.10303. Product version: 4.6.6.
2019-08-15 11:47:04.6315 Error DatabaseTarget(Name=DBLog): Error when writing to database. Exception: Microsoft.Data.Sqlite.SqliteException (0x80004005): SQLite Error 26: '**file is not a database**'.
at Microsoft.Data.Sqlite.SqliteException.ThrowExceptionForRC(Int32 rc, sqlite3 db)
at Microsoft.Data.Sqlite.SqliteCommand.<PrepareAndEnumerateStatements>d__62.MoveNext()
at Microsoft.Data.Sqlite.SqliteCommand.ExecuteReader(CommandBehavior behavior)
at Microsoft.Data.Sqlite.SqliteCommand.ExecuteReader()
at Microsoft.Data.Sqlite.SqliteCommand.ExecuteNonQuery()
at NLog.Targets.DatabaseTarget.WriteEventToDatabase(LogEventInfo logEvent, String connectionString)
at NLog.Targets.DatabaseTarget.Write(LogEventInfo logEvent)
The current NLog config file is as follows (the password and connectionString are actually correct, I've just renamed them in this example)
<?xml version="1.0" encoding="utf-8" ?>
<nlog xmlns="http://www.nlog-project.org/schemas/NLog.xsd"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
internalLogLovel="Trace"
internalLogFile="file.txt"
internalLogToConsole="true"
internalLogIncludeTimestamp="true">
<targets>
<!-- DATABASE LOGGER-->
<target name="DBLog"
xsi:type="Database"
dbProvider="Microsoft.Data.SQLite.SQLiteConnection, Microsoft.Data.SQLite"
keepConnection="false"
connectionString="Data Source=C:\Folder\DatabaseName.db"
dbPassword="password"
commandText="INSERT INTO Logs (Message) VALUES ('Test');">
</target>
</targets>
<rules>
<logger name="*" minlevel="Debug" writeTo="DBLog" />
</rules>
</nlog>
I think the problem may lie in the dbProvider property, but I am unsure what is needed in order to get NLog to work with SQLCipher (encrypted version of SQLite3)
Thanks in advance!
Edit (adding for JAZ)
2019-08-16 08:59:51.4363 Error Database Target[DBLog]: Error initializing target Exception: System.TypeLoadException: Could not load type 'System.Data.SQLite' from assembly 'NLog, Version=4.0.0.0, Culture=neutral, PublicKeyToken=5120e14c03d0593c'.
at System.RuntimeTypeHandle.GetTypeByName(String name, Boolean throwOnError, Boolean ignoreCase, Boolean reflectionOnly, StackCrawlMarkHandle stackMark, IntPtr pPrivHostBinder, Boolean loadTypeFromPartialName, ObjectHandleOnStack type)
at System.RuntimeTypeHandle.GetTypeByName(String name, Boolean throwOnError, Boolean ignoreCase, Boolean reflectionOnly, StackCrawlMark& stackMark, IntPtr pPrivHostBinder, Boolean loadTypeFromPartialName)
at System.RuntimeType.GetType(String typeName, Boolean throwOnError, Boolean ignoreCase, Boolean reflectionOnly, StackCrawlMark& stackMark)
at System.Type.GetType(String typeName, Boolean throwOnError, Boolean ignoreCase)
at NLog.Targets.DatabaseTarget.SetConnectionType()
at NLog.Targets.DatabaseTarget.InitializeTarget()
at NLog.Targets.Target.Initialize(LoggingConfiguration configuration)
Have you tried just doing this (Injecting the PRAGMA key in the commandText):
<!-- DATABASE LOGGER-->
<target name="DBLog"
xsi:type="Database"
dbProvider="Microsoft.Data.SQLite.SQLiteConnection, Microsoft.Data.SQLite"
keepConnection="false"
connectionString="Data Source=redacted\redacted.db"
commandText="PRAGMA key = 'redacted';INSERT INTO Logs (Message) VALUES ('Test');">
</target>
See also: https://www.zetetic.net/sqlcipher/sqlcipher-for-dotnet/

Azure AD Connect installation - System.Security.SecurityException: Requested registry access is not allowed

I had to reinstall Azure AD Connect after server formatting and I get the following error, using Custom settings:
[ERROR] A terminating unhandled exception occurred.
Exception Data (Raw): System.AggregateException: One or more errors occurred. ---> System.Reflection.TargetInvocationException: Exception has been thrown by the target of an invocation. ---> System.Security.SecurityException: Requested registry access is not allowed.
at System.ThrowHelper.ThrowSecurityException(ExceptionResource resource)
at Microsoft.Win32.RegistryKey.OpenSubKey(String name, Boolean writable)
at Microsoft.Identity.Health.Common.FileUploader.GetHealthAgentInstallPath()
at Microsoft.Identity.Health.Common.FileUploader..ctor(UploadSourcePolicy agent, Action`1 logLine)
at Microsoft.Online.Deployment.Types.Utility.AutoUpgradeEligibilityProvider..ctor()
--- End of inner exception stack trace ---
at System.RuntimeTypeHandle.CreateInstance(RuntimeType type, Boolean publicOnly, Boolean noCheck, Boolean& canBeCached, RuntimeMethodHandleInternal& ctor, Boolean& bNeedSecurityCheck)
at System.RuntimeType.CreateInstanceSlow(Boolean publicOnly, Boolean skipCheckThis, Boolean fillCache, StackCrawlMark& stackMark)
at System.Activator.CreateInstance(Type type, Boolean nonPublic)
at System.Activator.CreateInstance(Type type)
at Microsoft.Online.Deployment.Framework.ProviderRegistry.CreateInstance[TProvider]()
at Microsoft.Online.Deployment.OneADWizard.UI.WizardPages.PerformConfigurationPageViewModel.ExecuteAutoUpgradeCheck()
at Microsoft.Online.Deployment.OneADWizard.UI.WizardPages.PerformConfigurationPageViewModel.BackgroundInitialize(Object obj)
at System.Threading.Tasks.Task.Execute()
--- End of inner exception stack trace ---
---> (Inner Exception #0) System.Reflection.TargetInvocationException: Exception has been thrown by the target of an invocation. ---> System.Security.SecurityException: Requested registry access is not allowed.
at System.ThrowHelper.ThrowSecurityException(ExceptionResource resource)
at Microsoft.Win32.RegistryKey.OpenSubKey(String name, Boolean writable)
at Microsoft.Identity.Health.Common.FileUploader.GetHealthAgentInstallPath()
at Microsoft.Identity.Health.Common.FileUploader..ctor(UploadSourcePolicy agent, Action`1 logLine)
at Microsoft.Online.Deployment.Types.Utility.AutoUpgradeEligibilityProvider..ctor()
--- End of inner exception stack trace ---
at System.RuntimeTypeHandle.CreateInstance(RuntimeType type, Boolean publicOnly, Boolean noCheck, Boolean& canBeCached, RuntimeMethodHandleInternal& ctor, Boolean& bNeedSecurityCheck)
at System.RuntimeType.CreateInstanceSlow(Boolean publicOnly, Boolean skipCheckThis, Boolean fillCache, StackCrawlMark& stackMark)
at System.Activator.CreateInstance(Type type, Boolean nonPublic)
at System.Activator.CreateInstance(Type type)
at Microsoft.Online.Deployment.Framework.ProviderRegistry.CreateInstance[TProvider]()
at Microsoft.Online.Deployment.OneADWizard.UI.WizardPages.PerformConfigurationPageViewModel.ExecuteAutoUpgradeCheck()
at Microsoft.Online.Deployment.OneADWizard.UI.WizardPages.PerformConfigurationPageViewModel.BackgroundInitialize(Object obj)
at System.Threading.Tasks.Task.Execute()<---
Do you have any idea about the origin of the problem?
Thank you.
Bertrand
Found the answer here and here
That's about the registry key to give permission to:
HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\ADHealthAgent\Sync
Make sure you are logged into the VM as the tenant cloud administrator and also ensure that you explicitly run Powershell as an administrator if you are installing through Powershell. Also, check that you are installing the latest version of AAD Connect.
The Admin account for the server needs to have registry access privileges. In your system settings on the VM make sure to add your account as an admin.
See also these troubleshooting steps for this error.

The web user to have access to only one database

I have few web sites running in IIS 7.5 and each one is mapped to its own related database, using the connectionStrings section in each one of the config files. The string is using "Integrated Security=SSPI" and everything is working fine so far, users can read and write to their respective dbs. The IIS and the SQL Server are on the same machine and the SQL is set for mixed authentication.
I want to set Integrated Security=false and add user=mySpecifDb;pwd=test123 to the string, but it doesn't work. The web site throws a db connection error. I've created the user "mySpecifDb" using the SSMS and followed all the instructions so far. I can log into the SSMS using the credentials "mySpecifDb" and "test123" and I can read and write to the selected database and only to it exclusively. I can't access any other db using these credentials and this is what I want. In the IIS 7.5 all websites are using the DefaultAppPool. I dont know where to go from this point.
EDIT: This is the real connection string with the real credentials. As mentioned before I can log in SSMS using them, and read/write to AutoParkDemo db only.If I just change "true" to "SSPI" then all works.
<connectionStrings>
<clear />
<add name="AutoPark" connectionString="Data Source=(LocalDb)\v11.0;Initial Catalog=AutoParkDemo;Integrated Security=false;user=apmDemo;pwd=*****" providerName="System.Data.SqlClient" />
</connectionStrings>
EDIT:
Server Error in '/Manager' Application.
Login failed for user 'apmDemo'.
Exception Details: System.Data.SqlClient.SqlException: Login failed for user 'apmDemo'.
Stack Trace:
[SqlException (0x80131904): Login failed for user 'apmDemo'.]
System.Data.ProviderBase.DbConnectionPool.TryGetConnection(DbConnection owningObject, UInt32 waitForMultipleObjectsTimeout, Boolean allowCreate, Boolean onlyOneCheckConnection, DbConnectionOptions userOptions, DbConnectionInternal& connection) +642
System.Data.ProviderBase.DbConnectionPool.TryGetConnection(DbConnection owningObject, TaskCompletionSource`1 retry, DbConnectionOptions userOptions, DbConnectionInternal& connection) +116
System.Data.ProviderBase.DbConnectionFactory.TryGetConnection(DbConnection owningConnection, TaskCompletionSource`1 retry, DbConnectionOptions userOptions, DbConnectionInternal oldConnection, DbConnectionInternal& connection) +1089
System.Data.ProviderBase.DbConnectionInternal.TryOpenConnectionInternal(DbConnection outerConnection, DbConnectionFactory connectionFactory, TaskCompletionSource`1 retry, DbConnectionOptions userOptions) +6785863
System.Data.SqlClient.SqlConnection.TryOpenInner(TaskCompletionSource`1 retry) +233
System.Data.SqlClient.SqlConnection.TryOpen(TaskCompletionSource`1 retry) +278
System.Data.SqlClient.SqlConnection.Open() +239
System.Data.Entity.Infrastructure.Interception.InternalDispatcher`1.Dispatch(TTarget target, Action`2 operation, TInterceptionContext interceptionContext, Action`3 executing, Action`3 executed) +207
System.Data.Entity.Infrastructure.Interception.DbConnectionDispatcher.Open(DbConnection connection, DbInterceptionContext interceptionContext) +438
System.Data.Entity.SqlServer.<>c__DisplayClass1.<Execute>b__0() +15
System.Data.Entity.SqlServer.DefaultSqlExecutionStrategy.Execute(Func`1 operation) +263
System.Data.Entity.SqlServer.SqlProviderServices.UsingConnection(DbConnection sqlConnection, Action`1 act) +375
System.Data.Entity.SqlServer.SqlProviderServices.UsingMasterConnection(DbConnection sqlConnection, Action`1 act) +749
System.Data.Entity.SqlServer.SqlProviderServices.GetDbProviderManifestToken(DbConnection connection) +504
System.Data.Entity.Core.Common.DbProviderServices.GetProviderManifestToken(DbConnection connection) +118
[ProviderIncompatibleException: The provider did not return a ProviderManifestToken string.]
System.Data.Entity.Core.Common.DbProviderServices.GetProviderManifestToken(DbConnection connection) +459
System.Data.Entity.Utilities.DbProviderServicesExtensions.GetProviderManifestTokenChecked(DbProviderServices providerServices, DbConnection connection) +51
[ProviderIncompatibleException: An error occurred accessing the database. This usually means that the connection to the database failed. Check that the connection string is correct and that the appropriate DbContext constructor is being used to specify it or find it in the application's config file. See http://go.microsoft.com/fwlink/?LinkId=386386 for information on DbContext and connections. See the inner exception for details of the failure.]
System.Data.Entity.Utilities.DbProviderServicesExtensions.GetProviderManifestTokenChecked(DbProviderServices providerServices, DbConnection connection) +300
System.Collections.Concurrent.ConcurrentDictionary`2.GetOrAdd(TKey key, Func`2 valueFactory) +83
System.Data.Entity.Infrastructure.DefaultManifestTokenResolver.ResolveManifestToken(DbConnection connection) +327
System.Data.Entity.DbModelBuilder.Build(DbConnection providerConnection) +118
System.Data.Entity.Internal.LazyInternalContext.CreateModel(LazyInternalContext internalContext) +94
System.Data.Entity.Internal.RetryLazy`2.GetValue(TInput input) +248
System.Data.Entity.Internal.LazyInternalContext.InitializeContext() +618
System.Data.Entity.Internal.InternalContext.CreateObjectContextForDdlOps() +23
System.Data.Entity.Database.Exists() +40
Microsoft.AspNet.Identity.EntityFramework.IdentityDbContext`1.IsIdentityV1Schema(DbContext db) +168
Microsoft.AspNet.Identity.EntityFramework.IdentityDbContext`1..ctor(String nameOrConnectionString, Boolean throwIfV1Schema) +80
AutoParkManager.Models.ApplicationDbContext..ctor() in c:\AppVS2013\AutoPark\AutoParkManager\Models\IdentityModels.cs:12
AutoParkManager.Controllers.AccountController..ctor() in c:\AppVS2013\AutoPark\AutoParkManager\Controllers\AccountController.cs:22
[TargetInvocationException: Exception has been thrown by the target of an invocation.]
System.RuntimeTypeHandle.CreateInstance(RuntimeType type, Boolean publicOnly, Boolean noCheck, Boolean& canBeCached, RuntimeMethodHandleInternal& ctor, Boolean& bNeedSecurityCheck) +0
System.RuntimeType.CreateInstanceSlow(Boolean publicOnly, Boolean skipCheckThis, Boolean fillCache, StackCrawlMark& stackMark) +159
System.RuntimeType.CreateInstanceDefaultCtor(Boolean publicOnly, Boolean skipCheckThis, Boolean fillCache, StackCrawlMark& stackMark) +256
System.Activator.CreateInstance(Type type, Boolean nonPublic) +127
System.Activator.CreateInstance(Type type) +11
System.Web.Mvc.DefaultControllerActivator.Create(RequestContext requestContext, Type controllerType) +92
[InvalidOperationException: An error occurred when trying to create a controller of type 'AutoParkManager.Controllers.AccountController'. Make sure that the controller has a parameterless public constructor.]
System.Web.Mvc.DefaultControllerActivator.Create(RequestContext requestContext, Type controllerType) +256
System.Web.Mvc.DefaultControllerFactory.CreateController(RequestContext requestContext, String controllerName) +169
System.Web.Mvc.MvcHandler.ProcessRequestInit(HttpContextBase httpContext, IController& controller, IControllerFactory& factory) +270
System.Web.Mvc.MvcHandler.BeginProcessRequest(HttpContextBase httpContext, AsyncCallback callback, Object state) +147
System.Web.CallHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute() +12639055
System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously) +288
Change you connectionstring like below and try again. Take off the Integrated Security=false; and specify Persist Security Info=True;
<add name="AutoPark" connectionString="Data Source=(LocalDb)\v11.0;Initial Catalog=AutoParkDemo;Persist Security Info=True;user=apmDemo;pwd=*****" providerName="System.Data.SqlClient" />
A better solution would be to create a new local windows user on the server, add that user to the SQL database (with correct permissions). Then create a new app pool using this new identity and assoicate the one web site with this new app pool. You would leave the Integrate Security as True.
If you really want to specify the user in the config, then as Martin and Dennis commented we would need full error message and connection string (minus the password)

Resources