Ejemplo n.º 1
0
        public DepartmentGroup GetGroupForEvent(ProcessedNotification notification)
        {
            //NotificationItem dynamicData = (NotificationItem)JsonConvert.DeserializeObject(data);
            NotificationItem dynamicData = ObjectSerialization.Deserialize <NotificationItem>(notification.Data);

            if (notification.Type == EventTypes.UnitStatusChanged)
            {
                var unitEvent = _unitsService.GetUnitStateById(dynamicData.StateId);
                return(_departmentGroupsService.GetGroupById(unitEvent.Unit.StationGroupId.GetValueOrDefault()));
            }
            else if (notification.Type == EventTypes.PersonnelStatusChanged)
            {
                var userStaffing = _userStateService.GetUserStateById(dynamicData.StateId);
                var group        = _departmentGroupsService.GetGroupForUser(userStaffing.UserId, notification.DepartmentId);
                return(group);
            }
            else if (notification.Type == EventTypes.PersonnelStatusChanged)
            {
                var actionLog = _actionLogsService.GetActionlogById(dynamicData.StateId);
                var group     = _departmentGroupsService.GetGroupForUser(actionLog.UserId, notification.DepartmentId);
                return(group);
            }
            else if (notification.Type == EventTypes.UserAssignedToGroup)
            {
                return(_departmentGroupsService.GetGroupById(dynamicData.GroupId));
            }

            return(null);
        }
Ejemplo n.º 2
0
        //[Test]
        public void TestDeserialization()
        {
            string test    =  "<?xml version=\"1.0\" encoding=\"utf-8\"?><TestObject xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\"><Id>500</Id><Data>This is just a test object. TestStringToSearchOn</Data></TestObject>";
            var    testObj = ObjectSerialization.Deserialize <TestObject>(test);

            testObj.Should().NotBeNull();
            testObj.Id.Should().Be(500);
            testObj.Data.Should().Be("This is just a test object. TestStringToSearchOn");
        }
Ejemplo n.º 3
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));
        }
Ejemplo n.º 4
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))
                    {
                        NotificationItem ni = null;
                        try
                        {
                            ni = ObjectSerialization.Deserialize <NotificationItem>(body);
                        }
                        catch (Exception ex)
                        {
                            success = false;
                            result  = "Unable to parse message body Exception: " + ex.ToString();
                            //message.DeadLetter();
                            await _client.DeadLetterAsync(message.SystemProperties.LockToken);
                        }

                        await ProcessNotificationItem(ni, message.MessageId, body);
                    }
                    else
                    {
                        success = false;
                        result  = "Message body is null or empty";
                    }

                    try
                    {
                        //message.Complete();
                        await _client.CompleteAsync(message.SystemProperties.LockToken);
                    }
                    catch (MessageLockLostException)
                    {
                    }
                }
                catch (Exception ex)
                {
                    success = false;
                    result  = ex.ToString();

                    Logging.LogException(ex);
                    //message.Abandon();
                    await _client.AbandonAsync(message.SystemProperties.LockToken);
                }
            }

            return(new Tuple <bool, string>(success, result));
        }
Ejemplo n.º 5
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))
                    {
                        NotificationItem ni = null;
                        try
                        {
                            ni = ObjectSerialization.Deserialize <NotificationItem>(body);
                        }
                        catch (Exception ex)
                        {
                            success = false;
                            result  = "Unable to parse message body Exception: " + ex.ToString();
                            message.DeadLetter();
                        }

                        ProcessNotificationItem(ni, message.MessageId, body);
                    }
                    else
                    {
                        success = false;
                        result  = "Message body is null or empty";
                    }

                    try
                    {
                        message.Complete();
                    }
                    catch (MessageLockLostException)
                    {
                    }
                }
                catch (Exception ex)
                {
                    success = false;
                    result  = ex.ToString();

                    Logging.LogException(ex);
                    message.Abandon();
                }
            }

            return(new Tuple <bool, string>(success, result));
        }
