Example #1
0
    public override async Task HandleEvent(CqrsEvent <UserRegisteredEventParameters> cqrsEvent, CancellationToken cancellationToken = default)
    {
        // Events can be used to trigger multiple business activities.
        Logger.LogInformation("Notify User Registered Handler: Handled Event, {EventTypeName}.", cqrsEvent.GetType().FullName);

        await Task.CompletedTask;
    }
Example #2
0
        public HttpResponseMessage TroubleAlert(TroubleAlertEvent troubleInput)
        {
            if (troubleInput == null)
            {
                throw HttpStatusCode.NotFound.AsException();
            }

            try
            {
                troubleInput.DepartmentId = DepartmentId;
                troubleInput.UserId       = UserId;
                troubleInput.TimeStamp    = DateTime.UtcNow;

                CqrsEvent registerUnitPushEvent = new CqrsEvent();
                registerUnitPushEvent.Type = (int)CqrsEventTypes.TroubleAlert;
                registerUnitPushEvent.Data = ObjectSerialization.Serialize(troubleInput);

                _cqrsProvider.EnqueueCqrsEvent(registerUnitPushEvent);

                return(Request.CreateResponse(HttpStatusCode.Created));
            }
            catch (Exception ex)
            {
                Logging.LogException(ex);
                throw HttpStatusCode.InternalServerError.AsException();
            }

            throw HttpStatusCode.BadRequest.AsException();
        }
Example #3
0
        private async Task  OnCqrsEventQueueReceived(CqrsEvent cqrs)
        {
            _logger.LogInformation($"{Name}: System Queue Received with a type of {cqrs.Type}, starting processing...");
            await SystemQueueLogic.ProcessSystemQueueItem(cqrs);

            _logger.LogInformation($"{Name}: Finished processing of system queue item with type of {cqrs.Type}.");
        }
Example #4
0
        public async Task <ActionResult> TroubleAlert(TroubleAlertEvent troubleInput)
        {
            if (troubleInput == null)
            {
                return(NotFound());
            }

            try
            {
                troubleInput.DepartmentId = DepartmentId;
                troubleInput.UserId       = UserId;
                troubleInput.TimeStamp    = DateTime.UtcNow;

                CqrsEvent registerUnitPushEvent = new CqrsEvent();
                registerUnitPushEvent.Type = (int)CqrsEventTypes.TroubleAlert;
                registerUnitPushEvent.Data = ObjectSerialization.Serialize(troubleInput);

                await _cqrsProvider.EnqueueCqrsEventAsync(registerUnitPushEvent);

                return(CreatedAtAction(nameof(TroubleAlert), new { id = troubleInput.DepartmentId }, troubleInput));
            }
            catch (Exception ex)
            {
                Logging.LogException(ex);
                return(BadRequest());
            }

            return(BadRequest());
        }
Example #5
0
    public void EventWithParametersShouldAssignMessageIdWhenCreated()
    {
        // Arrange / Act
        var subject = new CqrsEvent <TestParameters>(_params, Constants.CorrelationId, Constants.CausationId);

        // Assert
        subject.MessageId.Should().NotBeEmpty();
    }
Example #6
0
    public void EventWithoutParametersShouldAssignCorrelationIdWhenCreated()
    {
        // Arrange / Act
        var subject = new CqrsEvent(Constants.CorrelationId, Constants.CausationId);

        // Assert
        subject.CorrelationId.Should().Be(Constants.CorrelationId);
    }
Example #7
0
            public void Handle(AuditEvent message)
            {
                CqrsEvent cqrsEvent = new CqrsEvent();

                cqrsEvent.Type = (int)CqrsEventTypes.AuditLog;
                cqrsEvent.Data = ObjectSerialization.Serialize(message);

                _cqrsProvider.EnqueueCqrsEvent(cqrsEvent);
            }
Example #8
0
    public void EventWithParametersShouldAssignParameters()
    {
        // Arrange / Act
        var subject = new CqrsEvent <TestParameters>(_params, Constants.CorrelationId, Constants.CausationId);

        // Assert
        subject.Params.Should().NotBeNull();
        subject.Params.Should().BeEquivalentTo(_params);
    }
Example #9
0
        public async Task <ActionResult <DeviceRegistrationResult> > RegisterDevice([FromBody] DeviceRegistrationInput registrationInput, CancellationToken cancellationToken)
        {
            if (this.ModelState.IsValid)
            {
                var result = new DeviceRegistrationResult();

                try
                {
                    if (registrationInput == null)
                    {
                        return(BadRequest());
                    }

                    var push = new PushUri();
                    push.UserId       = UserId;
                    push.PlatformType = registrationInput.Plt;

                    if (!String.IsNullOrWhiteSpace(registrationInput.Uri))
                    {
                        push.PushLocation = HttpUtility.UrlDecode(registrationInput.Uri);
                    }
                    else if (registrationInput.Plt == (int)Platforms.Android)
                    {
                        push.PushLocation = "Android";
                    }
                    else if (registrationInput.Plt == (int)Platforms.iPhone || registrationInput.Plt == (int)Platforms.iPad)
                    {
                        push.PushLocation = "Apple";
                    }

                    push.DeviceId     = registrationInput.Did;
                    push.Uuid         = registrationInput.Id;
                    push.DepartmentId = DepartmentId;

                    CqrsEvent registerUnitPushEvent = new CqrsEvent();
                    registerUnitPushEvent.Type = (int)CqrsEventTypes.PushRegistration;
                    registerUnitPushEvent.Data = ObjectSerialization.Serialize(push);

                    await _cqrsProvider.EnqueueCqrsEventAsync(registerUnitPushEvent);

                    result.Sfl = true;
                    result.Id  = push.PushUriId;

                    return(result);
                }
                catch (Exception ex)
                {
                    result.Sfl = false;
                    Framework.Logging.LogException(ex);

                    return(result);
                }
            }

            return(BadRequest());
        }
Example #10
0
        public async Task <Tuple <bool, string> > ProcessQueueMessage(Message message, CancellationToken token)
        {
            bool   success = true;
            string result  = "";

            if (message != null)
            {
                try
                {
                    var body = message.GetBody <string>();

                    if (!String.IsNullOrWhiteSpace(body))
                    {
                        CqrsEvent qi = null;
                        try
                        {
                            qi = ObjectSerialization.Deserialize <CqrsEvent>(body);
                        }
                        catch (Exception ex)
                        {
                            success = false;
                            result  = "Unable to parse message body Exception: " + ex.ToString();
                            //message.Complete();
                            await _client.CompleteAsync(message.SystemProperties.LockToken);
                        }

                        success = await ProcessPaymentQueueItem(qi);
                    }

                    try
                    {
                        if (success)
                        {
                            await _client.CompleteAsync(message.SystemProperties.LockToken);
                        }
                        //message.Complete();
                    }
                    catch (MessageLockLostException)
                    {
                    }
                }
                catch (Exception ex)
                {
                    Logging.LogException(ex);
                    Logging.SendExceptionEmail(ex, "PaymentQueueLogic");

                    await _client.AbandonAsync(message.SystemProperties.LockToken);

                    //message.Abandon();
                    success = false;
                    result  = ex.ToString();
                }
            }

            return(new Tuple <bool, string>(success, result));
        }
    public async Task MessageSenderCallsCorrectHandlerForEvent()
    {
        // Arrange
        var @event = new CqrsEvent <TestParameters>(new TestParameters(nameof(MessageSenderCallsCorrectHandlerForEvent)), Constants.CorrelationId, Constants.CausationId);

        // Act
        await Subject.Publish(@event, CancellationToken.None);

        // Assert
        await Verifier.Received(1).Receive(Arg.Is(@event.Params.Value));
    }
Example #12
0
    public async Task MessageSenderThrowsWhenNoHandlerRegisteredForEvent()
    {
        // Arrange
        var @event = new CqrsEvent <string>(string.Empty, Constants.CorrelationId, Constants.CausationId);

        // Act
        Func <Task> subjectResult = async() => { await Subject.Publish(@event, CancellationToken.None); };

        // Assert
        await subjectResult.Should().ThrowAsync <HandlerNotFoundException>()
        .WithMessage($"No concrete handlers for type '{typeof(ICqrsEventHandler<CqrsEvent<string>>).AssemblyQualifiedName}' could be found.");
    }
