Exemplo n.º 1
0
        public bool CreateWorkDefinition(WorkDefinitionEvent workDefinitionEvent)
        {
            var workDefinition = GetDbModel(workDefinitionEvent);

            _loggingService.Info($"Create Work Definition: {JsonConvert.SerializeObject(workDefinition)}", "WorkDefinitionServices.CreateWorkDefinition");

            var messages = new List <KafkaMessage>(workdefintionTopicNames?.Select((topic) =>
                                                                                   new KafkaMessage
            {
                Key     = workDefinition.AssetUID.ToString(),
                Message = new
                {
                    CreateWorkDefinitionEvent = new
                    {
                        AssetUID           = workDefinition.AssetUID.ToString(),
                        WorkDefinitionType = workDefinitionEvent.WorkDefinitionType,
                        SensorNumber       = workDefinition.SwitchNumber,
                        StartIsOn          = workDefinition.SwitchWorkStartState,
                        ActionUTC          = workDefinition.InsertUTC,
                        ReceivedUTC        = workDefinition.InsertUTC,
                    }
                },
                Topic = topic
            }
                                                                                   ));

            var actions = new List <Action>()
            {
                () => _transaction.Upsert(workDefinition),
                () => _transaction.Publish(messages)
            };

            return(_transaction.Execute(actions));
        }
Exemplo n.º 2
0
        public bool AssociateCustomerAsset(AssociateCustomerAssetEvent associateCustomerAsset)
        {
            try
            {
                var customer = GetCustomer(associateCustomerAsset.CustomerUID);
                if (customer?.CustomerID > 0)
                {
                    Enum.TryParse(associateCustomerAsset.RelationType, true,
                                  out CustomerEnum.RelationType relationType);

                    var messages = CustomerTopics
                                   ?.Select(topic => new KafkaMessage
                    {
                        Key     = associateCustomerAsset.CustomerUID.ToString(),
                        Message = new
                        {
                            AssociateCustomerAssetEvent = new
                            {
                                associateCustomerAsset.CustomerUID,
                                associateCustomerAsset.AssetUID,
                                RelationType = relationType.ToString(),
                                associateCustomerAsset.ActionUTC,
                                associateCustomerAsset.ReceivedUTC
                            }
                        },
                        Topic = topic
                    })
                                   ?.ToList();
                    var assetCustomer = new DbAssetCustomer
                    {
                        Fk_CustomerUID         = associateCustomerAsset.CustomerUID,
                        Fk_AssetUID            = associateCustomerAsset.AssetUID,
                        fk_AssetRelationTypeID = (int)relationType,
                        LastCustomerUTC        = DateTime.UtcNow
                    };

                    var actions = new List <Action>()
                    {
                        () => transaction.Upsert(assetCustomer),
                        () => transaction.Publish(messages)
                    };
                    return(transaction.Execute(actions));
                }

                logger.LogInformation($"Skipping the CustomerAsset Association as the required customeruid" +
                                      $" {associateCustomerAsset.CustomerUID} has not been received yet.");
                return(false);
            }
            catch (Exception ex)
            {
                logger.LogError($"Error while associating asset to customer : {ex.Message}, {ex.StackTrace}");
                throw;
            }
        }