Ejemplo n.º 6
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))
                    {
                        DistributionListQueueItem dlqi = null;
                        try
                        {
                            dlqi = ObjectSerialization.Deserialize <DistributionListQueueItem>(body);
                        }
                        catch (Exception ex)
                        {
                            success = false;
                            result  = "Unable to parse message body Exception: " + ex.ToString();
                            //message.Complete();
                            await _client.CompleteAsync(message.SystemProperties.LockToken);
                        }

                        await ProcessDistributionListQueueItem(dlqi);
                    }

                    try
                    {
                        if (success)
                        {
                            await _client.CompleteAsync(message.SystemProperties.LockToken);
                        }
                        //message.Complete();
                    }
                    catch (MessageLockLostException)
                    {
                    }
                }
                catch (Exception ex)
                {
                    result = ex.ToString();
                    Logging.LogException(ex);
                    //message.Abandon();
                    await _client.DeadLetterAsync(message.SystemProperties.LockToken);
                }
            }

            return(new Tuple <bool, string>(success, result));
        }
Ejemplo n.º 7
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));
        }
Ejemplo n.º 8
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))
                    {
                        DistributionListQueueItem dlqi = null;
                        try
                        {
                            dlqi = ObjectSerialization.Deserialize <DistributionListQueueItem>(body);
                        }
                        catch (Exception ex)
                        {
                            success = false;
                            result  = "Unable to parse message body Exception: " + ex.ToString();
                            message.Complete();
                        }

                        ProcessDistributionListQueueItem(dlqi);
                    }

                    try
                    {
                        if (success)
                        {
                            message.Complete();
                        }
                    }
                    catch (MessageLockLostException)
                    {
                    }
                }
                catch (Exception ex)
                {
                    result = ex.ToString();
                    Logging.LogException(ex);
                    message.Abandon();
                }
            }

            return(new Tuple <bool, string>(success, result));
        }
Ejemplo n.º 9
0
        public async Task <List <PersonnelListStatusOrder> > GetDepartmentPersonnelListStatusSortOrderAsync(int departmentId)
        {
            var settingValue = await GetSettingByDepartmentIdType(departmentId, DepartmentSettingTypes.PersonnelListStatusSortOrder);

            if (settingValue != null)
            {
                var setting = ObjectSerialization.Deserialize <PersonnelListStatusOrderSetting>(settingValue.Setting);

                if (setting != null)
                {
                    return(setting.Orders);
                }
            }
            return(null);
        }
Ejemplo n.º 10
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);
        }
Ejemplo n.º 11
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))
                    {
                        CallQueueItem cqi = null;
                        try
                        {
                            cqi = ObjectSerialization.Deserialize <CallQueueItem>(body);
                        }
                        catch (Exception ex)
                        {
                            success = false;
                            result  = "Unable to parse message body Exception: " + ex.ToString();
                            message.DeadLetter();
                        }

                        if (cqi != null && cqi.Call != null && cqi.Call.HasAnyDispatches())
                        {
                            try
                            {
                                ProcessCallQueueItem(cqi);
                            }
                            catch (Exception ex)
                            {
                                Logging.LogException(ex);
                                message.Abandon();

                                success = false;
                                result  = ex.ToString();
                            }
                        }
                    }
                    else
                    {
                        success = false;
                        result  = "Message body is null or empty";
                    }

                    try
                    {
                        message.Complete();
                    }
                    catch (MessageLockLostException)
                    {
                    }
                }
                catch (Exception ex)
                {
                    success = false;
                    result  = ex.ToString();

                    Logging.LogException(ex);
                    message.Abandon();
                }
            }

            return(new Tuple <bool, string>(success, result));
        }