Example #13
0
        public static Tuple <bool, string> ProcessQueueMessage(BrokeredMessage message)
        {
            bool   success = true;
            string result  = "";

            if (message != null)
            {
                try
                {
                    var body = message.GetBody <string>();

                    if (!String.IsNullOrWhiteSpace(body))
                    {
                        CqrsEvent qi = null;
                        try
                        {
                            qi = ObjectSerialization.Deserialize <CqrsEvent>(body);
                        }
                        catch (Exception ex)
                        {
                            success = false;
                            result  = "Unable to parse message body Exception: " + ex.ToString();
                            message.Complete();
                        }

                        success = ProcessPaymentQueueItem(qi);
                    }

                    try
                    {
                        if (success)
                        {
                            message.Complete();
                        }
                    }
                    catch (MessageLockLostException)
                    {
                    }
                }
                catch (Exception ex)
                {
                    Logging.LogException(ex);
                    Logging.SendExceptionEmail(ex, "PaymentQueueLogic");

                    message.Abandon();
                    success = false;
                    result  = ex.ToString();
                }
            }

            return(new Tuple <bool, string>(success, result));
        }
Example #14
0
        public bool EnqueuePaymentEvent(CqrsEvent cqrsEvent)
        {
            if (Config.SystemBehaviorConfig.ServiceBusType == Config.ServiceBusTypes.Rabbit)
            {
                _rabbitOutboundQueueProvider.EnqueuePaymentEvent(cqrsEvent);
                return(true);
            }

            var             serializedObject = ObjectSerialization.Serialize(cqrsEvent);
            BrokeredMessage message          = new BrokeredMessage(serializedObject);

            message.MessageId = string.Format("{0}", cqrsEvent.EventId);

            return(SendMessage(_systemClient, message));
        }
Example #15
0
        public async Task <bool> EnqueuePaymentEventAsync(CqrsEvent cqrsEvent)
        {
            if (Config.SystemBehaviorConfig.ServiceBusType == Config.ServiceBusTypes.Rabbit)
            {
                _rabbitOutboundQueueProvider.EnqueuePaymentEvent(cqrsEvent);
                return(true);
            }

            var     serializedObject = ObjectSerialization.Serialize(cqrsEvent);
            Message message          = new Message(Encoding.UTF8.GetBytes(serializedObject));

            message.MessageId = string.Format("{0}", cqrsEvent.EventId);

            return(await SendMessageAsync(_systemClient, message));
        }
    public async Task MessageSenderCallsCorrectHandlerForEvents()
    {
        // Arrange
        var @event = new CqrsEvent <TestParameters>(new TestParameters(nameof(MessageSenderCallsCorrectHandlerForEvents)), Constants.CorrelationId, Constants.CausationId);
        var events = new List <CqrsEvent <TestParameters> >
        {
            @event
        };

        var enumerableEvents = events.AsEnumerable();

        // Act
        await Subject.Publish(enumerableEvents, CancellationToken.None);

        // Assert
        await Verifier.Received(1).Receive(@event.Params.Value);
    }
Example #17
0
        public async Task Save(IEnumerable <IEvent> events, CancellationToken cancellationToken = default(CancellationToken))
        {
            foreach (var @event in events)
            {
                CqrsEvent entity = new CqrsEvent()
                {
                    AggregateId = @event.Id,
                    Version     = @event.Version,
                    TimeStamp   = @event.TimeStamp,
                    Data        = JsonConvert.SerializeObject(@event),
                    EventType   = @event.GetType().ToString()
                };

                _cqrsEventReposiory.Insert(entity);

                await _publisher.Publish(@event, cancellationToken);
            }
        }
Example #18
0
        public async Task <ActionResult> NotifyNewChat([FromBody] NotifyChatInput notifyChatInput)
        {
            if (notifyChatInput != null && notifyChatInput.RecipientUserIds != null && notifyChatInput.RecipientUserIds.Count > 0)
            {
                var newChatEvent = new NewChatNotificationEvent();
                newChatEvent.Id               = notifyChatInput.Id;
                newChatEvent.GroupName        = notifyChatInput.GroupName;
                newChatEvent.Message          = notifyChatInput.Message;
                newChatEvent.RecipientUserIds = notifyChatInput.RecipientUserIds;
                newChatEvent.SendingUserId    = notifyChatInput.SendingUserId;
                newChatEvent.Type             = notifyChatInput.Type;

                CqrsEvent registerUnitPushEvent = new CqrsEvent();
                registerUnitPushEvent.Type      = (int)CqrsEventTypes.NewChatMessage;
                registerUnitPushEvent.Timestamp = DateTime.UtcNow;
                registerUnitPushEvent.Data      = ObjectSerialization.Serialize(newChatEvent);

                await _cqrsProvider.EnqueueCqrsEventAsync(registerUnitPushEvent);
            }

            return(Ok());
        }
Example #19
0
        public HttpResponseMessage NotifyNewChat([FromBody] NotifyChatInput notifyChatInput)
        {
            if (notifyChatInput != null && notifyChatInput.RecipientUserIds != null && notifyChatInput.RecipientUserIds.Count > 0)
            {
                var newChatEvent = new NewChatNotificationEvent();
                newChatEvent.Id               = notifyChatInput.Id;
                newChatEvent.GroupName        = notifyChatInput.GroupName;
                newChatEvent.Message          = notifyChatInput.Message;
                newChatEvent.RecipientUserIds = notifyChatInput.RecipientUserIds;
                newChatEvent.SendingUserId    = notifyChatInput.SendingUserId;
                newChatEvent.Type             = notifyChatInput.Type;

                CqrsEvent registerUnitPushEvent = new CqrsEvent();
                registerUnitPushEvent.Type      = (int)CqrsEventTypes.NewChatMessage;
                registerUnitPushEvent.Timestamp = DateTime.UtcNow;
                registerUnitPushEvent.Data      = ObjectSerialization.Serialize(newChatEvent);

                _cqrsProvider.EnqueueCqrsEvent(registerUnitPushEvent);
            }

            return(Request.CreateResponse(HttpStatusCode.OK));
        }
