2

I'm using ASP.NET Boilerplate (with .NET Core). I'm trying to implement notification system as mentioned in official doc under Multiple Notifiers, but I encountered:

System.NullReferenceException: 'Object reference not set to an instance of an object.'

My question is not related to exception itself. I want to know if there are any pre-requests configuration or setting before I implement the example, or if my code misses something:

public class MessageAppService: AsyncCrudAppService<Message, MessageDto, long, PagedAndSortedResultRequestDto, CreateMessageDto, UpdateMessageDto, ReadMessageDto>, IRealTimeNotifier, ITransientDependency
{
    private readonly IRepository<Message, long> _repository;

    private readonly IDbContextProvider<MySystemDbContext> _dbContextProvider;
    private MySystemDbContext db => _dbContextProvider.GetDbContext();

    IHubContext<MyChatHub> _hubContext; // This for online chat

    private readonly IEmailSender _emailSender;
    private readonly UserManager _userManager;

    private readonly INotificationSubscriptionManager _notificationSubscriptionManager;

    public MessageAppService(
        IDbContextProvider<MySystemDbContext> dbContextProvider,
        IRepository<Message, long> repository, 
        IHubContext<MyChatHub> hubContext /* This for online chat */,
        INotificationSubscriptionManager notificationSubscriptionManager,
        IEmailSender emailSender,
        UserManager userManager
    ) : base(repository)
    {
        _repository = repository;
        _dbContextProvider = dbContextProvider;
        _hubContext = hubContext; // This for online chat 
        _notificationSubscriptionManager = notificationSubscriptionManager;
        _emailSender = emailSender;
        _userManager = userManager;
    }

    public override async Task<MessageDto> CreateAsync(CreateMessageDto input)
    {
        var test = await base.CreateAsync(input);
        UserNotification userNotifications = new UserNotification();
        userNotifications.UserId = 10010;
        //
        userNotifications.Notification.TenantId = AbpSession.TenantId;
        userNotifications.Notification.NotificationName = "test";

        UserNotification[] notificationList = new UserNotification[1];
        notificationList[0] = userNotifications;
        await SendNotificationsAsync(notificationList);
        return test;
    }

    public async Task SendNotificationsAsync(UserNotification[] userNotifications)
    {
        foreach (var userNotification in userNotifications)
        {
            if (userNotification.Notification.Data is MessageNotificationData data)
            {
                var user = await _userManager.GetUserByIdAsync(userNotification.UserId);

                _emailSender.Send(
                    to: "testg@gmail.com",
                    subject: "You have a new notification!",
                    body: data.Message,
                    isBodyHtml: true
                );
            }
        }
    }

    void IRealTimeNotifier.SendNotifications(UserNotification[] userNotifications)
    {
        throw new NotImplementedException();
    }
}

I've added below in PreInitialize() function in .Application module:

Configuration.Notifications.Notifiers.Add<MessageAppService>();

Update:

I know how to avoid this exception but I want to know if the steps that I've implemented in my code are enough to get the notification.


Update 2:

I've applied the code in the question mentioned by aaron. I got another exception:

WARN  2020-07-05 13:30:06,907 [9    ] fications.DefaultNotificationDistributer - System.Net.Mail.SmtpException: Failure sending mail.
 ---> System.Net.Internals.SocketExceptionFactory+ExtendedSocketException (10061): No connection could be made because the target machine actively refused it. [::ffff:127.0.0.1]:25
   at System.Net.Sockets.Socket.DoConnect(EndPoint endPointSnapshot, SocketAddress socketAddress)
   at System.Net.Sockets.Socket.Connect(EndPoint remoteEP)
   at System.Net.Sockets.TcpClient.Connect(IPEndPoint remoteEP)
   at System.Net.Sockets.TcpClient.Connect(String hostname, Int32 port)