Ejemplo n.º 12
0
        private void StartMonitoring()
        {
            if (SystemBehaviorConfig.ServiceBusType == ServiceBusTypes.Rabbit)
            {
                var callQueueReceivedConsumer = new EventingBasicConsumer(_channel);
                callQueueReceivedConsumer.Received += (model, ea) =>
                {
                    if (ea != null && ea.Body != null && ea.Body.Length > 0)
                    {
                        var body    = ea.Body;
                        var message = Encoding.UTF8.GetString(body);

                        try
                        {
                            var cqi = ObjectSerialization.Deserialize <CallQueueItem>(message);

                            if (cqi != null)
                            {
                                CallQueueReceived?.Invoke(cqi);
                            }
                        }
                        catch (Exception ex)
                        {
                            Logging.LogException(ex);
                        }
                    }

                    _channel.BasicAck(ea.DeliveryTag, false);
                };

                var messageQueueReceivedConsumer = new EventingBasicConsumer(_channel);
                messageQueueReceivedConsumer.Received += (model, ea) =>
                {
                    if (ea != null && ea.Body != null && ea.Body.Length > 0)
                    {
                        var body    = ea.Body;
                        var message = Encoding.UTF8.GetString(body);

                        try
                        {
                            var mqi = ObjectSerialization.Deserialize <MessageQueueItem>(message);

                            if (mqi != null)
                            {
                                MessageQueueReceived?.Invoke(mqi);
                            }
                        }
                        catch (Exception ex)
                        {
                            Logging.LogException(ex);
                        }
                    }

                    _channel.BasicAck(ea.DeliveryTag, false);
                };

                var distributionListQueueReceivedConsumer = new EventingBasicConsumer(_channel);
                distributionListQueueReceivedConsumer.Received += (model, ea) =>
                {
                    if (ea != null && ea.Body != null && ea.Body.Length > 0)
                    {
                        var body    = ea.Body;
                        var message = Encoding.UTF8.GetString(body);

                        try
                        {
                            var dlqi = ObjectSerialization.Deserialize <DistributionListQueueItem>(message);

                            if (dlqi != null)
                            {
                                DistributionListQueueReceived?.Invoke(dlqi);
                            }
                        }
                        catch (Exception ex)
                        {
                            Logging.LogException(ex);
                        }
                    }

                    _channel.BasicAck(ea.DeliveryTag, false);
                };

                var notificationQueueReceivedConsumer = new EventingBasicConsumer(_channel);
                notificationQueueReceivedConsumer.Received += (model, ea) =>
                {
                    if (ea != null && ea.Body != null && ea.Body.Length > 0)
                    {
                        var body    = ea.Body;
                        var message = Encoding.UTF8.GetString(body);

                        try
                        {
                            var ni = ObjectSerialization.Deserialize <NotificationItem>(message);

                            if (ni != null)
                            {
                                NotificationQueueReceived?.Invoke(ni);
                            }
                        }
                        catch (Exception ex)
                        {
                            Logging.LogException(ex);
                        }
                    }

                    _channel.BasicAck(ea.DeliveryTag, false);
                };

                var shiftNotificationQueueReceivedConsumer = new EventingBasicConsumer(_channel);
                shiftNotificationQueueReceivedConsumer.Received += (model, ea) =>
                {
                    if (ea != null && ea.Body != null && ea.Body.Length > 0)
                    {
                        var body    = ea.Body;
                        var message = Encoding.UTF8.GetString(body);

                        try
                        {
                            var sqi = ObjectSerialization.Deserialize <ShiftQueueItem>(message);

                            if (sqi != null)
                            {
                                ShiftNotificationQueueReceived?.Invoke(sqi);
                            }
                        }
                        catch (Exception ex)
                        {
                            Logging.LogException(ex);
                        }
                    }

                    _channel.BasicAck(ea.DeliveryTag, false);
                };

                var cqrsEventQueueReceivedConsumer = new EventingBasicConsumer(_channel);
                cqrsEventQueueReceivedConsumer.Received += (model, ea) =>
                {
                    if (ea != null && ea.Body != null && ea.Body.Length > 0)
                    {
                        var body    = ea.Body;
                        var message = Encoding.UTF8.GetString(body);

                        try
                        {
                            var cqrs = ObjectSerialization.Deserialize <CqrsEvent>(message);

                            if (cqrs != null)
                            {
                                CqrsEventQueueReceived?.Invoke(cqrs);
                            }
                        }
                        catch (Exception ex)
                        {
                            Logging.LogException(ex);
                        }
                    }

                    _channel.BasicAck(ea.DeliveryTag, false);
                };


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

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

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

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

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

                String cqrsEventQueueReceivedConsumerTag = _channel.BasicConsume(
                    queue: ServiceBusConfig.SystemQueueName,
                    autoAck: false,
                    consumer: cqrsEventQueueReceivedConsumer);
            }
        }