Exemplo n.º 3
0
        public bool CreateAssetSubscriptions(List <CreateAssetSubscriptionEvent> createSubscriptionList)
        {
            SubscriptionSource subscriptionSource;
            var kafkaMessageList = new List <KafkaMessage>();
            var currentUtc       = DateTime.UtcNow;

            var subscriptionList = new List <DbAssetSubscription>();

            foreach (var createSubscription in createSubscriptionList)
            {
                if (createSubscription.SubscriptionType == null ||
                    !_assetSubscriptionTypeCache.ContainsKey(createSubscription.SubscriptionType))
                {
                    throw new Exception("Invalid Asset Subscription Type for the SubscriptionUID:- " +
                                        createSubscription.SubscriptionUID);
                }

                Enum.TryParse(createSubscription.Source, true, out subscriptionSource);
                var createSubscriptionModel = new DbAssetSubscription
                {
                    AssetSubscriptionUID    = createSubscription.SubscriptionUID.Value,
                    fk_AssetUID             = createSubscription.AssetUID.Value,
                    fk_DeviceUID            = createSubscription.DeviceUID.Value,
                    fk_CustomerUID          = createSubscription.CustomerUID.Value,
                    fk_SubscriptionSourceID = (int)subscriptionSource,
                    StartDate         = createSubscription.StartDate.Value,
                    EndDate           = createSubscription.EndDate.Value,
                    InsertUTC         = currentUtc,
                    UpdateUTC         = currentUtc,
                    fk_ServiceTypeID  = _assetSubscriptionTypeCache[createSubscription.SubscriptionType],
                    LastProcessStatus = 0
                };
                subscriptionList.Add(createSubscriptionModel);

                topics.ToList().ForEach(topic =>
                {
                    var kafkaMessage = new KafkaMessage()
                    {
                        Key     = createSubscription.SubscriptionUID.ToString(),
                        Message = new { CreateAssetSubscriptionEvent = createSubscription },
                        Topic   = topic
                    };
                    kafkaMessageList.Add(kafkaMessage);
                });
            }

            var actions = new List <Action>();

            actions.Add(() => transaction.Upsert <DbAssetSubscription>(subscriptionList));
            actions.Add(() => transaction.Publish(kafkaMessageList));

            return(transaction.Execute(actions));
        }
Exemplo n.º 4
0
        public bool CreateAsset(CreateAssetEvent asset)
        {
            try
            {
                var owningCustomerUID = asset.OwningCustomerUID.HasValue ?
                                        asset.OwningCustomerUID.Value : new Guid();

                DateTime actionUTC = DateTime.UtcNow;

                //Db Object
                var assetObject = new DbModel.AssetPayload
                {
                    AssetUID                = new Guid(asset.AssetUID.ToString()),
                    OwningCustomerUID       = owningCustomerUID,
                    AssetName               = string.IsNullOrWhiteSpace(asset.AssetName) ? null : asset.AssetName,
                    LegacyAssetID           = asset.LegacyAssetID == -9999999 ? 0 : asset.LegacyAssetID,
                    SerialNumber            = asset.SerialNumber,
                    MakeCode                = asset.MakeCode,
                    Model                   = string.IsNullOrWhiteSpace(asset.Model) ? null : asset.Model,
                    AssetTypeName           = string.IsNullOrWhiteSpace(asset.AssetType) ? null : asset.AssetType,
                    IconKey                 = asset.IconKey == -9999999 ? null : asset.IconKey,
                    EquipmentVIN            = string.IsNullOrWhiteSpace(asset.EquipmentVIN) ? null : asset.EquipmentVIN,
                    ModelYear               = asset.ModelYear == -9999999 ? null : asset.ModelYear,
                    InsertUTC               = actionUTC,
                    UpdateUTC               = actionUTC,
                    StatusInd               = true,
                    ObjectType              = asset.ObjectType,
                    Category                = asset.Category,
                    ProjectStatus           = asset.ProjectStatus,
                    SortField               = asset.SortField,
                    Source                  = asset.Source,
                    UserEnteredRuntimeHours = asset.UserEnteredRuntimeHours,
                    Classification          = asset.Classification,
                    PlanningGroup           = asset.PlanningGroup
                };

                var actions = new List <Action>()
                {
                    () => _transaction.Upsert(assetObject),
                    () => _transaction.Publish(GetGetAssetSourceSnapshotTopublish(assetObject, asset.ReceivedUTC.Value, false))
                };
                return(_transaction.Execute(actions));
            }
            catch (MySqlException ex)
            {
                _logger.LogError("error while creating asset in db: ", ex);
                throw ex;
            }
            finally
            {
            }
        }