--- End of stack trace from previous location where exception was thrown ---
   at System.Net.Sockets.TcpClient.Connect(String hostname, Int32 port)
   at System.Net.Mail.SmtpConnection.GetConnection(String host, Int32 port)
   at System.Net.Mail.SmtpTransport.GetConnection(String host, Int32 port)
   at System.Net.Mail.SmtpClient.GetConnection()
   at System.Net.Mail.SmtpClient.Send(MailMessage message)
   --- End of inner exception stack trace ---
   at System.Net.Mail.SmtpClient.Send(MailMessage message)
   at Abp.Net.Mail.Smtp.SmtpEmailSender.SendEmail(MailMessage mail)
   at Abp.Net.Mail.EmailSenderBase.Send(MailMessage mail, Boolean normalize)
   at Abp.Net.Mail.EmailSenderBase.Send(String to, String subject, String body, Boolean isBodyHtml)
   at MySystem.ChatAppService.MessageAppService.SendNotificationsAsync(UserNotification[] userNotifications) in D:\WorkSpace\MySystem\aspnet-core\src\MySystem.Application\ChatAppService\MessageAppService.cs:line 172
   at Abp.Notifications.DefaultNotificationDistributer.NotifyAsync(UserNotification[] userNotifications)
System.Net.Mail.SmtpException: Failure sending mail.
 ---> System.Net.Internals.SocketExceptionFactory+ExtendedSocketException (10061): No connection could be made because the target machine actively refused it. [::ffff:127.0.0.1]:25
   at System.Net.Sockets.Socket.DoConnect(EndPoint endPointSnapshot, SocketAddress socketAddress)
   at System.Net.Sockets.Socket.Connect(EndPoint remoteEP)
   at System.Net.Sockets.TcpClient.Connect(IPEndPoint remoteEP)
   at System.Net.Sockets.TcpClient.Connect(String hostname, Int32 port)
--- End of stack trace from previous location where exception was thrown ---
   at System.Net.Sockets.TcpClient.Connect(String hostname, Int32 port)
   at System.Net.Mail.SmtpConnection.GetConnection(String host, Int32 port)
   at System.Net.Mail.SmtpTransport.GetConnection(String host, Int32 port)
   at System.Net.Mail.SmtpClient.GetConnection()
   at System.Net.Mail.SmtpClient.Send(MailMessage message)
   --- End of inner exception stack trace ---
   at System.Net.Mail.SmtpClient.Send(MailMessage message)
   at Abp.Net.Mail.Smtp.SmtpEmailSender.SendEmail(MailMessage mail)
   at Abp.Net.Mail.EmailSenderBase.Send(MailMessage mail, Boolean normalize)
   at Abp.Net.Mail.EmailSenderBase.Send(String to, String subject, String body, Boolean isBodyHtml)
   at MySystem.ChatAppService.MessageAppService.SendNotificationsAsync(UserNotification[] userNotifications) in D:\WorkSpace\MySystem\aspnet-core\src\MySystem.Application\ChatAppService\MessageAppService.cs:line 172
   at Abp.Notifications.DefaultNotificationDistributer.NotifyAsync(UserNotification[] userNotifications)
WARN  2020-07-05 13:30:09,049 [10   ] fications.DefaultNotificationDistributer - System.Net.Mail.SmtpException: Failure sending mail.
 ---> System.Net.Internals.SocketExceptionFactory+ExtendedSocketException (10061): No connection could be made because the target machine actively refused it. [::ffff:127.0.0.1]:25
   at System.Net.Sockets.Socket.DoConnect(EndPoint endPointSnapshot, SocketAddress socketAddress)
   at System.Net.Sockets.Socket.Connect(EndPoint remoteEP)
   at System.Net.Sockets.TcpClient.Connect(IPEndPoint remoteEP)
   at System.Net.Sockets.TcpClient.Connect(String hostname, Int32 port)