Ejemplo n.º 13
0
        public static Tuple <bool, string> ProcessQueueMessage(BrokeredMessage message)
        {
            bool   success = true;
            string result  = "";

            if (message != null)
            {
                MessageQueueItem mqi = null;

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

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

                        ProcessMessageQueueItem(mqi);
                    }

                    try
                    {
                        if (success)
                        {
                            message.Complete();
                        }
                    }
                    catch (MessageLockLostException)
                    {
                    }
                }
                catch (Exception ex)
                {
                    result = ex.ToString();

                    if (mqi != null)
                    {
                        ex.Data.Add("DepartmentId", mqi.DepartmentId);

                        if (mqi.Message != null)
                        {
                            ex.Data.Add("MessageId", mqi.Message.MessageId);
                            ex.Data.Add("SendingUserId", mqi.Message.SendingUserId);
                            ex.Data.Add("RecievingUserId", mqi.Message.ReceivingUserId);
                        }
                    }

                    ex.Data.Add("MQI", JsonConvert.SerializeObject(mqi));

                    Logging.LogException(ex);
                    message.Abandon();
                }
            }

            return(new Tuple <bool, string>(success, result));
        }
Ejemplo n.º 14
0
        public async Task <Tuple <bool, string> > ProcessQueueMessage(Message message, CancellationToken token)
        {
            bool   success = true;
            string result  = "";

            if (message != null)
            {
                MessageQueueItem mqi = null;

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

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

                        await ProcessMessageQueueItem(mqi);
                    }

                    try
                    {
                        if (success)
                        {
                            await _client.CompleteAsync(message.SystemProperties.LockToken);
                        }
                        //message.Complete();
                    }
                    catch (MessageLockLostException)
                    {
                    }
                }
                catch (Exception ex)
                {
                    result = ex.ToString();

                    if (mqi != null)
                    {
                        ex.Data.Add("DepartmentId", mqi.DepartmentId);

                        if (mqi.Message != null)
                        {
                            ex.Data.Add("MessageId", mqi.Message.MessageId);
                            ex.Data.Add("SendingUserId", mqi.Message.SendingUserId);
                            ex.Data.Add("RecievingUserId", mqi.Message.ReceivingUserId);
                        }
                    }

                    ex.Data.Add("MQI", JsonConvert.SerializeObject(mqi));

                    Logging.LogException(ex);
                    await _client.AbandonAsync(message.SystemProperties.LockToken);

                    //message.Abandon();
                }
            }

            return(new Tuple <bool, string>(success, result));
        }