Example #20
0
        public async Task <IActionResult> Index()
        {
            Event stripeEvent = null;
            PaymentProviderEvent providerEvent = null;

            try
            {
                string json = await new StreamReader(HttpContext.Request.Body).ReadToEndAsync();
                stripeEvent = EventUtility.ConstructEvent(json, Request.Headers["Stripe-Signature"], PaymentProviderConfig.TestWebhookSigningKey, 300L, false);

                providerEvent = new PaymentProviderEvent();
                providerEvent.ProviderType = (int)PaymentMethods.Stripe;
                providerEvent.RecievedOn   = DateTime.UtcNow;
                providerEvent.Data         = JsonConvert.SerializeObject(stripeEvent);
                providerEvent.Processed    = false;
                providerEvent.CustomerId   = "SYSTEM";
            }
            catch (Exception ex)
            {
                Logging.LogException(ex);
                return(BadRequest());
            }

            if (stripeEvent == null)
            {
                return(BadRequest());
            }

            try
            {
                switch (stripeEvent.Type)
                {
                case "charge.succeeded":
                    var succeededCharge = JsonConvert.DeserializeObject <Charge>(stripeEvent.Data.RawObject.ToString());
                    providerEvent.CustomerId = succeededCharge.CustomerId;
                    providerEvent.Processed  = true;
                    providerEvent.Type       = typeof(Charge).FullName;

                    CqrsEvent stripeChargeSucceededEvent = new CqrsEvent();
                    stripeChargeSucceededEvent.Type = (int)CqrsEventTypes.StripeChargeSucceeded;
                    stripeChargeSucceededEvent.Data = stripeEvent.Data.RawObject.ToString();

#if !DEBUG
                    await _cqrsProvider.EnqueuePaymentEventAsync(stripeChargeSucceededEvent);
#else
                    await _paymentProviderService.ProcessStripePaymentAsync(succeededCharge);
#endif
                    break;

                case "charge.failed":
                    var failedCharge = JsonConvert.DeserializeObject <Charge>(stripeEvent.Data.RawObject.ToString());
                    providerEvent.CustomerId = failedCharge.CustomerId;
                    providerEvent.Type       = typeof(Charge).FullName;

                    CqrsEvent stripeChargeFailedEvent = new CqrsEvent();
                    stripeChargeFailedEvent.Type = (int)CqrsEventTypes.StripeChargeFailed;
                    stripeChargeFailedEvent.Data = stripeEvent.Data.RawObject.ToString();

#if !DEBUG
                    await _cqrsProvider.EnqueuePaymentEventAsync(stripeChargeFailedEvent);
#else
                    await _paymentProviderService.ProcessStripeChargeFailedAsync(failedCharge);
#endif
                    break;

                case "charge.refunded":
                    var refundedCharge = JsonConvert.DeserializeObject <Charge>(stripeEvent.Data.RawObject.ToString());
                    providerEvent.CustomerId = refundedCharge.CustomerId;
                    providerEvent.Type       = typeof(Charge).FullName;

                    CqrsEvent stripeChargeRefundedEvent = new CqrsEvent();
                    stripeChargeRefundedEvent.Type = (int)CqrsEventTypes.StripeChargeRefunded;
                    stripeChargeRefundedEvent.Data = stripeEvent.Data.RawObject.ToString();

#if !DEBUG
                    await _cqrsProvider.EnqueuePaymentEventAsync(stripeChargeRefundedEvent);
#else
                    await _paymentProviderService.ProcessStripeSubscriptionRefundAsync(refundedCharge);
#endif
                    break;

                case "customer.subscription.updated":
                    var updatedSubscription = JsonConvert.DeserializeObject <Subscription>(stripeEvent.Data.RawObject.ToString());
                    providerEvent.CustomerId = updatedSubscription.CustomerId;
                    providerEvent.Processed  = true;
                    providerEvent.Type       = typeof(Subscription).FullName;

                    CqrsEvent stripeSubUpdatedEvent = new CqrsEvent();
                    stripeSubUpdatedEvent.Type = (int)CqrsEventTypes.StripeSubUpdated;
                    stripeSubUpdatedEvent.Data = stripeEvent.Data.RawObject.ToString();

#if !DEBUG
                    await _cqrsProvider.EnqueuePaymentEventAsync(stripeSubUpdatedEvent);
#else
                    await _paymentProviderService.ProcessStripeSubscriptionUpdateAsync(updatedSubscription);
#endif
                    break;

                case "customer.subscription.deleted":
                    var deletedSubscription = JsonConvert.DeserializeObject <Subscription>(stripeEvent.Data.RawObject.ToString());
                    providerEvent.CustomerId = deletedSubscription.CustomerId;
                    providerEvent.Processed  = true;
                    providerEvent.Type       = typeof(Subscription).FullName;

                    CqrsEvent stripeSubDeletedEvent = new CqrsEvent();
                    stripeSubDeletedEvent.Type = (int)CqrsEventTypes.StripeSubDeleted;
                    stripeSubDeletedEvent.Data = stripeEvent.Data.RawObject.ToString();

#if !DEBUG
                    await _cqrsProvider.EnqueuePaymentEventAsync(stripeSubDeletedEvent);
#else
                    await _paymentProviderService.ProcessStripeSubscriptionCancellationAsync(deletedSubscription);
#endif

                    break;

                case "customer.subscription.created":
                    var createdSubscription = JsonConvert.DeserializeObject <Subscription>(stripeEvent.Data.RawObject.ToString());
                    providerEvent.CustomerId = createdSubscription.CustomerId;
                    providerEvent.Type       = typeof(Subscription).FullName;
                    break;

                case "checkout.session.completed":
                    var session = JsonConvert.DeserializeObject <Session>(stripeEvent.Data.RawObject.ToString());
                    providerEvent.CustomerId = session.CustomerId;
                    providerEvent.Processed  = true;
                    providerEvent.Type       = typeof(Session).FullName;

                    CqrsEvent stripeSessionCompletedEvent = new CqrsEvent();
                    stripeSessionCompletedEvent.Type = (int)CqrsEventTypes.StripeCheckoutCompleted;
                    stripeSessionCompletedEvent.Data = stripeEvent.Data.RawObject.ToString();

                    if (!String.IsNullOrWhiteSpace(session.Mode) && session.Mode.ToLower() == "setup")
                    {
                        var service     = new SetupIntentService();
                        var setupIntent = service.Get(session.SetupIntentId);
                        providerEvent.CustomerId = setupIntent.Metadata["customer_id"];

                        stripeSessionCompletedEvent.Type = (int)CqrsEventTypes.StripeCheckoutUpdated;
#if !DEBUG
                        await _cqrsProvider.EnqueuePaymentEventAsync(stripeSessionCompletedEvent);
#else
                        await _paymentProviderService.ProcessStripeCheckoutUpdateAsync(session);
#endif
                    }
                    break;
                }
            }
            catch (Exception ex)
            {
                Logging.LogException(ex);
                Logging.SendExceptionEmail(ex, "StripeHandler");
                return(BadRequest());
            }
            finally
            {
                await _paymentProviderService.SaveEventAsync(providerEvent);
            }

            return(Ok());
        }
        public void EnqueuePaymentEvent(CqrsEvent cqrsEvent)
        {
            var serializedObject = ObjectSerialization.Serialize(cqrsEvent);

            SendMessage(ServiceBusConfig.PaymentQueueName, serializedObject);
        }
Example #22
0
        public static bool ProcessPaymentQueueItem(CqrsEvent qi)
        {
            bool success = true;

            if (qi != null)
            {
                try
                {
                    switch ((CqrsEventTypes)qi.Type)
                    {
                    case CqrsEventTypes.None:
                        break;

                    case CqrsEventTypes.StripeChargeSucceeded:
                        var succeededCharge = JsonConvert.DeserializeObject <Charge>(qi.Data);

                        if (succeededCharge != null)
                        {
                            var paymentProviderService = Bootstrapper.GetKernel().Resolve <IPaymentProviderService>();

                            paymentProviderService.ProcessStripePayment(succeededCharge);
                        }
                        break;

                    case CqrsEventTypes.StripeChargeFailed:
                        var failedCharge = JsonConvert.DeserializeObject <Charge>(qi.Data);

                        if (failedCharge != null)
                        {
                            var paymentProviderService = Bootstrapper.GetKernel().Resolve <IPaymentProviderService>();

                            paymentProviderService.ProcessStripeChargeFailed(failedCharge);
                        }
                        break;

                    case CqrsEventTypes.StripeChargeRefunded:
                        var refundedCharge = JsonConvert.DeserializeObject <Charge>(qi.Data);

                        if (refundedCharge != null)
                        {
                            var paymentProviderService = Bootstrapper.GetKernel().Resolve <IPaymentProviderService>();

                            paymentProviderService.ProcessStripeSubscriptionRefund(refundedCharge);
                        }
                        break;

                    case CqrsEventTypes.StripeSubUpdated:
                        var updatedSubscription = JsonConvert.DeserializeObject <Subscription>(qi.Data);

                        if (updatedSubscription != null)
                        {
                            var paymentProviderService = Bootstrapper.GetKernel().Resolve <IPaymentProviderService>();

                            paymentProviderService.ProcessStripeSubscriptionUpdate(updatedSubscription);
                        }
                        break;

                    case CqrsEventTypes.StripeSubDeleted:
                        var deletedSubscription = JsonConvert.DeserializeObject <Subscription>(qi.Data);

                        if (deletedSubscription != null)
                        {
                            var paymentProviderService = Bootstrapper.GetKernel().Resolve <IPaymentProviderService>();

                            paymentProviderService.ProcessStripeSubscriptionCancellation(deletedSubscription);
                        }
                        break;

                    case CqrsEventTypes.StripeCheckoutCompleted:
                        var stripeCheckoutSession = JsonConvert.DeserializeObject <Session>(qi.Data);

                        if (stripeCheckoutSession != null)
                        {
                            var paymentProviderService = Bootstrapper.GetKernel().Resolve <IPaymentProviderService>();

                            paymentProviderService.ProcessStripeCheckoutCompleted(stripeCheckoutSession);
                        }
                        break;

                    case CqrsEventTypes.StripeCheckoutUpdated:
                        var stripeCheckoutSessionUpdated = JsonConvert.DeserializeObject <Session>(qi.Data);

                        if (stripeCheckoutSessionUpdated != null)
                        {
                            var paymentProviderService = Bootstrapper.GetKernel().Resolve <IPaymentProviderService>();

                            paymentProviderService.ProcessStripeCheckoutUpdate(stripeCheckoutSessionUpdated);
                        }
                        break;

                    default:
                        throw new ArgumentOutOfRangeException();
                    }
                }
                catch (Exception ex)
                {
                    Logging.LogException(ex);
                    Logging.SendExceptionEmail(ex, "ProcessPaymentQueueItem");
                }
            }

            return(success);
        }