--- End of stack trace from previous location where exception was thrown ---
   at System.Net.Sockets.TcpClient.Connect(String hostname, Int32 port)
   at System.Net.Mail.SmtpConnection.GetConnection(String host, Int32 port)
   at System.Net.Mail.SmtpTransport.GetConnection(String host, Int32 port)
   at System.Net.Mail.SmtpClient.GetConnection()
   at System.Net.Mail.SmtpClient.Send(MailMessage message)
   --- End of inner exception stack trace ---
   at System.Net.Mail.SmtpClient.Send(MailMessage message)
   at Abp.Net.Mail.Smtp.SmtpEmailSender.SendEmail(MailMessage mail)
   at Abp.Net.Mail.EmailSenderBase.Send(MailMessage mail, Boolean normalize)
   at Abp.Net.Mail.EmailSenderBase.Send(String to, String subject, String body, Boolean isBodyHtml)
   at MySystem.ChatAppService.MessageAppService.SendNotificationsAsync(UserNotification[] userNotifications) in D:\WorkSpace\MySystem\aspnet-core\src\MySystem.Application\ChatAppService\MessageAppService.cs:line 172
   at Abp.Notifications.DefaultNotificationDistributer.NotifyAsync(UserNotification[] userNotifications)
System.Net.Mail.SmtpException: Failure sending mail.
 ---> System.Net.Internals.SocketExceptionFactory+ExtendedSocketException (10061): No connection could be made because the target machine actively refused it. [::ffff:127.0.0.1]:25
   at System.Net.Sockets.Socket.DoConnect(EndPoint endPointSnapshot, SocketAddress socketAddress)
   at System.Net.Sockets.Socket.Connect(EndPoint remoteEP)
   at System.Net.Sockets.TcpClient.Connect(IPEndPoint remoteEP)
   at System.Net.Sockets.TcpClient.Connect(String hostname, Int32 port)
--- End of stack trace from previous location where exception was thrown ---
   at System.Net.Sockets.TcpClient.Connect(String hostname, Int32 port)
   at System.Net.Mail.SmtpConnection.GetConnection(String host, Int32 port)
   at System.Net.Mail.SmtpTransport.GetConnection(String host, Int32 port)
   at System.Net.Mail.SmtpClient.GetConnection()
   at System.Net.Mail.SmtpClient.Send(MailMessage message)
   --- End of inner exception stack trace ---
   at System.Net.Mail.SmtpClient.Send(MailMessage message)
   at Abp.Net.Mail.Smtp.SmtpEmailSender.SendEmail(MailMessage mail)
   at Abp.Net.Mail.EmailSenderBase.Send(MailMessage mail, Boolean normalize)
   at Abp.Net.Mail.EmailSenderBase.Send(String to, String subject, String body, Boolean isBodyHtml)
   at MySystem.ChatAppService.MessageAppService.SendNotificationsAsync(UserNotification[] userNotifications) in D:\WorkSpace\MySystem\aspnet-core\src\MySystem.Application\ChatAppService\MessageAppService.cs:line 172
   at Abp.Notifications.DefaultNotificationDistributer.NotifyAsync(UserNotification[] userNotifications)
ERROR 2020-07-05 13:30:28,176 [10   ] Mvc.ExceptionHandling.AbpExceptionFilter - Failure sending mail.
System.Net.Mail.SmtpException: Failure sending mail.
 ---> System.Net.Internals.SocketExceptionFactory+ExtendedSocketException (10061): No connection could be made because the target machine actively refused it. [::ffff:127.0.0.1]:25
   at System.Net.Sockets.Socket.DoConnect(EndPoint endPointSnapshot, SocketAddress socketAddress)
   at System.Net.Sockets.Socket.Connect(EndPoint remoteEP)
   at System.Net.Sockets.TcpClient.Connect(IPEndPoint remoteEP)
   at System.Net.Sockets.TcpClient.Connect(String hostname, Int32 port)