Exemplo n.º 5
0
        public bool PublishMessage(string kafkaKey, IEnumerable <object> kafkaObjects, string deviceFamily)
        {
            var isPublished = false;

            if (!String.IsNullOrEmpty(deviceFamily))
            {
                if (!_topicNames.ContainsKey(deviceFamily))
                {
                    return(isPublished);
                }

                var payloadMessages = kafkaObjects.Select(x => new KafkaMessage
                {
                    Key     = kafkaKey,
                    Message = string.Format(ObjectEmbedder, x.GetType().Name, JsonConvert.SerializeObject(x)),
                    Topic   = _topicNames[deviceFamily]
                }).ToList();

                _transaction.Publish(payloadMessages);
                isPublished = true;
            }
            else
            {
                foreach (var kafkaObject in kafkaObjects.GroupBy(x => x.GetType()))
                {
                    if (kafkaObject.Any())
                    {
                        var topic = _topicNames[kafkaObject.FirstOrDefault().GetType().Name];

                        var payloadMessages = kafkaObject.Select(x => new KafkaMessage
                        {
                            Key     = kafkaKey,
                            Message = JsonConvert.SerializeObject(x),
                            Topic   = topic
                        }).ToList();

                        _transaction.Publish(payloadMessages);
                        isPublished = true;
                    }
                    else
                    {
                        isPublished = false;
                    }
                }
            }
            return(isPublished);
        }
Exemplo n.º 6
0
 public bool publishAssetWeeklySettings(List <AssetWeeklyTargetsDto> targets)
 {
     try
     {
         _loggingService.Debug("Started Publishing Asset Weekly Settings", "AssetSettingsPublisher.publishAssetWeeklySettings");
         List <KafkaMessage> msgs = new List <KafkaMessage>();
         foreach (var target in targets)
         {
             _loggingService.Debug(string.Format("Current Target : {0}", JsonConvert.SerializeObject(target)), "AssetSettingsPublisher.publishAssetWeeklySettings");
             var createAssetWeeklyTargetEvent = new AssetWeeklyTargetEvent
             {
                 AssetTargetUID       = target.AssetTargetUID,
                 AssetUID             = target.AssetUID,
                 EndDate              = target.EndDate,
                 StartDate            = target.StartDate,
                 SundayTargetValue    = target.SundayTargetValue,
                 MondayTargetValue    = target.MondayTargetValue,
                 TuesdayTargetValue   = target.TuesdayTargetValue,
                 WednesdayTargetValue = target.WednesdayTargetValue,
                 ThursdayTargetValue  = target.ThursdayTargetValue,
                 FridayTargetValue    = target.FridayTargetValue,
                 SaturdayTargetValue  = target.SaturdayTargetValue,
                 TargetType           = target.TargetType,
                 InsertUTC            = DateTime.UtcNow,
                 StatusInd            = target.Status,
                 UpdateUTC            = DateTime.UtcNow
             };
             _loggingService.Debug(string.Format("Message To Be Published to Kafka :- {0} ", JsonConvert.SerializeObject(new KafkaMessage {
                 Key = target.AssetUID.ToString(), Message = createAssetWeeklyTargetEvent, Topic = _assetWeeklySettingsTopic
             })), "AssetSettingsPublisher.publishAssetWeeklySettings");
             msgs.Add(new KafkaMessage {
                 Key = target.AssetUID.ToString(), Message = createAssetWeeklyTargetEvent, Topic = _assetWeeklySettingsTopic
             });
         }
         _transactions.Publish(msgs);
         _loggingService.Debug(string.Format("Weekly Settings Published to Kafka :- {0} ", JsonConvert.SerializeObject(msgs)), "AssetSettingsPublisher.publishAssetWeeklySettings");
         return(true);
     }
     catch (Exception ex)
     {
         this._loggingService.Error("An Exception has occurred ", MethodInfo.GetCurrentMethod().Name, ex);
         return(false);
     }
 }
Exemplo n.º 7
0
        public bool AssociateCustomerUser(AssociateCustomerUserEvent associateCustomerUser)
        {
            try
            {
                var customer = GetCustomer(associateCustomerUser.CustomerUID);
                if (customer?.CustomerID > 0)
                {
                    List <KafkaMessage> messages = CustomerTopics
                                                   ?.Select(topic => new KafkaMessage
                    {
                        Key     = associateCustomerUser.CustomerUID.ToString(),
                        Message = new { AssociateCustomerUserEvent = associateCustomerUser },
                        Topic   = topic
                    })
                                                   ?.ToList();

                    var userCustomer = new DbUserCustomer
                    {
                        fk_CustomerID  = customer.CustomerID,
                        fk_CustomerUID = associateCustomerUser.CustomerUID,
                        fk_UserUID     = associateCustomerUser.UserUID,
                        LastUserUTC    = DateTime.UtcNow
                    };

                    var actions = new List <Action>
                    {
                        () => transaction.Upsert(userCustomer),
                        () => transaction.Publish(messages)
                    };
                    return(transaction.Execute(actions));
                }

                return(false);
            }
            catch (Exception ex)
            {
                logger.LogError($"Error while associating user for customer : {ex.Message}, {ex.StackTrace}");
                throw;
            }
        }