Example #23
0
 public override async Task HandleEvent(CqrsEvent <MessageParameters> cqrsEvent, CancellationToken cancellationToken = default)
 {
     await Task.CompletedTask;
 }
        public bool EnqueueCqrsEvent(CqrsEvent cqrsEvent)
        {
            var serializedObject = ObjectSerialization.Serialize(cqrsEvent);

            return(SendMessage(ServiceBusConfig.SystemQueueName, serializedObject));
        }
Example #25
0
        private async Task StartMonitoring()
        {
            if (SystemBehaviorConfig.ServiceBusType == ServiceBusTypes.Rabbit)
            {
                var callQueueReceivedConsumer = new EventingBasicConsumer(_channel);
                callQueueReceivedConsumer.Received += async(model, ea) =>
                {
                    if (ea != null && ea.Body.Length > 0)
                    {
                        CallQueueItem cqi = null;
                        try
                        {
                            var body    = ea.Body;
                            var message = Encoding.UTF8.GetString(body.ToArray());
                            cqi = ObjectSerialization.Deserialize <CallQueueItem>(message);
                        }
                        catch (Exception ex)
                        {
                            _channel.BasicNack(ea.DeliveryTag, false, false);
                            Logging.LogException(ex, Encoding.UTF8.GetString(ea.Body.ToArray()));
                        }

                        try
                        {
                            if (cqi != null)
                            {
                                if (CallQueueReceived != null)
                                {
                                    await CallQueueReceived.Invoke(cqi);

                                    _channel.BasicAck(ea.DeliveryTag, false);
                                }
                            }
                        }
                        catch (Exception ex)
                        {
                            Logging.LogException(ex);
                            if (RetryQueueItem(ea, ex))
                            {
                                _channel.BasicNack(ea.DeliveryTag, false, false);
                            }
                            else
                            {
                                _channel.BasicNack(ea.DeliveryTag, false, true);
                            }
                        }
                    }
                };

                var messageQueueReceivedConsumer = new EventingBasicConsumer(_channel);
                messageQueueReceivedConsumer.Received += async(model, ea) =>
                {
                    if (ea != null && ea.Body.Length > 0)
                    {
                        MessageQueueItem mqi = null;
                        try
                        {
                            var body    = ea.Body;
                            var message = Encoding.UTF8.GetString(body.ToArray());
                            mqi = ObjectSerialization.Deserialize <MessageQueueItem>(message);
                        }
                        catch (Exception ex)
                        {
                            _channel.BasicNack(ea.DeliveryTag, false, false);
                            Logging.LogException(ex, Encoding.UTF8.GetString(ea.Body.ToArray()));
                        }

                        try
                        {
                            if (mqi != null)
                            {
                                if (MessageQueueReceived != null)
                                {
                                    await MessageQueueReceived.Invoke(mqi);

                                    _channel.BasicAck(ea.DeliveryTag, false);
                                }
                            }
                        }
                        catch (Exception ex)
                        {
                            Logging.LogException(ex);
                            if (RetryQueueItem(ea, ex))
                            {
                                _channel.BasicAck(ea.DeliveryTag, false);
                            }
                            else
                            {
                                _channel.BasicNack(ea.DeliveryTag, false, true);
                            }
                        }
                    }
                };

                var distributionListQueueReceivedConsumer = new EventingBasicConsumer(_channel);
                distributionListQueueReceivedConsumer.Received += async(model, ea) =>
                {
                    if (ea != null && ea.Body.Length > 0)
                    {
                        DistributionListQueueItem dlqi = null;
                        try
                        {
                            var body    = ea.Body;
                            var message = Encoding.UTF8.GetString(body.ToArray());
                            dlqi = ObjectSerialization.Deserialize <DistributionListQueueItem>(message);
                        }
                        catch (Exception ex)
                        {
                            _channel.BasicNack(ea.DeliveryTag, false, false);
                            Logging.LogException(ex, Encoding.UTF8.GetString(ea.Body.ToArray()));
                        }

                        try
                        {
                            if (dlqi != null)
                            {
                                if (DistributionListQueueReceived != null)
                                {
                                    await DistributionListQueueReceived.Invoke(dlqi);

                                    _channel.BasicAck(ea.DeliveryTag, false);
                                }
                            }
                        }
                        catch (Exception ex)
                        {
                            Logging.LogException(ex);
                            if (RetryQueueItem(ea, ex))
                            {
                                _channel.BasicAck(ea.DeliveryTag, false);
                            }
                            else
                            {
                                _channel.BasicNack(ea.DeliveryTag, false, true);
                            }
                        }
                    }
                };

                var notificationQueueReceivedConsumer = new EventingBasicConsumer(_channel);
                notificationQueueReceivedConsumer.Received += async(model, ea) =>
                {
                    if (ea != null && ea.Body.Length > 0)
                    {
                        NotificationItem ni = null;
                        try
                        {
                            var body    = ea.Body;
                            var message = Encoding.UTF8.GetString(body.ToArray());
                            ni = ObjectSerialization.Deserialize <NotificationItem>(message);
                        }
                        catch (Exception ex)
                        {
                            _channel.BasicNack(ea.DeliveryTag, false, false);
                            Logging.LogException(ex, Encoding.UTF8.GetString(ea.Body.ToArray()));
                        }

                        try
                        {
                            if (ni != null)
                            {
                                if (NotificationQueueReceived != null)
                                {
                                    await NotificationQueueReceived.Invoke(ni);

                                    _channel.BasicAck(ea.DeliveryTag, false);
                                }
                            }
                        }
                        catch (Exception ex)
                        {
                            Logging.LogException(ex);
                            if (RetryQueueItem(ea, ex))
                            {
                                _channel.BasicAck(ea.DeliveryTag, false);
                            }
                            else
                            {
                                _channel.BasicNack(ea.DeliveryTag, false, true);
                            }
                        }
                    }
                };

                var shiftNotificationQueueReceivedConsumer = new EventingBasicConsumer(_channel);
                shiftNotificationQueueReceivedConsumer.Received += async(model, ea) =>
                {
                    if (ea != null && ea.Body.Length > 0)
                    {
                        ShiftQueueItem sqi = null;
                        try
                        {
                            var body    = ea.Body;
                            var message = Encoding.UTF8.GetString(body.ToArray());
                            sqi = ObjectSerialization.Deserialize <ShiftQueueItem>(message);
                        }
                        catch (Exception ex)
                        {
                            _channel.BasicNack(ea.DeliveryTag, false, false);
                            Logging.LogException(ex, Encoding.UTF8.GetString(ea.Body.ToArray()));
                        }

                        try
                        {
                            if (sqi != null)
                            {
                                if (ShiftNotificationQueueReceived != null)
                                {
                                    await ShiftNotificationQueueReceived.Invoke(sqi);

                                    _channel.BasicAck(ea.DeliveryTag, false);
                                }
                            }
                        }
                        catch (Exception ex)
                        {
                            Logging.LogException(ex);
                            if (RetryQueueItem(ea, ex))
                            {
                                _channel.BasicAck(ea.DeliveryTag, false);
                            }
                            else
                            {
                                _channel.BasicNack(ea.DeliveryTag, false, true);
                            }
                        }
                    }
                };

                var cqrsEventQueueReceivedConsumer = new EventingBasicConsumer(_channel);
                cqrsEventQueueReceivedConsumer.Received += async(model, ea) =>
                {
                    if (ea != null && ea.Body.Length > 0)
                    {
                        CqrsEvent cqrs = null;
                        try
                        {
                            var body    = ea.Body;
                            var message = Encoding.UTF8.GetString(body.ToArray());
                            cqrs = ObjectSerialization.Deserialize <CqrsEvent>(message);
                        }
                        catch (Exception ex)
                        {
                            _channel.BasicNack(ea.DeliveryTag, false, false);
                            Logging.LogException(ex, Encoding.UTF8.GetString(ea.Body.ToArray()));
                        }

                        try
                        {
                            if (cqrs != null)
                            {
                                if (CqrsEventQueueReceived != null)
                                {
                                    await CqrsEventQueueReceived.Invoke(cqrs);

                                    _channel.BasicAck(ea.DeliveryTag, false);
                                }
                            }
                        }
                        catch (Exception ex)
                        {
                            Logging.LogException(ex);
                            if (RetryQueueItem(ea, ex))
                            {
                                _channel.BasicAck(ea.DeliveryTag, false);
                            }
                            else
                            {
                                _channel.BasicNack(ea.DeliveryTag, false, true);
                            }
                        }
                    }
                };

                var paymentEventQueueReceivedConsumer = new EventingBasicConsumer(_channel);
                paymentEventQueueReceivedConsumer.Received += async(model, ea) =>
                {
                    if (ea != null && ea.Body.Length > 0)
                    {
                        CqrsEvent cqrs = null;
                        try
                        {
                            var body    = ea.Body;
                            var message = Encoding.UTF8.GetString(body.ToArray());
                            cqrs = ObjectSerialization.Deserialize <CqrsEvent>(message);
                        }
                        catch (Exception ex)
                        {
                            _channel.BasicNack(ea.DeliveryTag, false, false);
                            Logging.LogException(ex, Encoding.UTF8.GetString(ea.Body.ToArray()));
                        }

                        try
                        {
                            if (cqrs != null)
                            {
                                if (PaymentEventQueueReceived != null)
                                {
                                    await PaymentEventQueueReceived.Invoke(cqrs);

                                    _channel.BasicAck(ea.DeliveryTag, false);
                                }
                            }
                        }
                        catch (Exception ex)
                        {
                            Logging.LogException(ex);
                            if (RetryQueueItem(ea, ex))
                            {
                                _channel.BasicAck(ea.DeliveryTag, false);
                            }
                            else
                            {
                                _channel.BasicNack(ea.DeliveryTag, false, true);
                            }
                        }
                    }
                };


                String callQueueReceivedConsumerTag = _channel.BasicConsume(
                    queue: SetQueueNameForEnv(ServiceBusConfig.CallBroadcastQueueName),
                    autoAck: false,
                    consumer: callQueueReceivedConsumer);

                String messageQueueReceivedConsumerTag = _channel.BasicConsume(
                    queue: SetQueueNameForEnv(ServiceBusConfig.MessageBroadcastQueueName),
                    autoAck: false,
                    consumer: messageQueueReceivedConsumer);

                String distributionListQueueReceivedConsumerTag = _channel.BasicConsume(
                    queue: SetQueueNameForEnv(ServiceBusConfig.EmailBroadcastQueueName),
                    autoAck: false,
                    consumer: distributionListQueueReceivedConsumer);

                String notificationQueueReceivedConsumerTag = _channel.BasicConsume(
                    queue: SetQueueNameForEnv(ServiceBusConfig.NotificaitonBroadcastQueueName),
                    autoAck: false,
                    consumer: notificationQueueReceivedConsumer);

                String shiftNotificationQueueReceivedConsumerTag = _channel.BasicConsume(
                    queue: SetQueueNameForEnv(ServiceBusConfig.ShiftNotificationsQueueName),
                    autoAck: false,
                    consumer: shiftNotificationQueueReceivedConsumer);

                String cqrsEventQueueReceivedConsumerTag = _channel.BasicConsume(
                    queue: SetQueueNameForEnv(ServiceBusConfig.SystemQueueName),
                    autoAck: false,
                    consumer: cqrsEventQueueReceivedConsumer);

                String paymentEventQueueReceivedConsumerTag = _channel.BasicConsume(
                    queue: SetQueueNameForEnv(ServiceBusConfig.PaymentQueueName),
                    autoAck: false,
                    consumer: paymentEventQueueReceivedConsumer);
            }
        }