--- End of stack trace from previous location where exception was thrown ---
   at System.Net.Sockets.TcpClient.Connect(String hostname, Int32 port)
   at System.Net.Mail.SmtpConnection.GetConnection(String host, Int32 port)
   at System.Net.Mail.SmtpTransport.GetConnection(String host, Int32 port)
   at System.Net.Mail.SmtpClient.GetConnection()
   at System.Net.Mail.SmtpClient.Send(MailMessage message)
   --- End of inner exception stack trace ---
   at System.Net.Mail.SmtpClient.Send(MailMessage message)
   at Abp.Net.Mail.Smtp.SmtpEmailSender.SendEmail(MailMessage mail)
   at Abp.Net.Mail.EmailSenderBase.Send(MailMessage mail, Boolean normalize)
   at Abp.Net.Mail.EmailSenderBase.Send(String to, String subject, String body, Boolean isBodyHtml)
   at MySystem.ChatAppService.MessageAppService.CreateAsync(CreateMessageDto input) in D:\WorkSpace\MySystem\aspnet-core\src\MySystem.Application\ChatAppService\MessageAppService.cs:line 153
   at Abp.Authorization.AuthorizationInterceptor.InternalInterceptAsynchronous[TResult](IInvocation invocation)
   at Abp.Domain.Uow.UnitOfWorkInterceptor.InternalInterceptAsynchronous[TResult](IInvocation invocation)
   at Abp.Auditing.AuditingInterceptor.InternalInterceptAsynchronous[TResult](IInvocation invocation)
   at Abp.Runtime.Validation.Interception.ValidationInterceptor.InternalInterceptAsynchronous[TResult](IInvocation invocation)
   at lambda_method(Closure , Object )
   at Microsoft.Extensions.Internal.ObjectMethodExecutorAwaitable.Awaiter.GetResult()
   at Microsoft.AspNetCore.Mvc.Infrastructure.ActionMethodExecutor.AwaitableObjectResultExecutor.Execute(IActionResultTypeMapper mapper, ObjectMethodExecutor executor, Object controller, Object[] arguments)
   at Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.<InvokeActionMethodAsync>g__Awaited|12_0(ControllerActionInvoker invoker, ValueTask`1 actionResultValueTask)
   at Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.<InvokeNextActionFilterAsync>g__Awaited|10_0(ControllerActionInvoker invoker, Task lastTask, State next, Scope scope, Object state, Boolean isCompleted)
   at Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.Rethrow(ActionExecutedContextSealed context)
   at Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.Next(State& next, Scope& scope, Object& state, Boolean& isCompleted)
   at Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.<InvokeInnerFilterAsync>g__Awaited|13_0(ControllerActionInvoker invoker, Task lastTask, State next, Scope scope, Object state, Boolean isCompleted)
   at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.<InvokeNextExceptionFilterAsync>g__Awaited|25_0(ResourceInvoker invoker, Task lastTask, State next, Scope scope, Object state, Boolean isCompleted)
aaron
  • 17,311
  • 4
  • 27
  • 63
3202User
  • 371
  • 4
  • 19

1 Answers1

0

You do not show us enough information. What does UserNotification class contain? Is this your own class or ABP Framework's code?

The first obvious error I see is this piece of code:

UserNotification userNotifications = new UserNotification();
userNotifications.UserId = 10010;
//
userNotifications.Notification.TenantId = AbpSession.TenantId;
userNotifications.Notification.NotificationName = "test";

The Notification property does not seem to be initialized. I expected to see something like:

UserNotification userNotification = new UserNotification
{
   UserId = 10010,
   Notification = new Notification 
   {
     TenantId = AbpSession.TenantId,
     NotificationName = "test"
   }
};
    
  • UserNotification is ABP class and Notification part of UserNotification class . and I can't initialize Notification as you mentioned – 3202User Jul 05 '20 at 09:25
  • https://aspnetboilerplate.com/api-docs/html/T_Abp_Notifications_UserNotification.htm – 3202User Jul 05 '20 at 09:26