Exemplo n.º 8
0
        public bool CreateAccount(CreateCustomerEvent createAccount)
        {
            try
            {
                FieldHelper.ReplaceEmptyFieldsByNull(createAccount);

                var message = new KafkaMessage
                {
                    Key     = createAccount.CustomerUID.ToString(),
                    Topic   = AccountTopic,
                    Message = new
                    {
                        AccountEvent = new AccountEvent
                        {
                            AccountName         = createAccount.CustomerName,
                            AccountUID          = createAccount.CustomerUID,
                            Action              = Operation.Create.ToString(),
                            BSSID               = createAccount.BSSID,
                            DealerAccountCode   = createAccount.DealerAccountCode,
                            NetworkCustomerCode = createAccount.NetworkCustomerCode,
                            ActionUTC           = createAccount.ActionUTC,
                            ReceivedUTC         = createAccount.ReceivedUTC
                        }
                    }
                };

                var accountObj = new DbAccount
                {
                    CustomerAccountUID = createAccount.CustomerUID,
                    BSSID               = createAccount.BSSID,
                    AccountName         = createAccount.CustomerName,
                    NetworkCustomerCode = createAccount.NetworkCustomerCode,
                    DealerAccountCode   = createAccount.DealerAccountCode,
                    RowUpdatedUTC       = DateTime.UtcNow
                };

                var actions = new List <Action>()
                {
                    () => transaction.Upsert(accountObj),
                    () => transaction.Publish(message)
                };
                return(transaction.Execute(actions));
            }
            catch (Exception ex)
            {
                logger.LogError($"Error while creating account customer : {ex.Message}, {ex.StackTrace}");
                throw;
            }
        }
Exemplo n.º 9
0
        public bool?CreateUserPreference(CreateUserPreferenceEvent userPreference)
        {
            var preference = GetPreferenceKey(userPreference.PreferenceKeyUID, userPreference.PreferenceKeyName);

            if (preference == null || userPreference.PreferenceKeyUID.HasValue &&
                !preference.PreferenceKeyUID.Equals(userPreference.PreferenceKeyUID))
            {
                return(null);
            }

            if (string.IsNullOrEmpty(userPreference.SchemaVersion))
            {
                userPreference.SchemaVersion = "1.0";
            }

            var currentUtc           = DateTime.UtcNow;
            var insertUserPreference = new DbUserPreference()
            {
                fk_UserUID         = userPreference.UserUID,
                fk_PreferenceKeyID = preference.PreferenceKeyID,
                PreferenceValue    = userPreference.PreferenceJson,
                SchemaVersion      = userPreference.SchemaVersion,
                InsertUTC          = currentUtc,
                UpdateUTC          = currentUtc
            };

            var kafkaMessage = new KafkaMessage()
            {
                Key     = userPreference.UserUID.ToString(),
                Message = new { CreateUserPreferenceEvent = userPreference }
            };

            var actions = new List <Action>();

            actions.Add(() => transaction.Upsert <DbUserPreference>(insertUserPreference));
            actions.Add(() => topics.ToList().ForEach(topic =>
            {
                kafkaMessage.Topic = topic;
                transaction.Publish(kafkaMessage);
            }));

            return(transaction.Execute(actions));
        }