Example #26
0
        public async Task <ActionResult> SetUnitLocation(UnitLocationInput locationInput, CancellationToken cancellationToken)
        {
            var unit = await _unitsService.GetUnitByIdAsync(locationInput.Uid);

            if (unit == null)
            {
                return(NotFound());
            }

            if (unit.DepartmentId != DepartmentId)
            {
                return(Unauthorized());
            }

            if (this.ModelState.IsValid)
            {
                try
                {
                    CqrsEvent    locationEvent = new CqrsEvent();
                    UnitLocation location      = new UnitLocation();
                    location.UnitId = locationInput.Uid;

                    if (locationInput.Tms.HasValue)
                    {
                        location.Timestamp = locationInput.Tms.Value;
                    }
                    else
                    {
                        location.Timestamp = DateTime.UtcNow;
                    }

                    if (!String.IsNullOrWhiteSpace(locationInput.Lat) && locationInput.Lat != "NaN" && !String.IsNullOrWhiteSpace(locationInput.Lon) && locationInput.Lon != "NaN")
                    {
                        location.Latitude  = decimal.Parse(locationInput.Lat);
                        location.Longitude = decimal.Parse(locationInput.Lon);

                        if (!String.IsNullOrWhiteSpace(locationInput.Acc) && locationInput.Acc != "NaN")
                        {
                            location.Accuracy = decimal.Parse(locationInput.Acc);
                        }

                        if (!String.IsNullOrWhiteSpace(locationInput.Alt) && locationInput.Alt != "NaN")
                        {
                            location.Altitude = decimal.Parse(locationInput.Alt);
                        }

                        if (!String.IsNullOrWhiteSpace(locationInput.Alc) && locationInput.Alc != "NaN")
                        {
                            location.AltitudeAccuracy = decimal.Parse(locationInput.Alc);
                        }

                        if (!String.IsNullOrWhiteSpace(locationInput.Spd) && locationInput.Spd != "NaN")
                        {
                            location.Speed = decimal.Parse(locationInput.Spd);
                        }

                        if (!String.IsNullOrWhiteSpace(locationInput.Hdn) && locationInput.Hdn != "NaN")
                        {
                            location.Heading = decimal.Parse(locationInput.Hdn);
                        }

                        locationEvent.Type = (int)CqrsEventTypes.UnitLocation;
                        locationEvent.Data = ObjectSerialization.Serialize(location);
                        await _cqrsProvider.EnqueueCqrsEventAsync(locationEvent);

                        return(CreatedAtAction(nameof(SetUnitLocation), new { id = locationInput.Uid }, locationEvent));
                    }
                    else
                    {
                        return(Ok());
                    }
                }
                catch (Exception ex)
                {
                    Logging.LogException(ex);
                    return(BadRequest());
                }
            }

            return(BadRequest());
        }