Ejemplo n.º 15
0
        public string GetMessageForType(ProcessedNotification notification)
        {
            try
            {
                NotificationItem data = ObjectSerialization.Deserialize <NotificationItem>(notification.Data);

                switch (notification.Type)
                {
                case EventTypes.UnitStatusChanged:
                    var unitEvent  = _unitsService.GetUnitStateById((int)data.StateId);
                    var unitStatus = _customStateService.GetCustomUnitState(unitEvent);

                    if (unitEvent != null && unitEvent.Unit != null)
                    {
                        return(String.Format("Unit {0} is now {1}", unitEvent.Unit.Name, unitStatus.ButtonText));
                    }
                    else if (unitEvent != null)
                    {
                        return(String.Format("A Unit's status is now {0}", unitStatus.ButtonText));
                    }
                    else
                    {
                        return("A unit's status changed");
                    }

                case EventTypes.PersonnelStaffingChanged:
                    var userStaffing     = _userStateService.GetUserStateById((int)data.StateId);
                    var userProfile      = _userProfileService.GetProfileByUserId(userStaffing.UserId);
                    var userStaffingText = _customStateService.GetCustomPersonnelStaffing(data.DepartmentId, userStaffing);

                    return(String.Format("{0} staffing is now {1}", userProfile.FullName.AsFirstNameLastName, userStaffingText.ButtonText));

                case EventTypes.PersonnelStatusChanged:
                    var actionLog = _actionLogsService.GetActionlogById(data.StateId);

                    UserProfile profile = null;
                    if (actionLog != null)
                    {
                        profile = _userProfileService.GetProfileByUserId(actionLog.UserId);
                    }
                    else if (data.UserId != String.Empty)
                    {
                        profile = _userProfileService.GetProfileByUserId(data.UserId);
                    }

                    var userStatusText = _customStateService.GetCustomPersonnelStatus(data.DepartmentId, actionLog);

                    if (profile != null && userStatusText != null)
                    {
                        return(String.Format("{0} status is now {1}", profile.FullName.AsFirstNameLastName, userStatusText.ButtonText));
                    }
                    else if (profile != null)
                    {
                        return(String.Format("{0} status has changed", profile.FullName.AsFirstNameLastName));
                    }

                    return(String.Empty);

                case EventTypes.UserCreated:
                    var newUserprofile = _userProfileService.GetProfileByUserId(data.UserId);

                    if (newUserprofile != null)
                    {
                        return(String.Format("{0} has been added to your department", newUserprofile.FullName.AsFirstNameLastName));
                    }
                    else
                    {
                        return("A new user has been added to your department");
                    }

                case EventTypes.UserAssignedToGroup:

                    UserProfile groupUserprofile = null;
                    try
                    {
                        if (data.UserId != String.Empty)
                        {
                            groupUserprofile = _userProfileService.GetProfileByUserId(data.UserId);
                        }
                    }
                    catch { }

                    DepartmentGroup newGroup = null;
                    try
                    {
                        if (data.GroupId != 0)
                        {
                            newGroup = _departmentGroupsService.GetGroupById((int)data.GroupId, false);
                        }
                    }
                    catch { }

                    if (groupUserprofile != null && newGroup != null)
                    {
                        return(String.Format("{0} has been assigned to group {1}", groupUserprofile.FullName.AsFirstNameLastName, newGroup.Name));
                    }
                    else if (groupUserprofile != null && newGroup == null)
                    {
                        return(String.Format("{0} has been assigned to group", groupUserprofile.FullName.AsFirstNameLastName));
                    }
                    else if (newGroup != null && groupUserprofile == null)
                    {
                        return(String.Format("A user has been assigned to group {0}", newGroup.Name));
                    }
                    else
                    {
                        return(String.Format("A has been assigned to a group"));
                    }

                case EventTypes.CalendarEventUpcoming:
                    var calandarItem = _calendarService.GetCalendarItemById((int)data.ItemId);
                    return(String.Format("Event {0} is upcoming", calandarItem.Title));

                case EventTypes.DocumentAdded:
                    var document = _documentsService.GetDocumentById((int)data.ItemId);
                    return(String.Format("Document {0} has been added", document.Name));

                case EventTypes.NoteAdded:
                    var note = _notesService.GetNoteById((int)data.ItemId);

                    if (note != null)
                    {
                        return(String.Format("Message {0} has been added", note.Title));
                    }

                    break;

                case EventTypes.UnitAdded:
                    var unit = _unitsService.GetUnitById((int)data.UnitId);
                    return(String.Format("Unit {0} has been added", unit.Name));

                case EventTypes.LogAdded:
                    var log = _workLogsService.GetWorkLogById((int)data.ItemId);

                    if (log != null)
                    {
                        var logUserProfile = _userProfileService.GetProfileByUserId(log.LoggedByUserId);
                        return(String.Format("{0} created log {1}", logUserProfile.FullName.AsFirstNameLastName, log.LogId));
                    }
                    else
                    {
                        return(String.Format("A new log was created"));
                    }

                case EventTypes.DepartmentSettingsChanged:
                    return(String.Format("Settings have been updated for your department"));

                case EventTypes.RolesInGroupAvailabilityAlert:

                    var userStateChanged = _userStateService.GetUserStateById(int.Parse(notification.Value));
                    var roleForGroup     = _personnelRolesService.GetRoleById(notification.PersonnelRoleTargeted);
                    var groupForRole     = _departmentGroupsService.GetGroupForUser(userStateChanged.UserId, notification.DepartmentId);

                    return(String.Format("Availability for role {0} in group {1} is at or below the lower limit", roleForGroup.Name, groupForRole.Name));

                case EventTypes.RolesInDepartmentAvailabilityAlert:
                    if (notification != null)
                    {
                        var roleForDep = _personnelRolesService.GetRoleById(notification.PersonnelRoleTargeted);

                        if (roleForDep != null)
                        {
                            return(String.Format("Availability for role {0} for the department is at or below the lower limit", roleForDep.Name));
                        }
                    }
                    break;

                case EventTypes.UnitTypesInGroupAvailabilityAlert:
                    if (data.UnitId != 0)
                    {
                        var unitForGroup = _unitsService.GetUnitById(data.UnitId);

                        if (unitForGroup != null && unitForGroup.StationGroupId.HasValue)
                        {
                            var groupForUnit = _departmentGroupsService.GetGroupById(unitForGroup.StationGroupId.Value);

                            return(String.Format("Availability for unit type {0} in group {1} is at or below the lower limit",
                                                 unitForGroup.Type, groupForUnit.Name));
                        }
                    }
                    return(String.Empty);

                case EventTypes.UnitTypesInDepartmentAvailabilityAlert:
                    return(String.Format("Availability for unit type {0} for the department is at or below the lower limit", notification.UnitTypeTargeted));

                case EventTypes.CalendarEventAdded:
                    var calEvent   = _calendarService.GetCalendarItemById(notification.ItemId);
                    var department = _departmentsService.GetDepartmentById(calEvent.DepartmentId);

                    if (calEvent != null)
                    {
                        if (calEvent.ItemType == 0)
                        {
                            if (calEvent.IsAllDay)
                            {
                                return($"New Calendar Event {calEvent.Title} on {calEvent.Start.TimeConverter(department).ToShortDateString()}");
                            }
                            else
                            {
                                return($"New Calendar Event {calEvent.Title} on {calEvent.Start.TimeConverter(department).ToShortDateString()} at {calEvent.Start.TimeConverter(department).ToShortTimeString()}");
                            }
                        }
                        else
                        if (calEvent.IsAllDay)
                        {
                            return($"New Calendar RSVP Event {calEvent.Title} on {calEvent.Start.TimeConverter(department).ToShortDateString()}");
                        }
                        else
                        {
                            return($"New Calendar RSVP Event {calEvent.Title} on {calEvent.Start.TimeConverter(department).ToShortDateString()} at {calEvent.Start.TimeConverter(department).ToShortTimeString()}");
                        }
                    }
                    else
                    {
                        return(String.Empty);
                    }

                case EventTypes.CalendarEventUpdated:
                    var calUpdatedEvent           = _calendarService.GetCalendarItemById(notification.ItemId);
                    var calUpdatedEventDepartment = _departmentsService.GetDepartmentById(calUpdatedEvent.DepartmentId);

                    if (calUpdatedEvent != null)
                    {
                        return($"Calendar Event {calUpdatedEvent.Title} on {calUpdatedEvent.Start.TimeConverter(calUpdatedEventDepartment).ToShortDateString()} has changed");
                    }
                    else
                    {
                        return(String.Empty);
                    }

                default:
                    throw new ArgumentOutOfRangeException("type");
                }
            }
            catch (Exception ex)
            {
                Logging.LogException(ex, extraMessage: notification.Data);
                return(String.Empty);
            }

            return(String.Empty);
        }