Exemplo n.º 10
0
        public bool CreateDevice(CreateDeviceEvent device, DeviceStateEnum deviceState)
        {
            DbDeviceType deviceType = deviceTypesCache.First(x => string.Equals(x.Key, device.DeviceType, StringComparison.InvariantCultureIgnoreCase)).Value;

            var currentUTC    = DateTime.UtcNow;
            var devicePayload = new CreateDevicePayload
            {
                ActionUTC     = currentUTC,
                CellModemIMEI = device.CellModemIMEI,
                CellularFirmwarePartnumber = device.CellularFirmwarePartnumber,
                DataLinkType                = device.DataLinkType,
                DeviceState                 = deviceState.ToString(),
                DeregisteredUTC             = device.DeregisteredUTC,
                DevicePartNumber            = device.DevicePartNumber,
                DeviceSerialNumber          = device.DeviceSerialNumber,
                DeviceType                  = device.DeviceType,
                DeviceUID                   = device.DeviceUID.Value,
                FirmwarePartNumber          = device.FirmwarePartNumber,
                GatewayFirmwarePartNumber   = device.GatewayFirmwarePartNumber,
                MainboardSoftwareVersion    = device.MainboardSoftwareVersion,
                ModuleType                  = device.ModuleType,
                NetworkFirmwarePartnumber   = device.NetworkFirmwarePartnumber,
                RadioFirmwarePartNumber     = device.RadioFirmwarePartNumber,
                ReceivedUTC                 = device.ReceivedUTC,
                SatelliteFirmwarePartnumber = device.SatelliteFirmwarePartnumber
            };

            var devicePersonality = GetDevicePersonalities(devicePayload, null, deviceType);

            devicePayload = SetNullIfPropertyEmpty(devicePayload);
            //DeviceSerialNumber will be persisited as NULL in masterdata and send it as Empty to Kafka
            devicePayload.DeviceSerialNumber = string.IsNullOrEmpty(devicePayload.DeviceSerialNumber) ? string.Empty : devicePayload.DeviceSerialNumber;
            var deviceModel = new DbDevice
            {
                SerialNumber              = devicePayload.DeviceSerialNumber,
                DeregisteredUTC           = devicePayload.DeregisteredUTC,
                ModuleType                = devicePayload.ModuleType,
                fk_DeviceStatusID         = deviceState.GetHashCode(),
                MainboardSoftwareVersion  = devicePayload.MainboardSoftwareVersion,
                FirmwarePartNumber        = devicePayload.RadioFirmwarePartNumber == null ? devicePayload.FirmwarePartNumber : devicePayload.RadioFirmwarePartNumber,
                GatewayFirmwarePartNumber = devicePayload.GatewayFirmwarePartNumber,
                DataLinkType              = devicePayload.DataLinkType,
                InsertUTC                   = currentUTC,
                UpdateUTC                   = currentUTC,
                fk_DeviceTypeID             = deviceType.DeviceTypeID,
                CellModemIMEI               = devicePayload.CellModemIMEI,
                DevicePartNumber            = devicePayload.DevicePartNumber,
                CellularFirmwarePartnumber  = devicePayload.CellularFirmwarePartnumber,
                NetworkFirmwarePartnumber   = devicePayload.NetworkFirmwarePartnumber,
                SatelliteFirmwarePartnumber = devicePayload.SatelliteFirmwarePartnumber,
                DeviceUID                   = devicePayload.DeviceUID
            };

            var kafkaMessageList = new List <KafkaMessage>();

            kafkaTopicNames.ForEach(topic =>
            {
                var kafkaMessage = new KafkaMessage()
                {
                    Key     = device.DeviceUID.ToString(),
                    Message = new { CreateDeviceEvent = mapper.Map <CreateDevicePayload, CreateDeviceEvent>(devicePayload) },
                    Topic   = topic
                };
                kafkaMessageList.Add(kafkaMessage);
            });

            kafkaTopicNamesV2.ForEach(topic =>
            {
                var kafkaMessage = new KafkaMessage()
                {
                    Key     = device.DeviceUID.ToString(),
                    Message = ToDevicePayloadV2(devicePayload, devicePersonality),
                    Topic   = topic
                };
                kafkaMessageList.Add(kafkaMessage);
            });


            var actions = new List <Action>();

            actions.Add(() => transactions.Upsert(deviceModel));
            actions.Add(() => transactions.Upsert <DbDevicePersonality>(devicePersonality));
            actions.Add(() => transactions.Publish(kafkaMessageList));

            return(transactions.Execute(actions));
        }