Example #27
0
        public static bool ProcessSystemQueueItem(CqrsEvent qi)
        {
            bool success = true;

            if (qi != null)
            {
                switch ((CqrsEventTypes)qi.Type)
                {
                case CqrsEventTypes.None:
                    break;

                case CqrsEventTypes.UnitLocation:
                    UnitLocation unitLocation = null;
                    try
                    {
                        unitLocation = ObjectSerialization.Deserialize <UnitLocation>(qi.Data);
                    }
                    catch (Exception ex)
                    {
                    }

                    if (unitLocation != null)
                    {
                        IUnitsService unitService;
                        try
                        {
                            unitService = Bootstrapper.GetKernel().Resolve <IUnitsService>();
                            unitService.AddUnitLocation(unitLocation);
                        }
                        catch (Exception ex)
                        {
                        }
                        finally
                        {
                            unitService = null;
                        }
                    }
                    break;

                case CqrsEventTypes.PushRegistration:

                    PushUri data = null;
                    try
                    {
                        data = ObjectSerialization.Deserialize <PushUri>(qi.Data);
                    }
                    catch (Exception ex)
                    {
                    }

                    if (data != null)
                    {
                        var pushService     = Bootstrapper.GetKernel().Resolve <IPushService>();
                        var resgriterResult = pushService.Register(data).Result;

                        pushService = null;
                    }
                    break;

                case CqrsEventTypes.UnitPushRegistration:
                    PushRegisterionEvent unitData = null;
                    try
                    {
                        unitData = ObjectSerialization.Deserialize <PushRegisterionEvent>(qi.Data);
                    }
                    catch (Exception ex)
                    {
                    }

                    if (unitData != null)
                    {
                        PushUri pushUri = new PushUri();
                        pushUri.PushUriId    = unitData.PushUriId;
                        pushUri.UserId       = unitData.UserId;
                        pushUri.PlatformType = unitData.PlatformType;
                        pushUri.PushLocation = unitData.PushLocation;
                        pushUri.DepartmentId = unitData.DepartmentId;
                        pushUri.UnitId       = unitData.UnitId;
                        pushUri.DeviceId     = unitData.DeviceId;
                        pushUri.Uuid         = unitData.Uuid;

                        var pushService = Bootstrapper.GetKernel().Resolve <IPushService>();
                        var unitResult  = pushService.RegisterUnit(pushUri).Result;

                        pushService = null;
                    }
                    break;

                case CqrsEventTypes.StripeChargeSucceeded:
                    var succeededCharge = Stripe.Mapper <StripeCharge> .MapFromJson(qi.Data);

                    if (succeededCharge != null)
                    {
                        var paymentProviderService = Bootstrapper.GetKernel().Resolve <IPaymentProviderService>();

                        paymentProviderService.ProcessStripePayment(succeededCharge);
                    }
                    break;

                case CqrsEventTypes.StripeChargeFailed:
                    var failedCharge = Stripe.Mapper <StripeCharge> .MapFromJson(qi.Data);

                    if (failedCharge != null)
                    {
                        var paymentProviderService = Bootstrapper.GetKernel().Resolve <IPaymentProviderService>();

                        paymentProviderService.ProcessStripeChargeFailed(failedCharge);
                    }
                    break;

                case CqrsEventTypes.StripeChargeRefunded:
                    var refundedCharge = Stripe.Mapper <StripeCharge> .MapFromJson(qi.Data);

                    if (refundedCharge != null)
                    {
                        var paymentProviderService = Bootstrapper.GetKernel().Resolve <IPaymentProviderService>();

                        paymentProviderService.ProcessStripeSubscriptionRefund(refundedCharge);
                    }
                    break;

                case CqrsEventTypes.StripeSubUpdated:
                    var updatedSubscription = Stripe.Mapper <StripeSubscription> .MapFromJson(qi.Data);

                    if (updatedSubscription != null)
                    {
                        var paymentProviderService = Bootstrapper.GetKernel().Resolve <IPaymentProviderService>();

                        paymentProviderService.ProcessStripeSubscriptionUpdate(updatedSubscription);
                    }
                    break;

                case CqrsEventTypes.StripeSubDeleted:
                    var deletedSubscription = Stripe.Mapper <StripeSubscription> .MapFromJson(qi.Data);

                    if (deletedSubscription != null)
                    {
                        var paymentProviderService = Bootstrapper.GetKernel().Resolve <IPaymentProviderService>();

                        paymentProviderService.ProcessStripeSubscriptionCancellation(deletedSubscription);
                    }
                    break;

                case CqrsEventTypes.ClearDepartmentCache:

                    int departmentId;

                    if (int.TryParse(qi.Data, out departmentId))
                    {
                        var userProfileService = Bootstrapper.GetKernel().Resolve <IUserProfileService>();
                        //var departmentSettingsService = Bootstrapper.GetKernel().Resolve<IDepartmentSettingsService>();
                        var subscriptionService = Bootstrapper.GetKernel().Resolve <ISubscriptionsService>();
                        //var scheduledTasksService = Bootstrapper.GetKernel().Resolve<IScheduledTasksService>();
                        var departmentService   = Bootstrapper.GetKernel().Resolve <IDepartmentsService>();
                        var actionLogsService   = Bootstrapper.GetKernel().Resolve <IActionLogsService>();
                        var customStatesService = Bootstrapper.GetKernel().Resolve <ICustomStateService>();
                        var usersService        = Bootstrapper.GetKernel().Resolve <IUsersService>();

                        subscriptionService.ClearCacheForCurrentPayment(departmentId);
                        departmentService.InvalidateDepartmentUsersInCache(departmentId);
                        departmentService.InvalidateDepartmentInCache(departmentId);
                        departmentService.InvalidatePersonnelNamesInCache(departmentId);
                        userProfileService.ClearAllUserProfilesFromCache(departmentId);
                        usersService.ClearCacheForDepartment(departmentId);
                        actionLogsService.InvalidateActionLogs(departmentId);
                        customStatesService.InvalidateCustomStateInCache(departmentId);
                        departmentService.InvalidateDepartmentMembers();

                        userProfileService  = null;
                        subscriptionService = null;
                        departmentService   = null;
                        actionLogsService   = null;
                        customStatesService = null;
                        usersService        = null;
                    }
                    else
                    {
                    }
                    break;

                case CqrsEventTypes.NewChatMessage:
                    NewChatNotificationEvent newChatEvent = null;

                    if (qi != null && !String.IsNullOrWhiteSpace(qi.Data))
                    {
                        try
                        {
                            newChatEvent = ObjectSerialization.Deserialize <NewChatNotificationEvent>(qi.Data);
                        }
                        catch (Exception ex)
                        {
                        }

                        if (newChatEvent != null)
                        {
                            var userProfileService   = Bootstrapper.GetKernel().Resolve <IUserProfileService>();
                            var communicationService = Bootstrapper.GetKernel().Resolve <ICommunicationService>();
                            var usersService         = Bootstrapper.GetKernel().Resolve <IUsersService>();


                            if (newChatEvent != null && newChatEvent.RecipientUserIds != null && newChatEvent.RecipientUserIds.Count > 0)
                            {
                                List <UserProfile> profiles = new List <UserProfile>();
                                if (newChatEvent.RecipientUserIds.Count == 1)
                                {
                                    profiles.Add(userProfileService.GetProfileByUserId(newChatEvent.RecipientUserIds.First()));
                                }
                                else
                                {
                                    profiles.AddRange(userProfileService.GetSelectedUserProfiles(newChatEvent.RecipientUserIds));
                                }

                                var sendingUserProfile = userProfileService.GetProfileByUserId(newChatEvent.SendingUserId);

                                var chatResult = communicationService.SendChat(newChatEvent.Id, newChatEvent.SendingUserId, newChatEvent.GroupName, newChatEvent.Message, sendingUserProfile, profiles).Result;
                            }

                            userProfileService   = null;
                            communicationService = null;
                            usersService         = null;
                        }
                    }
                    break;

                case CqrsEventTypes.TroubleAlert:
                    TroubleAlertEvent troubleAlertEvent = null;
                    try
                    {
                        troubleAlertEvent = ObjectSerialization.Deserialize <TroubleAlertEvent>(qi.Data);
                    }
                    catch (Exception ex)
                    {
                    }

                    if (troubleAlertEvent != null && troubleAlertEvent.DepartmentId.HasValue)
                    {
                        var userProfileService        = Bootstrapper.GetKernel().Resolve <IUserProfileService>();
                        var communicationService      = Bootstrapper.GetKernel().Resolve <ICommunicationService>();
                        var usersService              = Bootstrapper.GetKernel().Resolve <IUsersService>();
                        var departmentService         = Bootstrapper.GetKernel().Resolve <IDepartmentsService>();
                        var unitsService              = Bootstrapper.GetKernel().Resolve <IUnitsService>();
                        var departmentGroupService    = Bootstrapper.GetKernel().Resolve <IDepartmentGroupsService>();
                        var callsService              = Bootstrapper.GetKernel().Resolve <ICallsService>();
                        var departmentSettingsService = Bootstrapper.GetKernel().Resolve <IDepartmentSettingsService>();
                        var geoLocationProvider       = Bootstrapper.GetKernel().Resolve <IGeoLocationProvider>();

                        var admins = departmentService.GetAllAdminsForDepartment(troubleAlertEvent.DepartmentId.Value);
                        var unit   = unitsService.GetUnitById(troubleAlertEvent.UnitId);
                        List <UserProfile> profiles = new List <UserProfile>();
                        Call   call             = null;
                        string departmentNumber = "";
                        string callAddress      = "No Call Address";
                        string unitAproxAddress = "Unknown Unit Address";

                        departmentNumber = departmentSettingsService.GetTextToCallNumberForDepartment(troubleAlertEvent.DepartmentId.Value);

                        if (admins != null)
                        {
                            profiles.AddRange(userProfileService.GetSelectedUserProfiles(admins.Select(x => x.Id).ToList()));
                        }

                        if (unit != null)
                        {
                            if (unit.StationGroupId.HasValue)
                            {
                                var groupAdmins = departmentGroupService.GetAllAdminsForGroup(unit.StationGroupId.Value);

                                if (groupAdmins != null)
                                {
                                    profiles.AddRange(userProfileService.GetSelectedUserProfiles(groupAdmins.Select(x => x.UserId).ToList()));
                                }
                            }

                            if (troubleAlertEvent.CallId.HasValue && troubleAlertEvent.CallId.GetValueOrDefault() > 0)
                            {
                                call = callsService.GetCallById(troubleAlertEvent.CallId.Value);

                                if (!String.IsNullOrEmpty(call.Address))
                                {
                                    callAddress = call.Address;
                                }
                                else if (!String.IsNullOrEmpty(call.GeoLocationData))
                                {
                                    string[] points = call.GeoLocationData.Split(char.Parse(","));

                                    if (points != null && points.Length == 2)
                                    {
                                        callAddress = geoLocationProvider.GetAproxAddressFromLatLong(double.Parse(points[0]), double.Parse(points[1]));
                                    }
                                }
                            }

                            if (!String.IsNullOrWhiteSpace(troubleAlertEvent.Latitude) && !String.IsNullOrWhiteSpace(troubleAlertEvent.Longitude))
                            {
                                unitAproxAddress = geoLocationProvider.GetAproxAddressFromLatLong(double.Parse(troubleAlertEvent.Latitude), double.Parse(troubleAlertEvent.Longitude));
                            }

                            communicationService.SendTroubleAlert(troubleAlertEvent, unit, call, departmentNumber, troubleAlertEvent.DepartmentId.Value, callAddress, unitAproxAddress, profiles);
                        }
                    }

                    break;

                case CqrsEventTypes.AuditLog:
                    AuditEvent auditEvent = null;
                    try
                    {
                        auditEvent = ObjectSerialization.Deserialize <AuditEvent>(qi.Data);
                    }
                    catch (Exception ex)
                    {
                    }

                    if (auditEvent != null)
                    {
                        var auditLogsRepository = Bootstrapper.GetKernel().Resolve <IGenericDataRepository <AuditLog> >();
                        var userProfileService  = Bootstrapper.GetKernel().Resolve <IUserProfileService>();

                        var profile = userProfileService.GetProfileByUserId(auditEvent.UserId);

                        var auditLog = new AuditLog();
                        auditLog.DepartmentId = auditEvent.DepartmentId;
                        auditLog.UserId       = auditEvent.UserId;
                        auditLog.LogType      = (int)auditEvent.Type;

                        switch (auditEvent.Type)
                        {
                        case AuditLogTypes.DepartmentSettingsChanged:
                            auditLog.Message = string.Format("{0} updated the department settings", profile.FullName.AsFirstNameLastName);
                            var compareLogic = new CompareLogic();
                            ComparisonResult auditCompareResult = compareLogic.Compare(auditEvent.Before, auditEvent.After);
                            auditLog.Data = auditCompareResult.DifferencesString;
                            break;

                        case AuditLogTypes.UserAdded:
                            if (auditEvent.After != null && auditEvent.After.GetType().BaseType == typeof(IdentityUser))
                            {
                                var newProfile = userProfileService.GetProfileByUserId(((IdentityUser)auditEvent.After).UserId);
                                auditLog.Message = string.Format("{0} added new user {1}", profile.FullName.AsFirstNameLastName, newProfile.FullName.AsFirstNameLastName);

                                auditLog.Data = $"New UserId: {newProfile.UserId}";
                            }
                            break;

                        case AuditLogTypes.UserRemoved:

                            if (auditEvent.Before != null && auditEvent.Before.GetType() == typeof(UserProfile))
                            {
                                auditLog.Message = $"{profile.FullName.AsFirstNameLastName} removed user {(((UserProfile)auditEvent.Before).FullName.AsFirstNameLastName)}";
                                auditLog.Data    = "No Data";
                            }

                            break;

                        case AuditLogTypes.GroupAdded:
                            if (auditEvent.After != null && auditEvent.After.GetType() == typeof(DepartmentGroup))
                            {
                                if (((DepartmentGroup)auditEvent.After).Type.HasValue && ((DepartmentGroup)auditEvent.After).Type.Value == (int)DepartmentGroupTypes.Station)
                                {
                                    auditLog.Message = $"{profile.FullName.AsFirstNameLastName} added station group {((DepartmentGroup)auditEvent.After).Name}";
                                }
                                else
                                {
                                    auditLog.Message = $"{profile.FullName.AsFirstNameLastName} added organizational group {((DepartmentGroup)auditEvent.After).Name}";
                                }

                                auditLog.Data = $"GroupId: {((DepartmentGroup)auditEvent.After).DepartmentGroupId}";
                            }
                            break;

                        case AuditLogTypes.GroupRemoved:
                            if (auditEvent.Before != null && auditEvent.Before.GetType() == typeof(DepartmentGroup))
                            {
                                auditLog.Message = string.Format("{0} removed group {1}", profile.FullName.AsFirstNameLastName, ((DepartmentGroup)auditEvent.Before).Name);
                                auditLog.Data    = "No Data";
                            }
                            break;

                        case AuditLogTypes.GroupChanged:
                            if (auditEvent.Before != null && auditEvent.Before.GetType() == typeof(DepartmentGroup) && auditEvent.After != null &&
                                auditEvent.After.GetType() == typeof(DepartmentGroup))
                            {
                                auditLog.Message = $"{profile.FullName.AsFirstNameLastName} updated group {((DepartmentGroup)auditEvent.After).Name}";
                                var compareLogicGroup = new CompareLogic();

                                ComparisonResult resultGroup = compareLogicGroup.Compare(auditEvent.Before, auditEvent.After);
                                auditLog.Data = resultGroup.DifferencesString;
                            }
                            break;

                        case AuditLogTypes.UnitAdded:
                            if (auditEvent.After != null && auditEvent.After.GetType() == typeof(Unit))
                            {
                                auditLog.Message = string.Format("{0} added unit {1}", profile.FullName.AsFirstNameLastName, ((Unit)auditEvent.After).Name);
                                auditLog.Data    = $"UnitId: {((Unit)auditEvent.After).UnitId}";
                            }
                            break;

                        case AuditLogTypes.UnitRemoved:
                            if (auditEvent.Before != null && auditEvent.Before.GetType() == typeof(Unit))
                            {
                                auditLog.Message = $"{profile.FullName.AsFirstNameLastName} removed unit {((Unit)auditEvent.Before).Name}";
                                auditLog.Data    = "No Data";
                            }
                            break;

                        case AuditLogTypes.UnitChanged:
                            if (auditEvent.Before != null && auditEvent.Before.GetType() == typeof(Unit) && auditEvent.After != null && auditEvent.After.GetType() == typeof(Unit))
                            {
                                auditLog.Message = $"{profile.FullName.AsFirstNameLastName} updated unit {((Unit)auditEvent.After).Name}";

                                var compareLogicUnit        = new CompareLogic();
                                ComparisonResult resultUnit = compareLogicUnit.Compare(auditEvent.Before, auditEvent.After);
                                auditLog.Data = resultUnit.DifferencesString;
                            }
                            break;

                        case AuditLogTypes.ProfileUpdated:
                            if (auditEvent.Before != null && auditEvent.Before.GetType() == typeof(UserProfile) && auditEvent.After != null && auditEvent.After.GetType() == typeof(UserProfile))
                            {
                                auditLog.Message = $"{profile.FullName.AsFirstNameLastName} updated the profile for {((UserProfile)auditEvent.After).FullName.AsFirstNameLastName}";

                                var compareLogicProfile        = new CompareLogic();
                                ComparisonResult resultProfile = compareLogicProfile.Compare(auditEvent.Before, auditEvent.After);
                                auditLog.Data = resultProfile.DifferencesString;
                            }
                            break;

                        case AuditLogTypes.PermissionsChanged:
                            if (auditEvent.Before != null && auditEvent.Before.GetType() == typeof(Permission) && auditEvent.After != null && auditEvent.After.GetType() == typeof(Permission))
                            {
                                auditLog.Message = $"{profile.FullName.AsFirstNameLastName} updated the department permissions";

                                var compareLogicProfile        = new CompareLogic();
                                ComparisonResult resultProfile = compareLogicProfile.Compare(auditEvent.Before, auditEvent.After);
                                auditLog.Data = resultProfile.DifferencesString;
                            }
                            break;
                        }

                        if (String.IsNullOrWhiteSpace(auditLog.Data))
                        {
                            auditLog.Data = "No Data";
                        }

                        if (!String.IsNullOrWhiteSpace(auditLog.Message))
                        {
                            auditLog.LoggedOn = DateTime.UtcNow;
                            auditLogsRepository.SaveOrUpdate(auditLog);
                        }
                    }
                    break;

                default:
                    throw new ArgumentOutOfRangeException();
                }
            }

            return(success);
        }
