ABP - Dependency injection issue for app service when using AbpCrudPageBase in Blazor - asp.net-core

I've been following this tutorial on the ABP docs site to learn ABP (using Blazor Server and EF Core ABP template).
The code for the issue I am encountering is available on my Github (I've created a tag for the issue).
I'm not doing it exactly the same, instead, I'm using Person as my entity instead of Book (making a sporting club management system instead of a book store).
I completed Part 1 of the tutorial and the correct API endpoints were created and I am able to use them to perform CRUD operations.
I am now on Part 2 of the tutorial and the "list page" is not loading.
This is the error I see in the browser dev tools.
blazor.server.js?_v=637732634000000000:1
[2022-01-17T17:57:20.070Z] Error: System.InvalidOperationException: Cannot provide a value for property 'AppService' on type 'Acme.ClubManagement.Blazor.Pages.People'. There is no registered service of type 'Acme.ClubManagement.People.IPersonAppService'.
at Microsoft.AspNetCore.Components.ComponentFactory.<>c__DisplayClass7_0.<CreateInitializer>g__Initialize|1(IServiceProvider serviceProvider, IComponent component)
at Microsoft.AspNetCore.Components.ComponentFactory.PerformPropertyInjection(IServiceProvider serviceProvider, IComponent instance)
at Microsoft.AspNetCore.Components.ComponentFactory.InstantiateComponent(IServiceProvider serviceProvider, Type componentType)
at Microsoft.AspNetCore.Components.RenderTree.Renderer.InstantiateChildComponentOnFrame(RenderTreeFrame& frame, Int32 parentComponentId)
at Microsoft.AspNetCore.Components.RenderTree.RenderTreeDiffBuilder.InitializeNewComponentFrame(DiffContext& diffContext, Int32 frameIndex)
at Microsoft.AspNetCore.Components.RenderTree.RenderTreeDiffBuilder.InitializeNewSubtree(DiffContext& diffContext, Int32 frameIndex)
at Microsoft.AspNetCore.Components.RenderTree.RenderTreeDiffBuilder.InsertNewFrame(DiffContext& diffContext, Int32 newFrameIndex)
at Microsoft.AspNetCore.Components.RenderTree.RenderTreeDiffBuilder.AppendDiffEntriesForFramesWithSameSequence(DiffContext& diffContext, Int32 oldFrameIndex, Int32 newFrameIndex)
at Microsoft.AspNetCore.Components.RenderTree.RenderTreeDiffBuilder.AppendDiffEntriesForRange(DiffContext& diffContext, Int32 oldStartIndex, Int32 oldEndIndexExcl, Int32 newStartIndex, Int32 newEndIndexExcl)
at Microsoft.AspNetCore.Components.RenderTree.RenderTreeDiffBuilder.AppendDiffEntriesForFramesWithSameSequence(DiffContext& diffContext, Int32 oldFrameIndex, Int32 newFrameIndex)
at Microsoft.AspNetCore.Components.RenderTree.RenderTreeDiffBuilder.AppendDiffEntriesForRange(DiffContext& diffContext, Int32 oldStartIndex, Int32 oldEndIndexExcl, Int32 newStartIndex, Int32 newEndIndexExcl)
at Microsoft.AspNetCore.Components.RenderTree.RenderTreeDiffBuilder.AppendDiffEntriesForFramesWithSameSequence(DiffContext& diffContext, Int32 oldFrameIndex, Int32 newFrameIndex)
at Microsoft.AspNetCore.Components.RenderTree.RenderTreeDiffBuilder.AppendDiffEntriesForRange(DiffContext& diffContext, Int32 oldStartIndex, Int32 oldEndIndexExcl, Int32 newStartIndex, Int32 newEndIndexExcl)
at Microsoft.AspNetCore.Components.RenderTree.RenderTreeDiffBuilder.ComputeDiff(Renderer renderer, RenderBatchBuilder batchBuilder, Int32 componentId, ArrayRange`1 oldTree, ArrayRange`1 newTree)
at Microsoft.AspNetCore.Components.Rendering.ComponentState.RenderIntoBatch(RenderBatchBuilder batchBuilder, RenderFragment renderFragment, Exception& renderFragmentException)
at Microsoft.AspNetCore.Components.RenderTree.Renderer.ProcessRenderQueue()
What I find difficult to understand is that it says there is a dependency injection issue for Acme.ClubManagement.People.IPersonAppService, but this service is correctly looked up when using the API endpoints.
Why is this DI issue happening for the Blazor page and not when using the API endpoints directly?

ABP uses a naming convention, see https://docs.abp.io/en/abp/latest/Dependency-Injection#exposed-services-by-convention
So, if you rename IPersonAppService to IPeopleAppService the problem will be solved.
Thanks for the minimal, reproducible example

#TheMagnificent11 in response to the question you wrote in the comment;
The problem is caused by the following code block in People.razor.
<DataGridColumns>
<DataGridColumn TItem="PersonDto"
Field="#nameof(PersonDto.GivenName)"
Caption="#Localizer["PeopleTable:GivenName"]">
</DataGridColumn>
</DataGridColumns>
<DataGridColumns>
<DataGridColumn TItem="PersonDto"
Field="#nameof(PersonDto.Surname)"
Caption="#Localizer["PeopleTable:Surname"]">
</DataGridColumn>
</DataGridColumns>
It is necessary to replace this code with the following:
<DataGridColumns>
<DataGridColumn TItem="PersonDto"
Field="#nameof(PersonDto.GivenName)"
Caption="#Localizer["PeopleTable:GivenName"]">
</DataGridColumn>
<DataGridColumn TItem="PersonDto"
Field="#nameof(PersonDto.Surname)"
Caption="#Localizer["PeopleTable:Surname"]">
</DataGridColumn>
</DataGridColumns>
In short, the problem is that the DataGridColumns tag is used twice in the same DataGrid.
PS: #TheMagnificent11 I couldn't fit the answer into the comment field so I had to write it here, FYI.

Related

Is fsbolero's runner, `bolero-live`, open source and if so, where is the source?

I've been having a problem getting a modified bolero app to perform HotReload. The problem appears to be in bolero-live as indicated by this top portion of the error log (line break inserted for convenience). However, the source code for bolero-live does not appear to be available despite the presence of its reference library code for the client and server projects, on github. I welcome any insight.
fail: Microsoft.AspNetCore.Server.Kestrel[13]
Connection id "0HLTL27BTITCT", Request id "0HLTL27BTITCT:00000001":
An unhandled exception was thrown by the application.
System.IO.DirectoryNotFoundException:
Could not find a part of the path '
/mnt/drive1/testproj/test1/src/test1.Serve/bin/Debug
/netstandard2.0/dist/_framework/_bin/test1.Client.dll
'
at Interop.ThrowExceptionForIoErrno(
ErrorInfo errorInfo, String path, Boolean isDirectory
,Func`2 errorRewriter
)
at Microsoft.Win32.SafeHandles.SafeFileHandle.Open(
String path, OpenFlags flags, Int32 mode
)
at System.IO.FileStream..ctor(
String path, FileMode mode, FileAccess access,
FileShare share, Int32 bufferSize, FileOptions options
)
at System.IO.FileStream..ctor(
String path, FileMode mode, FileAccess access
,FileShare share
)
at System.IO.File.InternalWriteAllBytes(String path, Byte[] bytes)
at System.IO.File.WriteAllBytes(String path, Byte[] bytes)
at Elmish.HotReload.Bolero.Cli.ListenerController.Update() in
/root/TeamCity/buildAgent/work/bbeb18eb622e1e0d/src
/bolero-live/ListenerController.fs
:line 39
at lambda_method(Closure , Object , Object[] )
at Microsoft.AspNetCore.Mvc.Internal.ActionMethodExecutor
.AwaitableResultExecutor.Execute(
IActionResultTypeMapper mapper
,ObjectMethodExecutor executor
,Object controller, Object[] arguments
)
at Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker
.InvokeActionMethodAsync()
at Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker
.InvokeNextActionFilterAsync()
at Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker
.Rethrow(ActionExecutedContext context)
bolero-live is different than the Bolero HotReload Templating implementation. bolero-live is supposed to reload the underlying dll as well, not just the front end. You can find the source code here
It unfortunately has not been heavily maintained or kept up to date with the latest Bolero versions (mostly as I've not had time to maintain it). The exception seems to indicate that the cli tool itself cannot find the newly made dll from FCSWatch.
bolero-live seems to be merely FCSWatch on github.com

Sitecore Core database index Update issue

We are using a multi server environment with 1 CMS and 2 CD configuration. The CORE and WEB of CMS are being shared by CD 2 only and CD 1 as its own web and core.
The issue is- log files of CD2 are capturing the below mentioned error:
ManagedPoolThread #14 00:00:05 INFO Job started:Index_Update_IndexName=sitecore_core_index
ManagedPoolThread #14 00:00:05 ERROR Exception
Exception: System.Reflection.TargetInvocationException
Message: Exception has been thrown by the target of an invocation.
Source: mscorlib
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.Reflection.MethodBase.Invoke(Object obj, Object[] parameters)
at (Object , Object[] )
at Sitecore.Pipelines.CorePipeline.Run(PipelineArgs args)
at Sitecore.Jobs.Job.ThreadEntry(Object state)
Nested Exception
Exception: System.InvalidOperationException
Message: Configuration
Source: Sitecore.ContentSearch.LuceneProvider
at Sitecore.ContentSearch.LuceneProvider.LuceneIndex.EnsureInitialized()
at Sitecore.ContentSearch.LuceneProvider.LuceneIndex.CreateUpdateContext()
at Sitecore.ContentSearch.LuceneProvider.LuceneIndex.PerformUpdate(IEnumerable`1 indexableUniqueIds, IndexingOptions indexingOptions)
As we researched, we found that this type of error gets captured when issue with Core database index update. Further this was also confirmed by crawling log and checking the configuration within the \App_Config\Include\Sitecore.ContentSearch.Lucene.Index.Core which has this job defined for Index update.
Crawling log entries getting captured
INFO [Index=sitecore_core_index] IntervalAsynchronousUpdateStrategy executing.
INFO [Index=sitecore_core_index] Event Queue is forced
As a next step we took following steps but problem still exist:
Deleted old Core indexes and rebuilt for CMS and CD2 both.
My Questions:
If we have same core for CMS and CD2 then do we require index rebuilt for both environment because as per my info the index get saved in disk.
Secondly we are facing caching issue for CD2 only, is this related to index update.
Thirdly the config details Sitecore.ContentSearch.Lucene.Index.Core are present in CMS and CD2 also so is this responsible for these exception as two processs are updating indexes for the same Core indexes.
Lastly we have a separate core and web for CD1 with replication enabled but we still see these error being captured in CD1 as well. We are seeing this errors from past few months and recently the frequency of errors has increased due to which it is eating a huge chunk of physical memory in CD2 and causing application higher response time.
I figured out what the problem in my environment was. Look in your log file and before you seeing that exeption, do you see the following:
ManagedPoolThread #11 10:07:24 INFO Loading Dictionary from database. Domain: 'Dictionary'. Language: 'en'.
ManagedPoolThread #11 10:07:24 ERROR Error saving {sitecore file path}\Website\temp\dictionary.dat.
Exception: System.IO.IOException
Message: The file '{sitecore file path}\Website\temp\dictionary.dat' already exists.
Source: mscorlib
at System.IO.__Error.WinIOError(Int32 errorCode, String maybeFullPath)
at System.IO.FileStream.Init(String path, FileMode mode, FileAccess access, Int32 rights, Boolean useRights, FileShare share, Int32 bufferSize, FileOptions options, SECURITY_ATTRIBUTES secAttrs, String msgPath, Boolean bFromProxy, Boolean useLongPath, Boolean checkHost)
at System.IO.FileStream..ctor(String path, FileMode mode, FileAccess access, FileShare share, Int32 bufferSize, FileOptions options, String msgPath, Boolean bFromProxy)
at System.IO.FileStream..ctor(String path, FileMode mode, FileAccess access, FileShare share, Int32 bufferSize)
at Sitecore.Globalization.Translate.Save()
If so, delete that and restart your site. This should fix the issue that you are seeing.

RavenDB connection issues

We have seen a noticeable uptick in problems related to RavenDB connections. We're using the IIS server connection method.
I've checked the index errors and I don't see anything listed.
This server is replicated with a MySQL server and there is one error related to replication in the log from today. Could the client stack trace errors actually be coming from the replicated server and not Raven?
EDIT
The client in this case is a single job that runs a few hundred times a day...succeeding many of those times but increasing in failures due to these errors.
Sql Replication failure to replication
Here are the partial stack trace errors from the client log:
[WebException: Unable to connect to the remote server]
System.Net.HttpWebRequest.GetRequestStream(TransportContext& context):367
System.Net.HttpWebRequest.GetRequestStream():3
Raven.Abstractions.Connection.HttpRequestHelper.WriteDataToRequest(HttpWebRequest req, String data, Boolean disableCompression):7
Raven.Client.Connection.ServerClient.DirectBatch(IEnumerable`1 commandDatas, String operationUrl):171
Raven.Client.Connection.ReplicationInformer.TryOperation[T](Func`2 operation, String operationUrl, Boolean avoidThrowing, T& result, Boolean& wasTimeout):35
Raven.Client.Connection.ReplicationInformer.ExecuteWithReplication[T](String method, String primaryUrl, Int32 currentRequest, Int32 currentReadStripingBase, Func`2 operation):169
Raven.Client.Connection.ServerClient.ExecuteWithReplication[T](String method, Func`2 operation):33
Raven.Client.Document.DocumentSession.SaveChanges():65
and
[WebException: Unable to connect to the remote server]
System.Net.HttpWebRequest.GetResponse():570
Raven.Client.Connection.HttpJsonRequest.ReadJsonInternal(Func`1 getResponse):45
Raven.Client.Connection.HttpJsonRequest.ReadResponseJson():206
Raven.Client.Connection.ServerClient.DirectGet(String[] ids, String operationUrl, String[] includes, String transformer, Dictionary`2 queryInputs, Boolean metadataOnly):631
Raven.Client.Connection.ServerClient+<>c__DisplayClass77.<Get>b__76(String u):51
Raven.Client.Connection.ReplicationInformer.TryOperation[T](Func`2 operation, String operationUrl, Boolean avoidThrowing, T& result, Boolean& wasTimeout):35
Raven.Client.Connection.ReplicationInformer.ExecuteWithReplication[T](String method, String primaryUrl, Int32 currentRequest, Int32 currentReadStripingBase, Func`2 operation):169
Raven.Client.Connection.ServerClient.ExecuteWithReplication[T](String method, Func`2 operation):33
Raven.Client.Document.HiLoKeyGenerator.GetDocument(IDatabaseCommands databaseCommands):41
Raven.Client.Document.HiLoKeyGenerator.GetNextRange(IDatabaseCommands databaseCommands):109
Raven.Client.Document.HiLoKeyGenerator.NextId(IDatabaseCommands commands):58
Raven.Client.Document.HiLoKeyGenerator.GenerateDocumentKey(IDatabaseCommands databaseCommands, DocumentConvention convention, Object entity):9
Raven.Client.Document.MultiTypeHiLoKeyGenerator.GenerateDocumentKey(IDatabaseCommands databaseCommands, DocumentConvention conventions, Object entity):174
Raven.Client.Document.DocumentStore+<>c__DisplayClass4.<Initialize>b__2(String dbName, IDatabaseCommands databaseCommands, Object entity):20
Raven.Client.Document.DocumentConvention.GenerateDocumentKey(String dbName, IDatabaseCommands databaseCommands, Object entity):164
Raven.Client.Document.GenerateEntityIdOnTheClient.GenerateDocumentKeyForStorage(Object entity):46
Raven.Client.Document.InMemoryDocumentSessionOperations.StoreInternal(Object entity, Etag etag, String id, Boolean forceConcurrencyCheck):79
Raven.Client.Document.InMemoryDocumentSessionOperations.Store(Object entity):23
The error says the client cannot connect to the the server. Maybe the client is offline. Or the server is. Or a firewall is in the way. Or maybe the server is there but blows up before returning a response to the client. If the issue is intermittent, and users arent complaining, it's probably just a connectivity thing that you can ignore. If users are complaining, you should look in server-side logs.

WCF : An item with the same key has already been added

While testing WCF services with 150 Users, i got this exception.
Note : I am using MS Test Project for loadtesting of WCF Service. When load test is run for 100users, there is no exception.
at System.ThrowHelper.ThrowArgumentException(ExceptionResource resource) at System.Collections.Generic.Dictionary2.Insert(TKey key, TValue value, Boolean add) at System.Linq.Dynamic.ClassFactory.GetDynamicClass(IEnumerable1 properties) at System.Linq.Dynamic.DynamicExpression.CreateClass(IEnumerable`1 properties) at System.Linq.Dynamic.ExpressionParser.ParseNew() at System.Linq.Dynamic.ExpressionParser.ParseIdentifier() at System.Linq.Dynamic.ExpressionParser.ParsePrimaryStart() at System.Linq.Dynamic.ExpressionParser.ParsePrimary() at System.Linq.Dynamic.ExpressionParser.ParseUnary() at System.Linq.Dynamic.ExpressionParser.ParseMultiplicative() at System.Linq.Dynamic.ExpressionParser.ParseAdditive() at System.Linq.Dynamic.ExpressionParser.ParseComparison() at System.Linq.Dynamic.ExpressionParser.ParseLogicalAnd() at System.Linq.Dynamic.ExpressionParser.ParseLogicalOr() at System.Linq.Dynamic.ExpressionParser.ParseExpression() at System.Linq.Dynamic.ExpressionParser.Parse(Type resultType) at System.Linq.Dynamic.DynamicExpression.ParseLambda(ParameterExpression[] parameters, Type resultType, String expression, Object[] values) at System.Linq.Dynamic.DynamicExpression.ParseLambda(Type itType, Type resultType, String expression, Object[] values) at System.Linq.Dynamic.DynamicQueryable.Select(IQueryable source, String selector, Object[] values) at CustomEntities.Data.Repository.CustomEntitiesDataRepository.GetCustomEntityData(CriteriaDto criteriaDto) in d:\Projects\SRM\Services\Data\CustomEntities\CustomEntities.Data.Repository\CustomEntitiesDataRepository.cs:line 131 at CustomEntities.Data.Manager.CustomEntitiesDataManager.GetCustomEntityData(CriteriaDto criteriaDto) in d:\Projects\SRM\Services\Data\CustomEntities\CustomEntities.Data.Manager\CustomEntitiesDataManager.cs:line 69
If you look at your code, in CustomEntitiesDataRepository.cs at line 131, this line is triggering the issue. The custom entity you are returning is, at some level, trying to insert a value into a Dictionary<T,U>, but the key its using already exists.
Actually it looks like there's a concurrency issue in .Select(). See http://www.webr2.com/system-linq-dynamic-select-new-does-not-appear-to-be-thread-safe/
Easiest fix is to put some locking in your code around calls to Select

Access Denied Error for a method in web service

I have a webservice that works perfectly from localhost but when I hosted it on the testing server I get an error on one of the methods. I am using wsHttp Binding. everything else works fine on the client side except for this method. This is the error that I am getting
client error:
System.ServiceModel.Security.SecurityAccessDeniedException: Access is denied.
Server stack trace:
at System.ServiceModel.Channels.ServiceChannel.ThrowIfFaultUnderstood(Message reply, MessageFault fault, String action, MessageVersion version, FaultConverter faultConverter)
at System.ServiceModel.Channels.ServiceChannel.HandleReply(ProxyOperationRuntime operation, ProxyRpc& rpc)
at System.ServiceModel.Channels.ServiceChannel.Call(String action, Boolean oneway, ProxyOperationRuntime operation, Object[] ins, Object[] outs, TimeSpan timeout)
at System.ServiceModel.Channels.ServiceChannelProxy.InvokeService(IMethodCallMessage methodCall, ProxyOperationRuntime operation)
at System.ServiceModel.Channels.ServiceChannelProxy.Invoke(IMessage message)
Server error:
namespace.Service Error: 10001 : Error occurred in methodname().
System.Security.SecurityException: The source was not found, but some or all event logs could not be searched. Inaccessible logs: Security.
at System.Diagnostics.EventLog.FindSourceRegistration(String source, String machineName, Boolean readOnly)
at System.Diagnostics.EventLog.SourceExists(String source, String machineName)
at System.Diagnostics.EventLog.VerifyAndCreateSource(String sourceName, String currentMachineName)
at System.Diagnostics.EventLog.WriteEvent(EventInstance instance, Byte[] data, Object[] values)
at System.Diagnostics.EventLog.WriteEvent(EventInstance instance, Object[] values)
at System.Diagnostics.EventLogTraceListener.TraceEvent(TraceEventCache eventCache, String source, TraceEventType severity, Int32 id, String format, Object[] args)
at System.Diagnostics.TraceSource.TraceEvent(TraceEventType eventType, Int32 id, String format, Object[] args)
at AutoWatch.Entity.WcfService.TrackingService.UpdateIncidentStatusHistory(Int64 incidentId, String status, String username, String comment, Boolean SuspectFaultyUnit) in C:\..servicename.cs:line 566
at AutoWatch.Entity.WcfService.TrackingService.GetNewIncidentMessage(String username) in C:\..servicename.cs:line 444
The Zone of the assembly that failed was:
MyComputer
I added in the error I am getting on the server.
Is it possible I am getting this error because the service cannot write to the event log?
Please help.
Ensure that account running your process where the service is hosted has access rights to the database. For example in case of IIS the account running the application pool where the service is hosted must have login to database server and it must have permissions to do all necessary operations in your database.
Edit:
The server stack trace looks quite straightforward. You have a problem with writing to Windows Event Log! It cannot find source you requested and it doesn't have permission to create it.
I got the same error when I tried to use the following statement in a Web Method of a WCF Service:
string myTypeName = typeof(ErrorHandlerBehavior).AssemblyQualifiedName;
where ErrorHandlerBehavior derives from BehaviorExtensionElement.
The line works well when I test the service on my localhost. On the web, the call of the containing method raises the Exception "Access is denied".
In this case, I guess that the cause was that my IP does not allow the creation of a BehaviourExtensionElement in a Partially Trusted environment (my service is in a shared hosting environment).
Finally, I succeded following the first mechanism described at https://learn.microsoft.com/en-us/dotnet/framework/wcf/extending/configuring-and-extending-the-runtime-with-behaviors about Service Behaviors:
"Using an attribute on the service class. When a ServiceHost is constructed, the ServiceHost implementation uses reflection to discover the set of attributes on the type of the service. If any of those attributes are implementations of IServiceBehavior, they are added to the behaviors collection on ServiceDescription. This allows those behaviors to participate in the construction of the service run time."
I just modified the derivation (no other modification required):
public class ErrorServiceBehavior : Attribute, IServiceBehavior
{ ... }
and use the class as Attribute of my service:
[ErrorServiceBehavior()]
public partial class MyService : IMyService
{...}
No other modification required. Check the original sample at How do I create a global exception handler for a WCF Services?.