Ejemplo n.º 16
0
        public bool ValidateNotificationForProcessing(ProcessedNotification notification, DepartmentNotification setting)
        {
            //dynamic dynamicData = JsonConvert.DeserializeObject(notification.Data);
            NotificationItem dynamicData = ObjectSerialization.Deserialize <NotificationItem>(notification.Data);

            switch (notification.Type)
            {
            case EventTypes.UnitStatusChanged:
                if (!String.IsNullOrWhiteSpace(setting.BeforeData) && !String.IsNullOrWhiteSpace(setting.CurrentData))
                {
                    if (setting.BeforeData.Contains("-1") && setting.CurrentData.Contains("-1"))
                    {
                        return(true);
                    }

                    bool beforeAny  = setting.BeforeData.Contains("-1");
                    bool currentAny = setting.CurrentData.Contains("-1");

                    UnitState beforeState  = null;
                    UnitState currentState = null;

                    currentState = _unitsService.GetUnitStateById((int)dynamicData.StateId);

                    if (!beforeAny)
                    {
                        beforeState = _unitsService.GetLastUnitStateBeforeId(currentState.UnitId, currentState.UnitStateId);
                    }

                    if ((currentAny || currentState.State == int.Parse(setting.CurrentData)) &&
                        (beforeAny || beforeState.State == int.Parse(setting.BeforeData)))
                    {
                        return(true);
                    }
                }
                else
                {
                    return(false);
                }
                break;

            case EventTypes.PersonnelStaffingChanged:
                if (!String.IsNullOrWhiteSpace(setting.BeforeData) && !String.IsNullOrWhiteSpace(setting.CurrentData))
                {
                    if (setting.BeforeData.Contains("-1") && setting.CurrentData.Contains("-1"))
                    {
                        return(true);
                    }

                    bool beforeAny  = setting.BeforeData.Contains("-1");
                    bool currentAny = setting.CurrentData.Contains("-1");

                    UserState beforeState  = null;
                    UserState currentState = null;

                    currentState = _userStateService.GetUserStateById((int)dynamicData.StateId);

                    if (!beforeAny)
                    {
                        beforeState = _userStateService.GetPerviousUserState(currentState.UserId, currentState.UserStateId);
                    }

                    if ((currentAny || currentState.State == int.Parse(setting.CurrentData)) &&
                        (beforeAny || beforeState.State == int.Parse(setting.BeforeData)))
                    {
                        return(true);
                    }
                }
                else
                {
                    return(false);
                }
                break;

            case EventTypes.PersonnelStatusChanged:
                if (!String.IsNullOrWhiteSpace(setting.BeforeData) && !String.IsNullOrWhiteSpace(setting.CurrentData))
                {
                    if (setting.BeforeData.Contains("-1") && setting.CurrentData.Contains("-1"))
                    {
                        return(true);
                    }

                    bool beforeAny  = setting.BeforeData.Contains("-1");
                    bool currentAny = setting.CurrentData.Contains("-1");

                    ActionLog beforeState  = null;
                    ActionLog currentState = null;

                    currentState = _actionLogsService.GetActionlogById((int)dynamicData.StateId);

                    if (!beforeAny)
                    {
                        beforeState = _actionLogsService.GetPreviousActionLog(currentState.UserId, currentState.ActionLogId);
                    }

                    if ((currentAny || currentState.ActionTypeId == int.Parse(setting.CurrentData)) &&
                        (beforeAny || beforeState.ActionTypeId == int.Parse(setting.BeforeData)))
                    {
                        return(true);
                    }
                }
                else
                {
                    return(false);
                }
                break;

            case EventTypes.RolesInGroupAvailabilityAlert:
                if (!String.IsNullOrWhiteSpace(setting.CurrentData) && !String.IsNullOrWhiteSpace(setting.Data))
                {
                    int count            = 0;
                    var userStateChanged = _userStateService.GetUserStateById((int)dynamicData.StateId);
                    var usersInRole      = _personnelRolesService.GetAllMembersOfRole(int.Parse(setting.Data));
                    var group            = _departmentGroupsService.GetGroupForUser(userStateChanged.UserId, notification.DepartmentId);

                    if (group == null || group.Members == null || !group.Members.Any())
                    {
                        return(false);
                    }

                    var acceptableStaffingLevels = setting.CurrentData.Split(char.Parse(","));

                    if (usersInRole != null && !usersInRole.Any())
                    {
                        return(false);
                    }

                    var staffingLevels = _userStateService.GetLatestStatesForDepartment(setting.DepartmentId);

                    if (staffingLevels != null && staffingLevels.Any())
                    {
                        foreach (var user in usersInRole)
                        {
                            var currentState = staffingLevels.FirstOrDefault(x => x.UserId == user.UserId);

                            if (currentState != null && acceptableStaffingLevels.Any(x => x == currentState.State.ToString()) &&
                                group.Members.Any(x => x.UserId == user.UserId))
                            {
                                count++;
                            }
                        }

                        if (count <= setting.LowerLimit)
                        {
                            notification.PersonnelRoleTargeted = int.Parse(setting.Data);
                            return(true);
                        }
                    }
                    else
                    {
                        return(false);
                    }
                }
                else
                {
                    return(false);
                }
                break;

            case EventTypes.RolesInDepartmentAvailabilityAlert:
                if (!String.IsNullOrWhiteSpace(setting.CurrentData) && !String.IsNullOrWhiteSpace(setting.Data))
                {
                    int count       = 0;
                    var usersInRole = _personnelRolesService.GetAllMembersOfRole(int.Parse(setting.Data));
                    var acceptableStaffingLevels = setting.CurrentData.Split(char.Parse(","));

                    if (usersInRole != null && !usersInRole.Any())
                    {
                        return(false);
                    }

                    var staffingLevels = _userStateService.GetLatestStatesForDepartment(setting.DepartmentId);

                    if (staffingLevels != null && staffingLevels.Any())
                    {
                        foreach (var user in usersInRole)
                        {
                            var currentState = staffingLevels.FirstOrDefault(x => x.UserId == user.UserId);

                            if (currentState != null && acceptableStaffingLevels.Any(x => x == currentState.State.ToString()))
                            {
                                count++;
                            }
                        }

                        if (count <= setting.LowerLimit)
                        {
                            notification.PersonnelRoleTargeted = int.Parse(setting.Data);
                            return(true);
                        }
                    }
                    else
                    {
                        return(false);
                    }
                }
                else
                {
                    return(false);
                }
                break;

            case EventTypes.UnitTypesInGroupAvailabilityAlert:
                if (!String.IsNullOrWhiteSpace(setting.CurrentData) && !String.IsNullOrWhiteSpace(setting.Data))
                {
                    int count            = 0;
                    var currentUnitState = _unitsService.GetUnitStateById((int)dynamicData.StateId);
                    var unitsForType     = _unitsService.GetAllUnitsForType(setting.DepartmentId, setting.Data);
                    var unitForEvent     = _unitsService.GetUnitById(currentUnitState.UnitId);

                    if (unitForEvent?.StationGroupId == null)
                    {
                        return(false);
                    }

                    var acceptableUnitStates = setting.CurrentData.Split(char.Parse(","));
                    var unitsInGroup         = _unitsService.GetAllUnitsForGroup(unitForEvent.StationGroupId.Value);

                    if (unitsForType != null && !unitsForType.Any())
                    {
                        return(false);
                    }

                    var staffingLevels = _unitsService.GetAllLatestStatusForUnitsByDepartmentId(setting.DepartmentId);

                    foreach (var unit in unitsForType)
                    {
                        var currentState = staffingLevels.FirstOrDefault(x => x.UnitId == unit.UnitId);

                        if (currentState != null && acceptableUnitStates.Any(x => x == currentState.State.ToString()) && unitsInGroup.Any(x => x.UnitId == unit.UnitId))
                        {
                            count++;
                        }
                    }

                    if (count <= setting.LowerLimit)
                    {
                        notification.UnitTypeTargeted = setting.Data;
                        return(true);
                    }
                }
                else
                {
                    return(false);
                }
                break;

            case EventTypes.UnitTypesInDepartmentAvailabilityAlert:
                if (!String.IsNullOrWhiteSpace(setting.CurrentData) && !String.IsNullOrWhiteSpace(setting.Data))
                {
                    int count                = 0;
                    var unitsForType         = _unitsService.GetAllUnitsForType(setting.DepartmentId, setting.Data);
                    var acceptableUnitStates = setting.CurrentData.Split(char.Parse(","));

                    if (unitsForType != null && !unitsForType.Any())
                    {
                        return(false);
                    }

                    var staffingLevels = _unitsService.GetAllLatestStatusForUnitsByDepartmentId(setting.DepartmentId);

                    foreach (var unit in unitsForType)
                    {
                        var currentState = staffingLevels.FirstOrDefault(x => x.UnitId == unit.UnitId);

                        if (currentState != null && acceptableUnitStates.Any(x => x == currentState.State.ToString()))
                        {
                            count++;
                        }
                    }

                    if (count <= setting.LowerLimit)
                    {
                        notification.UnitTypeTargeted = setting.Data;
                        return(true);
                    }
                }
                else
                {
                    return(false);
                }
                break;

            default:
                return(true);
            }

            return(false);
        }