Example #28
0
        public async Task <DeviceRegistrationResult> RegisterUnitDevice([FromBody] DeviceRegistrationInput registrationInput)
        {
            if (this.ModelState.IsValid)
            {
                var result = new DeviceRegistrationResult();

                try
                {
                    if (registrationInput == null)
                    {
                        throw HttpStatusCode.BadRequest.AsException();
                    }

                    var push = new PushUri();
                    push.UserId       = UserId;
                    push.PlatformType = registrationInput.Plt;
                    push.PushLocation = registrationInput.Id;
                    push.DepartmentId = DepartmentId;

                    if (!String.IsNullOrWhiteSpace(registrationInput.Uri))
                    {
                        push.PushLocation = HttpUtility.UrlDecode(registrationInput.Uri);
                    }

                    push.DeviceId = registrationInput.Did;

                    if (registrationInput.Uid != 0)
                    {
                        push.UnitId = registrationInput.Uid;
                    }

                    try
                    {
                        push = _pushUriService.SavePushUri(push);
                    }
                    catch { }

                    PushRegisterionEvent pushRegisterionEvent = new PushRegisterionEvent();
                    pushRegisterionEvent.PushUriId    = push.PushUriId;
                    pushRegisterionEvent.UserId       = UserId;
                    pushRegisterionEvent.PlatformType = registrationInput.Plt;
                    pushRegisterionEvent.PushLocation = registrationInput.Id;
                    pushRegisterionEvent.DepartmentId = DepartmentId;
                    pushRegisterionEvent.DeviceId     = registrationInput.Did;
                    pushRegisterionEvent.Uuid         = registrationInput.Id;

                    if (registrationInput.Uid != 0)
                    {
                        pushRegisterionEvent.UnitId = registrationInput.Uid;
                    }

                    CqrsEvent registerUnitPushEvent = new CqrsEvent();
                    registerUnitPushEvent.Type = (int)CqrsEventTypes.UnitPushRegistration;
                    registerUnitPushEvent.Data = ObjectSerialization.Serialize(pushRegisterionEvent);

                    await _cqrsProvider.EnqueueCqrsEventAsync(registerUnitPushEvent);

                    //await _pushService.RegisterUnit(push);

                    result.Sfl = true;
                    result.Id  = push.PushUriId;

                    return(result);
                }
                catch (Exception ex)
                {
                    result.Sfl = false;
                    Framework.Logging.LogException(ex);

                    return(result);
                }
            }

            throw HttpStatusCode.BadRequest.AsException();
        }