Exemplo n.º 11
0
        public virtual bool CreateAssetOwnerEvent(AssetOwnerEvent assetOwnerEvent)
        {
            string networkCustomerCode = string.IsNullOrWhiteSpace(assetOwnerEvent.AssetOwnerRecord.NetworkCustomerCode) ? null : assetOwnerEvent.AssetOwnerRecord.NetworkCustomerCode;
            string dealerAccountCode   = string.IsNullOrWhiteSpace(assetOwnerEvent.AssetOwnerRecord.DealerAccountCode) ? null : assetOwnerEvent.AssetOwnerRecord.DealerAccountCode;
            string networkDealerCode   = string.IsNullOrWhiteSpace(assetOwnerEvent.AssetOwnerRecord.NetworkDealerCode)? null : assetOwnerEvent.AssetOwnerRecord.NetworkDealerCode;
            string accountName         = string.IsNullOrWhiteSpace(assetOwnerEvent.AssetOwnerRecord.AccountName)? null : assetOwnerEvent.AssetOwnerRecord.AccountName;
            string dealerName          = string.IsNullOrWhiteSpace(assetOwnerEvent.AssetOwnerRecord.DealerName)? null : assetOwnerEvent.AssetOwnerRecord.DealerName;
            string customerName        = string.IsNullOrWhiteSpace(assetOwnerEvent.AssetOwnerRecord.CustomerName)? null : assetOwnerEvent.AssetOwnerRecord.CustomerName;

            Guid?customerUid = assetOwnerEvent.AssetOwnerRecord.CustomerUID == null || assetOwnerEvent.AssetOwnerRecord.CustomerUID == Guid.Empty ? (Guid?)null : assetOwnerEvent.AssetOwnerRecord.CustomerUID;
            Guid?accountUid  = assetOwnerEvent.AssetOwnerRecord.AccountUID == null || assetOwnerEvent.AssetOwnerRecord.AccountUID == Guid.Empty ? (Guid?)null : assetOwnerEvent.AssetOwnerRecord.AccountUID;
            Guid?dealerUid   = assetOwnerEvent.AssetOwnerRecord.DealerUID == Guid.Empty ? (Guid?)null : assetOwnerEvent.AssetOwnerRecord.DealerUID;

            try
            {
                var assetOwnerPayload = new AssetOwnerEvent
                {
                    AssetUID         = assetOwnerEvent.AssetUID,
                    AssetOwnerRecord = new ClientModel.AssetOwner
                    {
                        NetworkCustomerCode = networkCustomerCode,
                        DealerAccountCode   = dealerAccountCode,
                        NetworkDealerCode   = networkDealerCode,
                        AccountName         = accountName,
                        DealerName          = dealerName,
                        DealerUID           = dealerUid,
                        CustomerName        = customerName,
                        CustomerUID         = customerUid,
                        AccountUID          = accountUid
                    },
                    Action      = Operation.Create,
                    ActionUTC   = DateTime.UtcNow,
                    ReceivedUTC = DateTime.UtcNow
                };

                var assetOwnerDBModel = GetAssetOwnerDBModel(assetOwnerPayload);

                var message = new KafkaMessage
                {
                    Key     = assetOwnerEvent.AssetUID.ToString(),
                    Message = new {
                        AssetUID         = assetOwnerEvent.AssetUID,
                        AssetOwnerRecord = new ClientModel.AssetOwner
                        {
                            NetworkCustomerCode = networkCustomerCode,
                            DealerAccountCode   = dealerAccountCode,
                            NetworkDealerCode   = networkDealerCode,
                            AccountName         = accountName,
                            DealerName          = dealerName,
                            DealerUID           = assetOwnerEvent.AssetOwnerRecord.DealerUID,
                            CustomerName        = customerName,
                            CustomerUID         = customerUid,
                            AccountUID          = accountUid
                        },
                        Action      = "Create",
                        ActionUTC   = assetOwnerDBModel.UpdateUTC,
                        ReceivedUTC = assetOwnerDBModel.UpdateUTC
                    }
                };

                var actions = new List <Action>()
                {
                    () => _transaction.Upsert(assetOwnerDBModel),
                    () => assetOwnerTopicNames?.ForEach((topic) => { message.Topic = topic; _transaction.Publish(message); })
                };
                _logger.LogInformation($"Create Asset Owner: {JsonSerializer.Serialize(assetOwnerPayload)}");

                return(_transaction.Execute(actions));
            }
            catch (MySqlException ex)
            {
                _logger.LogError("error while creating asset in db: ", ex);
                throw ex;
            }
            finally
            {
            }
        }