Ejemplo n.º 17
0
        public async Task <T> RetrieveAsync <T>(string cacheKey, Func <Task <T> > fallbackFunction, TimeSpan expiration)
            where T : class
        {
            T         data  = null;
            IDatabase cache = null;

            try
            {
                if (Config.SystemBehaviorConfig.CacheEnabled && _connection != null && _connection.IsConnected)
                {
                    cache = _connection.GetDatabase();

                    var cacheValue = await cache.StringGetAsync(cacheKey);

                    try
                    {
                        if (cacheValue.HasValue)
                        {
                            data = ObjectSerialization.Deserialize <T>(cacheValue);
                        }
                    }
                    catch
                    {
                        await RemoveAsync(cacheKey);

                        throw;
                    }

                    if (data != null)
                    {
                        return(data);
                    }
                }
            }
            catch (TimeoutException)
            { }
            catch (Exception ex)
            {
                Logging.LogException(ex);
            }

            data = await fallbackFunction();

            if (Config.SystemBehaviorConfig.CacheEnabled && _connection != null && _connection.IsConnected)
            {
                if (data != null && cache != null)
                {
                    try
                    {
                        await cache.StringSetAsync(cacheKey, ObjectSerialization.Serialize(data), expiration);
                    }
                    catch (TimeoutException)
                    { }
                    catch (Exception ex)
                    {
                        Logging.LogException(ex);
                    }
                }
            }

            return(data);
        }
Ejemplo n.º 18
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);
            }
        }