Example #29
0
        public HttpResponseMessage SetUnitLocation(UnitLocationInput locationInput)
        {
            var unit = _unitsService.GetUnitById(locationInput.Uid);

            if (unit == null)
            {
                throw HttpStatusCode.NotFound.AsException();
            }

            if (unit.DepartmentId != DepartmentId)
            {
                throw HttpStatusCode.Unauthorized.AsException();
            }

            if (this.ModelState.IsValid)
            {
                try
                {
                    CqrsEvent    locationEvent = new CqrsEvent();
                    UnitLocation location      = new UnitLocation();
                    location.UnitId = locationInput.Uid;

                    if (locationInput.Tms.HasValue)
                    {
                        location.Timestamp = locationInput.Tms.Value;
                    }
                    else
                    {
                        location.Timestamp = DateTime.UtcNow;
                    }

                    if (!String.IsNullOrWhiteSpace(locationInput.Lat) && locationInput.Lat != "NaN" && !String.IsNullOrWhiteSpace(locationInput.Lon) && locationInput.Lon != "NaN")
                    {
                        location.Latitude  = decimal.Parse(locationInput.Lat);
                        location.Longitude = decimal.Parse(locationInput.Lon);

                        if (!String.IsNullOrWhiteSpace(locationInput.Acc) && locationInput.Acc != "NaN")
                        {
                            location.Accuracy = decimal.Parse(locationInput.Acc);
                        }

                        if (!String.IsNullOrWhiteSpace(locationInput.Alt) && locationInput.Alt != "NaN")
                        {
                            location.Altitude = decimal.Parse(locationInput.Alt);
                        }

                        if (!String.IsNullOrWhiteSpace(locationInput.Alc) && locationInput.Alc != "NaN")
                        {
                            location.AltitudeAccuracy = decimal.Parse(locationInput.Alc);
                        }

                        if (!String.IsNullOrWhiteSpace(locationInput.Spd) && locationInput.Spd != "NaN")
                        {
                            location.Speed = decimal.Parse(locationInput.Spd);
                        }

                        if (!String.IsNullOrWhiteSpace(locationInput.Hdn) && locationInput.Hdn != "NaN")
                        {
                            location.Heading = decimal.Parse(locationInput.Hdn);
                        }

                        locationEvent.Type = (int)CqrsEventTypes.UnitLocation;
                        locationEvent.Data = ObjectSerialization.Serialize(location);
                        _cqrsProvider.EnqueueCqrsEvent(locationEvent);

                        return(Request.CreateResponse(HttpStatusCode.Created));
                    }
                    else
                    {
                        return(Request.CreateResponse(HttpStatusCode.NotModified));
                    }
                }
                catch (Exception ex)
                {
                    Logging.LogException(ex);
                    throw HttpStatusCode.InternalServerError.AsException();
                }
            }

            throw HttpStatusCode.BadRequest.AsException();
        }