public bool HasNotification(int itemId)
        {
            try
            {
                int count = 0;
                IndustrialMonitoringEntities entities = new IndustrialMonitoringEntities();

                List <NotificationItemsLogLatest> notificationItemsLogLatests = entities.NotificationItemsLogLatests.ToList();

                foreach (NotificationItemsLogLatest item in notificationItemsLogLatests)
                {
                    if (item.NotificationItem.DisableNotification)
                    {
                        return(false);
                    }

                    if (item.NotificationItem.ItemId == itemId & item.Value == false)
                    {
                        return(true);
                    }
                }

                return(false);
            }
            catch (Exception ex)
            {
                Logger.LogMonitoringServiceLibrary(ex);
                return(false);
            }
        }
示例#2
0
        public bool DeleteItemLog(int itemLogId)
        {
            try
            {
                IndustrialMonitoringEntities entities = new IndustrialMonitoringEntities();
                var Item = entities.ItemsLogs.FirstOrDefault(x => x.ItemLogId == itemLogId);

                if (Item != null)
                {
                    entities.ItemsLogs.Remove(Item);
                    entities.SaveChanges();
                    return(true);
                }
                else
                {
                    var Item2 = entities.ItemsLogArchives.FirstOrDefault(x => x.ItemLogId == itemLogId);

                    if (Item2 != null)
                    {
                        entities.ItemsLogArchives.Remove(Item2);
                        entities.SaveChanges();
                        return(true);
                    }
                }

                return(false);
            }
            catch (Exception ex)
            {
                Logger.LogMonitoringServiceLibrary(ex);
                return(false);
            }
        }
示例#3
0
        public List <ItemsLogChartHistoryViewModel> GetItemLogs(int itemId, DateTime startDate, DateTime endDate)
        {
            var Entities = new IndustrialMonitoringEntities();
            List <ItemsLogChartHistoryViewModel> result = new List <ItemsLogChartHistoryViewModel>();

            var itemsLog1 = Entities.ItemsLogs.Where(x => x.ItemId == itemId & x.Time >= startDate & x.Time <= endDate).OrderBy(x => x.ItemLogId);
            var itemsLog2 = Entities.ItemsLogArchives.Where(x => x.ItemId == itemId & x.Time >= startDate & x.Time <= endDate).OrderBy(x => x.ItemLogId);

            List <ItemsLog> itemsLog = new List <ItemsLog>();

            itemsLog.AddRange(itemsLog1);

            foreach (ItemsLogArchive itemsLogArchive in itemsLog2)
            {
                ItemsLog log2 = new ItemsLog();
                log2.ItemId    = itemsLogArchive.ItemId;
                log2.Value     = itemsLogArchive.Value;
                log2.Time      = itemsLogArchive.Time;
                log2.ItemLogId = itemsLogArchive.ItemLogId;

                itemsLog.Add(log2);
            }

            var itemsLogAll = itemsLog.OrderBy(x => x.Time);

            foreach (var log in itemsLogAll)
            {
                result.Add(new ItemsLogChartHistoryViewModel(log));
            }

            return(result);
        }
示例#4
0
        public bool AddItem2(Item2 item)
        {
            try
            {
                IndustrialMonitoringEntities entities = new IndustrialMonitoringEntities();

                Item newItem = new Item();
                newItem.ItemName = item.ItemName;
                newItem.ItemType = (int)item.ItemType;
                newItem.Location = item.Location;
                newItem.SaveInItemsLogTimeInterval       = item.SaveInItemsLogTimeInterval;
                newItem.SaveInItemsLogLastesTimeInterval = item.SaveInItemsLogLastesTimeInterval;
                newItem.ShowInUITimeInterval             = item.ShowInUITimeInterval;
                newItem.ScanCycle              = item.ScanCycle;
                newItem.SaveInItemsLogWhen     = (int)item.SaveInItemsLogWhen;
                newItem.SaveInItemsLogLastWhen = (int)item.SaveInItemsLogLastWhen;

                entities.Items.Add(newItem);

                if (entities.SaveChanges() > 0)
                {
                    return(true);
                }


                return(false);
            }
            catch (Exception ex)
            {
                Logger.LogMonitoringServiceLibrary(ex);
                return(false);
            }
        }
        public int SetPassword(int userId, string oldPassword, string newPassword)
        {
            try
            {
                IndustrialMonitoringEntities entities = new IndustrialMonitoringEntities();
                var user = entities.Users.FirstOrDefault(x => x.UserId == userId);

                if (user == null)
                {
                    return(-1);
                }

                string pass2 = GetHash(oldPassword);
                if (user.Password != pass2)
                {
                    return(-2);
                }

                user.Password = GetHash(newPassword);

                entities.SaveChanges();
                return(1);
            }
            catch (Exception ex)
            {
                // TODO log
                return(0);
            }
        }
示例#6
0
        public Item1 GetItem(int itemId)
        {
            var   Entities = new IndustrialMonitoringEntities();
            var   item     = Entities.Items.FirstOrDefault(x => x.ItemId == itemId);
            Item1 result   = new Item1(item);

            return(result);
        }
        public UserViewModel GetUserByUserId(int userId)
        {
            UserViewModel result   = null;
            var           Entities = new IndustrialMonitoringEntities();
            User          user     = Entities.Users.FirstOrDefault(x => x.UserId == userId);

            result = new UserViewModel(user);

            return(result);
        }
        public bool CheckPermission(int userId, int itemId)
        {
            var Entities = new IndustrialMonitoringEntities();

            if (Entities.UsersItemsPermissions.Any(x => x.UserId == userId & x.ItemId == itemId))
            {
                return(true);
            }

            return(false);
        }
        public bool Authorize(string userName, string password)
        {
            var    Entities = new IndustrialMonitoringEntities();
            string pass2    = GetHash(password);

            if (Entities.Users.Any(x => x.UserName == userName & x.Password == pass2))
            {
                return(true);
            }

            return(false);
        }
 public User GetUserFromSession(string sessionKey)
 {
     try
     {
         var  entities = new IndustrialMonitoringEntities();
         User user     = entities.Sessions.FirstOrDefault(x => x.SessionKey == sessionKey).User;
         return(user);
     }
     catch (Exception ex)
     {
         Logger.LogMonitoringServiceLibrary(ex);
         return(null);
     }
 }
        public List <NotificationLog> GetNotificationLog(int userId, int itemId, DateTime startTime, DateTime endTime)
        {
            try
            {
                IndustrialMonitoringEntities entities = new IndustrialMonitoringEntities();

                List <NotificationItemsLog> notificationItemsLogs =
                    entities.NotificationItemsLogs.Where(x => x.Time >= startTime & x.Time <= endTime).OrderByDescending(x => x.Time).ToList();

                List <UsersItemsPermission> usersItemsPermissions =
                    entities.UsersItemsPermissions.Where(x => x.UserId == userId).ToList();

                List <NotificationLog> result = new List <NotificationLog>();


                foreach (NotificationItemsLog log in notificationItemsLogs)
                {
                    if (log.NotificationItem.ItemId == itemId)
                    {
                        if (usersItemsPermissions.Any(x => x.ItemId == log.NotificationItem.ItemId))
                        {
                            int      itemId2         = log.NotificationItem.ItemId;
                            string   itemName        = log.NotificationItem.Item.ItemName;
                            string   notificationMsg = log.NotificationItem.NotificationMsg;
                            DateTime dateTime        = log.Time;
                            bool     hasFault        = !log.Value;

                            var    tabsItem = entities.TabsItems.FirstOrDefault(x => x.ItemId == itemId);
                            string category = "";

                            if (tabsItem != null)
                            {
                                category = tabsItem.Tab.TabName;
                            }

                            NotificationLog notificationLog = new NotificationLog(itemId2, itemName, notificationMsg, dateTime, hasFault, category);

                            result.Add(notificationLog);
                        }
                    }
                }

                return(result);
            }
            catch (Exception ex)
            {
                Logger.LogMonitoringServiceLibrary(ex);
                return(null);
            }
        }
        public List <User2> GetUsers2()
        {
            IndustrialMonitoringEntities entities = new IndustrialMonitoringEntities();
            var usersQuery = entities.Users;

            List <User2> result = new List <User2>();

            foreach (User user in usersQuery)
            {
                User2 users2 = new User2(user);
                result.Add(users2);
            }

            return(result);
        }
示例#13
0
        public List <Tab1> GetTabs()
        {
            List <Tab1> result   = new List <Tab1>();
            var         Entities = new IndustrialMonitoringEntities();
            var         tabs     = Entities.Tabs.OrderBy(x => x.Order);

            foreach (var tab in tabs)
            {
                Tab1 current = new Tab1(tab);

                result.Add(current);
            }

            return(result);
        }
示例#14
0
        public List <TabsItemsViewModel> GetTabItems()
        {
            var Entities = new IndustrialMonitoringEntities();
            List <TabsItemsViewModel> result = new List <TabsItemsViewModel>();

            var tabItems = Entities.TabsItems.OrderBy(x => x.Item.Order);

            foreach (var tabsItem in tabItems)
            {
                TabsItemsViewModel current = new TabsItemsViewModel(tabsItem);
                result.Add(current);
            }

            return(result);
        }
示例#15
0
        public List <Item1> GetItems(int tabId)
        {
            var          Entities = new IndustrialMonitoringEntities();
            List <Item1> result   = new List <Item1>();

            var tabsItem = Entities.TabsItems.Where(x => x.TabId == tabId).OrderBy(x => x.Item.ItemName);

            foreach (var item in tabsItem)
            {
                Item currentItem = Entities.Items.FirstOrDefault(x => x.ItemId == item.ItemId);

                result.Add(new Item1(currentItem));
            }

            return(result);
        }
        public bool SystemHasNotification(int userId)
        {
            try
            {
                IndustrialMonitoringEntities entities = new IndustrialMonitoringEntities();

                var notifications = entities.NotificationItemsLogLatests.ToList();

                if (notifications == null || notifications.Count == 0)
                {
                    return(false);
                }

                List <int> ItemIds = new List <int>();

                foreach (NotificationItemsLogLatest notification in notifications)
                {
                    if (!notification.Value)
                    {
                        ItemIds.Add(notification.NotificationItem.ItemId);
                    }
                }

                List <int> ItemIdsForCurrentUser = new List <int>();

                foreach (int itemId in ItemIds)
                {
                    if (entities.UsersItemsPermissions.Any(x => x.UserId == userId & x.ItemId == itemId))
                    {
                        ItemIdsForCurrentUser.Add(itemId);
                    }
                }

                if (ItemIdsForCurrentUser.Count > 0)
                {
                    return(true);
                }

                return(false);
            }
            catch (Exception ex)
            {
                Logger.LogMonitoringServiceLibrary(ex);
                return(false);
            }
        }
        public bool UserHaveItemInTab(int userId, int tabId)
        {
            var Entities = new IndustrialMonitoringEntities();
            var userItemsPermissionQuery = Entities.UsersItemsPermissions.Where(x => x.UserId == userId);

            foreach (var u in userItemsPermissionQuery)
            {
                bool tabExist = Entities.TabsItems.Any(x => x.ItemId == u.ItemId & x.TabId == tabId);

                if (tabExist)
                {
                    return(true);
                }
            }

            return(false);
        }
        public List <string> TabsWithActiveNotification(int userId)
        {
            try
            {
                IndustrialMonitoringEntities entities = new IndustrialMonitoringEntities();

                List <string> result = new List <string>();

                var notifications = entities.NotificationItemsLogLatests.ToList();

                if (notifications == null || notifications.Count == 0)
                {
                    return(result);
                }

                List <int> ItemIds = new List <int>();

                foreach (NotificationItemsLogLatest notification in notifications)
                {
                    if (!notification.Value)
                    {
                        ItemIds.Add(notification.NotificationItem.ItemId);
                    }
                }

                foreach (int itemId in ItemIds)
                {
                    if (entities.UsersItemsPermissions.Any(x => x.UserId == userId & x.ItemId == itemId))
                    {
                        var tabItem = entities.TabsItems.FirstOrDefault(x => x.ItemId == itemId);
                        if (tabItem != null)
                        {
                            result.Add(tabItem.Tab.TabName);
                        }
                    }
                }

                return(result);
            }
            catch (Exception ex)
            {
                Logger.LogMonitoringServiceLibrary(ex);
                return(null);
            }
        }
示例#19
0
        public List <Tab1> GetTabs(Func <Tab1, bool> predicate)
        {
            var         Entities = new IndustrialMonitoringEntities();
            List <Tab1> result   = new List <Tab1>();

            var tabs = Entities.Tabs.OrderBy(x => x.Order);

            foreach (var tab in tabs)
            {
                Tab1 current = new Tab1(tab);

                if (predicate(current))
                {
                    result.Add(current);
                }
            }

            return(result);
        }
示例#20
0
        public bool AddItemsToTab(string tabName, List <string> items)
        {
            try
            {
                IndustrialMonitoringEntities entities = new IndustrialMonitoringEntities();

                bool success = false;

                using (TransactionScope transaction = new TransactionScope())
                {
                    try
                    {
                        Tab currenTab = entities.Tabs.FirstOrDefault(x => x.TabName == tabName);

                        foreach (var item in items)
                        {
                            Item     currentItem = entities.Items.FirstOrDefault(x => x.ItemName == item);
                            TabsItem newTabsItem = new TabsItem();
                            newTabsItem.ItemId = currentItem.ItemId;
                            newTabsItem.TabId  = currenTab.TabId;

                            entities.TabsItems.Add(newTabsItem);
                            entities.SaveChanges();
                        }

                        transaction.Complete();
                        success = true;
                    }
                    catch (Exception ex)
                    {
                        throw ex;
                    }
                }

                return(success);
            }
            catch (Exception ex)
            {
                Logger.LogMonitoringServiceLibrary(ex);
                return(false);
            }
        }
        public void Run()
        {
            IndustrialMonitoringEntities entities = new IndustrialMonitoringEntities();

            var listCommands = entities.OpcBooleanCommands.ToList();

            foreach (OpcBooleanCommand command in listCommands)
            {
                var location = command.Location;
                var value    = command.CommandValue;

                if (command.PreviousRun == null)
                {
                    var writer = new NetworkVariableBufferedWriter <bool>(location);
                    writer.Connect();
                    writer.WriteValue(value);
                    writer.Disconnect();

                    command.PreviousRun = DateTime.Now;
                    entities.SaveChanges();
                }
                else
                {
                    var datetime2 = DateTime.Now;
                    var datetime1 = command.PreviousRun;
                    var interval  = command.Interval;

                    var diff = datetime2 - datetime1;

                    if (diff.Value.TotalSeconds > interval)
                    {
                        var writer = new NetworkVariableBufferedWriter <bool>(location);
                        writer.Connect();
                        writer.WriteValue(value);
                        writer.Disconnect();

                        command.PreviousRun = DateTime.Now;
                        entities.SaveChanges();
                    }
                }
            }
        }
示例#22
0
        public List <Item3> GetItems3()
        {
            try
            {
                List <Item3> result   = new List <Item3>();
                var          Entities = new IndustrialMonitoringEntities();
                var          items    = Entities.Items.OrderBy(x => x.Order);

                foreach (var item in items)
                {
                    result.Add(new Item3(item));
                }

                return(result);
            }
            catch (Exception ex)
            {
                Logger.LogMonitoringServiceLibrary(ex);
                return(null);
            }
        }
        public string AuthorizeAndGetSession(string username, string password)
        {
            bool isAuthorized = Authorize(username, password);

            if (isAuthorized)
            {
                var entities = new IndustrialMonitoringEntities();
                var user     = entities.Users.FirstOrDefault(x => x.UserName == username);

                Session session = new Session();
                session.SessionKey = Guid.NewGuid().ToString();
                session.UserId     = user.UserId;
                session.IsValid    = true;

                entities.Sessions.Add(session);
                entities.SaveChanges();

                return(session.SessionKey);
            }

            return("");
        }
        public List <int> GetUserServicesPermission(int userId)
        {
            try
            {
                IndustrialMonitoringEntities entities = new IndustrialMonitoringEntities();
                var permissions = entities.UsersServicesPermissions.Where(x => x.UserId == userId).ToList();

                var ids = new List <int>();

                foreach (UsersServicesPermission u in permissions)
                {
                    ids.Add(u.ServiceId);
                }

                return(ids);
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }

            return(null);
        }
示例#25
0
        public bool EditItem2(Item2 item)
        {
            try
            {
                IndustrialMonitoringEntities entities = new IndustrialMonitoringEntities();

                Item itemToEdit = entities.Items.FirstOrDefault(x => x.ItemId == item.ItemId);

                if (itemToEdit == null)
                {
                    return(false);
                }

                itemToEdit.ItemName = item.ItemName;
                itemToEdit.ItemType = (int)item.ItemType;
                itemToEdit.Location = item.Location;
                itemToEdit.SaveInItemsLogTimeInterval       = item.SaveInItemsLogTimeInterval;
                itemToEdit.SaveInItemsLogLastesTimeInterval = item.SaveInItemsLogLastesTimeInterval;
                itemToEdit.ShowInUITimeInterval             = item.ShowInUITimeInterval;
                itemToEdit.ScanCycle              = item.ScanCycle;
                itemToEdit.SaveInItemsLogWhen     = (int)item.SaveInItemsLogWhen;
                itemToEdit.SaveInItemsLogLastWhen = (int)item.SaveInItemsLogLastWhen;

                if (entities.SaveChanges() > 0)
                {
                    return(true);
                }


                return(false);
            }
            catch (Exception ex)
            {
                Logger.LogMonitoringServiceLibrary(ex);
                return(false);
            }
        }
        public List <Notification1> GetNotifications(int itemId)
        {
            try
            {
                List <Notification1> resultList = new List <Notification1>();

                IndustrialMonitoringEntities entities = new IndustrialMonitoringEntities();

                List <NotificationItem> notificationItems = entities.NotificationItems.Where(x => x.ItemId == itemId).ToList();

                if (notificationItems == null || notificationItems.Count == 0)
                {
                    return(null);
                }

                foreach (var notificationItem in notificationItems)
                {
                    NotificationItemsLogLatest notificationItemsLogLatest =
                        entities.NotificationItemsLogLatests.FirstOrDefault(
                            x => x.NotificationId == notificationItem.NotificationId);

                    if (notificationItemsLogLatest.Value)
                    {
                        Notification1 notification1 = new Notification1(notificationItem);
                        resultList.Add(notification1);
                    }
                }

                return(resultList);
            }
            catch (Exception ex)
            {
                Logger.LogMonitoringServiceLibrary(ex);
                return(null);
            }
        }
示例#27
0
        public ItemsLogLatestAIOViewModel GeItemsLogLatest(int itemId)
        {
            try
            {
                ItemsLogLatestAIOViewModel result = null;

                var            Entities = new IndustrialMonitoringEntities();
                ItemsLogLatest current  = Entities.ItemsLogLatests.FirstOrDefault(x => x.ItemId == itemId);

                if (current == null)
                {
                    return(null);
                }

                result = new ItemsLogLatestAIOViewModel(current);

                return(result);
            }
            catch (Exception ex)
            {
                Logger.LogMonitoringServiceLibrary(ex);
                return(null);
            }
        }
        public async Task ReadValue()
        {
            try
            {
                Entities = new IndustrialMonitoringEntities();

                if (this.DefinationType == ItemDefinationType.SqlDefined)
                {
                    if (this.Type == ItemType.Digital)
                    {
                        SubscriberBool = new NetworkVariableBufferedSubscriber <bool>(this.Location);
                        SubscriberBool.Connect();
                    }
                    else if (this.Type == ItemType.Analog)
                    {
                        SubscriberInt = new NetworkVariableBufferedSubscriber <dynamic>(this.Location);
                        SubscriberInt.Connect();
                    }
                }
                else if (this.DefinationType == ItemDefinationType.BACnet)
                {
                    if (BACnetDevice == null)
                    {
                        this.BACnetDevice = BACnetDevice.Instance;
                    }

                    string     ip       = ItemObj.BACnetIP;
                    int        port     = ItemObj.BACnetPort.Value;
                    IPEndPoint endPoint = new IPEndPoint(IPAddress.Parse(ip), port);
                    uint       instance = (uint)ItemObj.BACnetControllerInstance.Value;

                    DeviceBaCnet = new Device("Device", 0, 0, endPoint, 0, instance);
                }


                string value = "-1000";

                if (this.DefinationType == ItemDefinationType.SqlDefined)
                {
                    if (this.Type == ItemType.Digital)
                    {
                        var data = SubscriberBool.ReadData();
                        value = Convert.ToInt32(data.GetValue()).ToString();
                    }
                    else if (this.Type == ItemType.Analog)
                    {
                        var data = SubscriberInt.ReadData();
                        value = Math.Round(data.GetValue(), 2).ToString();
                    }
                }
                else if (this.DefinationType == ItemDefinationType.CustomDefiend)
                {
                    switch (this.ItemId)
                    {
                    case 10:
                        value = (BSProcessDataServiceClient.GetPreHeatingZoneTemperature() / 10).ToString();
                        break;

                    case 13:
                        value = BSProcessDataServiceClient.GetSterilizerZoneTemperature().ToString();
                        break;

                    case 14:
                        value = (BSProcessDataServiceClient.GetCoolingZoneTemperature() / 10).ToString();
                        break;
                    }
                }
                else if (this.DefinationType == ItemDefinationType.BACnet)
                {
                    if (this.Type == ItemType.Digital)
                    {
                        BACnetEnums.BACNET_OBJECT_TYPE bacnetType = (BACnetEnums.BACNET_OBJECT_TYPE)ItemObj.BACnetItemType.Value;
                        uint itemInstance = (uint)ItemObj.BACnetItemInstance.Value;
                        value = BACnetDevice.ReadValue(DeviceBaCnet, bacnetType, itemInstance).ToString();
                    }
                    else if (Type == ItemType.Analog)
                    {
                        BACnetEnums.BACNET_OBJECT_TYPE bacnetType = (BACnetEnums.BACNET_OBJECT_TYPE)ItemObj.BACnetItemType.Value;
                        uint itemInstance = (uint)ItemObj.BACnetItemInstance.Value;

                        string preValue       = BACnetDevice.ReadValue(DeviceBaCnet, bacnetType, itemInstance).ToString();
                        double preValueDouble = double.Parse(preValue);
                        value = Math.Round(preValueDouble, 2).ToString();
                    }
                }

                lock (padlock)
                {
                    if (value == null)
                    {
                        return;
                    }

                    if (value == "-1000")
                    {
                        return;
                    }

                    double valueDouble = double.Parse(value);

                    bool condition = !string.IsNullOrEmpty(ItemObj.MinRange) && !string.IsNullOrEmpty(ItemObj.MaxRange);
                    if (condition)
                    {
                        double minRange = double.Parse(ItemObj.MinRange);
                        double maxRange = double.Parse(ItemObj.MaxRange);

                        bool shouldNormalize = false;

                        if (ItemObj.NormalizeWhenOutOfRange != null)
                        {
                            shouldNormalize = ItemObj.NormalizeWhenOutOfRange.Value;
                        }

                        if (valueDouble < minRange)
                        {
                            if (shouldNormalize)
                            {
                                value = ItemObj.MinRange;
                            }
                            else
                            {
                                return;
                            }
                        }

                        if (valueDouble > maxRange)
                        {
                            if (shouldNormalize)
                            {
                                value = ItemObj.MaxRange;
                            }
                            else
                            {
                                return;
                            }
                        }
                    }

                    // detect outliers

                    bool isOutlier = false;
                    int  outlierId = 0;

                    int numberOfDataForBoxplot = 0;

                    if (ItemObj.NumberOfDataForBoxplot != null)
                    {
                        numberOfDataForBoxplot = ItemObj.NumberOfDataForBoxplot.Value;
                    }

                    if (numberOfDataForBoxplot > 2)
                    {
                        if (this.Type == ItemType.Analog)
                        {
                            var lastData = Entities.ItemsLogRawDatas.Where(x => x.ItemId == ItemId).OrderByDescending(x => x.ItemLogRawDataId).Take(numberOfDataForBoxplot).ToList();

                            if (lastData.Count > 3)
                            {
                                List <double> lastDataInDouble = new List <double>();

                                foreach (var itemsLog in lastData)
                                {
                                    double currentValue = double.Parse(itemsLog.Value);

                                    lastDataInDouble.Add(currentValue);
                                }

                                var iqr = Statistics.InterquartileRange(lastDataInDouble);
                                var lqr = Statistics.LowerQuartile(lastDataInDouble);
                                var uqr = Statistics.UpperQuartile(lastDataInDouble);


                                if (valueDouble > 3 * iqr + uqr)
                                {
                                    isOutlier = true;
                                }

                                if (valueDouble < lqr - 3 * iqr)
                                {
                                    isOutlier = true;
                                }

                                if (isOutlier)
                                {
                                    LogOutlier logOutlier = new LogOutlier();
                                    logOutlier.ItemId = this.ItemId;
                                    logOutlier.IQR    = iqr.ToString();
                                    logOutlier.LQR    = lqr.ToString();
                                    logOutlier.UQR    = uqr.ToString();
                                    logOutlier.Value  = valueDouble.ToString();
                                    logOutlier.Time   = DateTime.Now;

                                    Entities.LogOutliers.Add(logOutlier);
                                    Entities.SaveChanges();

                                    outlierId = logOutlier.OutlierId;
                                }
                            }
                        }
                    }

                    //


                    // Save in ItemsLogRawData

                    var lastItemLogRaw = Entities.ItemsLogRawDatas.OrderByDescending(x => x.ItemLogRawDataId).FirstOrDefault(x => x.ItemId == ItemId);

                    if (lastItemLogRaw == null)
                    {
                        ItemsLogRawData rawData = new ItemsLogRawData();
                        rawData.ItemId = ItemId;
                        rawData.Value  = value;
                        rawData.Time   = DateTime.Now;

                        if (outlierId > 0)
                        {
                            rawData.OutlierId = outlierId;
                        }

                        Entities.ItemsLogRawDatas.Add(rawData);
                        Entities.SaveChanges();

                        lastItemLogRaw = rawData;
                    }

                    if (SaveInItemsLogWhen == WhenToLog.OnTimerElapsed)
                    {
                        TimeSpan timeSpan = DateTime.Now - lastItemLogRaw.Time;

                        if (timeSpan.TotalSeconds >= SaveInItemsLogTimeInterval)
                        {
                            ItemsLogRawData rawData = new ItemsLogRawData();
                            rawData.ItemId = ItemId;
                            rawData.Value  = value;
                            rawData.Time   = DateTime.Now;

                            if (outlierId > 0)
                            {
                                rawData.OutlierId = outlierId;
                            }

                            Entities.ItemsLogRawDatas.Add(rawData);
                            Entities.SaveChanges();
                        }
                    }
                    else if (SaveInItemsLogWhen == WhenToLog.OnChange)
                    {
                        if (lastItemLogRaw.Value != value)
                        {
                            ItemsLogRawData rawData = new ItemsLogRawData();
                            rawData.ItemId = ItemId;
                            rawData.Value  = value;
                            rawData.Time   = DateTime.Now;

                            if (outlierId > 0)
                            {
                                rawData.OutlierId = outlierId;
                            }

                            Entities.ItemsLogRawDatas.Add(rawData);
                            Entities.SaveChanges();
                        }
                        else
                        {
                            if (DateTime.Now - lastItemLogRaw.Time > new TimeSpan(0, 0, 1, 0))
                            {
                                ItemsLogRawData rawData = new ItemsLogRawData();
                                rawData.ItemId = ItemId;
                                rawData.Value  = value;
                                rawData.Time   = DateTime.Now;

                                if (outlierId > 0)
                                {
                                    rawData.OutlierId = outlierId;
                                }

                                Entities.ItemsLogRawDatas.Add(rawData);
                                Entities.SaveChanges();
                            }
                        }
                    }
                    //

                    if (!isOutlier)
                    {
                        var lastItemLog = Entities.ItemsLogs.OrderByDescending(x => x.ItemLogId).FirstOrDefault(x => x.ItemId == ItemId);

                        if (lastItemLog == null)
                        {
                            ItemsLog itemsLog = new ItemsLog();
                            itemsLog.ItemId = this.ItemId;
                            itemsLog.Time   = DateTime.Now;
                            itemsLog.Value  = value;
                            Entities.ItemsLogs.Add(itemsLog);

                            Entities.SaveChanges();

                            lastItemLog = itemsLog;
                        }

                        if (SaveInItemsLogWhen == WhenToLog.OnTimerElapsed)
                        {
                            TimeSpan timeSpan = DateTime.Now - lastItemLog.Time;

                            if (timeSpan.TotalSeconds >= SaveInItemsLogTimeInterval)
                            {
                                ItemsLog itemsLog = new ItemsLog();
                                itemsLog.ItemId = this.ItemId;
                                itemsLog.Time   = DateTime.Now;
                                itemsLog.Value  = value;
                                Entities.ItemsLogs.Add(itemsLog);

                                Entities.SaveChanges();
                            }
                        }
                        else if (SaveInItemsLogWhen == WhenToLog.OnChange)
                        {
                            if (lastItemLog.Value != value)
                            {
                                ItemsLog itemsLog = new ItemsLog();
                                itemsLog.ItemId = this.ItemId;
                                itemsLog.Time   = DateTime.Now;
                                itemsLog.Value  = value;
                                Entities.ItemsLogs.Add(itemsLog);

                                Entities.SaveChanges();
                            }
                            else
                            {
                                if (DateTime.Now - lastItemLog.Time > new TimeSpan(0, 0, 1, 0))
                                {
                                    ItemsLog itemsLog = new ItemsLog();
                                    itemsLog.ItemId = this.ItemId;
                                    itemsLog.Time   = DateTime.Now;
                                    itemsLog.Value  = value;
                                    Entities.ItemsLogs.Add(itemsLog);

                                    Entities.SaveChanges();
                                }
                            }
                        }


                        var lastItemLogLatest = Entities.ItemsLogLatests.FirstOrDefault(x => x.ItemId == ItemId);

                        if (lastItemLogLatest == null)
                        {
                            ItemsLogLatest itemsLogLatest = null;
                            if (Entities.ItemsLogLatests.Any(x => x.ItemId == this.ItemId))
                            {
                                itemsLogLatest       = Entities.ItemsLogLatests.FirstOrDefault(x => x.ItemId == this.ItemId);
                                itemsLogLatest.Time  = DateTime.Now;
                                itemsLogLatest.Value = value;
                            }
                            else
                            {
                                itemsLogLatest        = new ItemsLogLatest();
                                itemsLogLatest.ItemId = this.ItemId;
                                itemsLogLatest.Time   = DateTime.Now;
                                itemsLogLatest.Value  = value;
                                Entities.ItemsLogLatests.Add(itemsLogLatest);
                            }

                            Entities.SaveChanges();

                            lastItemLogLatest = itemsLogLatest;
                        }

                        if (SaveInItemsLogLastWhen == WhenToLog.OnTimerElapsed)
                        {
                            TimeSpan timeSpan = DateTime.Now - lastItemLogLatest.Time;

                            if (timeSpan.TotalSeconds >= SaveInItemsLogLastesTimeInterval)
                            {
                                ItemsLogLatest itemsLogLatest = null;
                                if (Entities.ItemsLogLatests.Any(x => x.ItemId == this.ItemId))
                                {
                                    itemsLogLatest       = Entities.ItemsLogLatests.FirstOrDefault(x => x.ItemId == this.ItemId);
                                    itemsLogLatest.Time  = DateTime.Now;
                                    itemsLogLatest.Value = value;
                                }
                                else
                                {
                                    itemsLogLatest        = new ItemsLogLatest();
                                    itemsLogLatest.ItemId = this.ItemId;
                                    itemsLogLatest.Time   = DateTime.Now;
                                    itemsLogLatest.Value  = value;
                                    Entities.ItemsLogLatests.Add(itemsLogLatest);
                                }

                                Entities.SaveChanges();
                            }
                        }
                        else if (SaveInItemsLogLastWhen == WhenToLog.OnChange)
                        {
                            if (lastItemLogLatest.Value != value)
                            {
                                ItemsLogLatest itemsLogLatest = null;
                                if (Entities.ItemsLogLatests.Any(x => x.ItemId == this.ItemId))
                                {
                                    itemsLogLatest       = Entities.ItemsLogLatests.FirstOrDefault(x => x.ItemId == this.ItemId);
                                    itemsLogLatest.Time  = DateTime.Now;
                                    itemsLogLatest.Value = value;
                                }
                                else
                                {
                                    itemsLogLatest        = new ItemsLogLatest();
                                    itemsLogLatest.ItemId = this.ItemId;
                                    itemsLogLatest.Time   = DateTime.Now;
                                    itemsLogLatest.Value  = value;
                                    Entities.ItemsLogLatests.Add(itemsLogLatest);
                                }

                                Entities.SaveChanges();
                            }
                            else
                            {
                                if (DateTime.Now - lastItemLogLatest.Time > new TimeSpan(0, 0, 1, 0))
                                {
                                    ItemsLogLatest itemsLogLatest = null;
                                    if (Entities.ItemsLogLatests.Any(x => x.ItemId == this.ItemId))
                                    {
                                        itemsLogLatest       = Entities.ItemsLogLatests.FirstOrDefault(x => x.ItemId == this.ItemId);
                                        itemsLogLatest.Time  = DateTime.Now;
                                        itemsLogLatest.Value = value;
                                    }
                                    else
                                    {
                                        itemsLogLatest        = new ItemsLogLatest();
                                        itemsLogLatest.ItemId = this.ItemId;
                                        itemsLogLatest.Time   = DateTime.Now;
                                        itemsLogLatest.Value  = value;
                                        Entities.ItemsLogLatests.Add(itemsLogLatest);
                                    }

                                    Entities.SaveChanges();
                                }
                            }
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                Logger.LogMonitoringServiceLibrary(ex);
            }
        }
示例#29
0
        private void CheckNotifications()
        {
            IsThreadRunning = true;

            while (!StopThread)
            {
                try
                {
                    IndustrialMonitoringEntities entities          = new IndustrialMonitoringEntities();
                    List <NotificationItem>      notificationItems = entities.NotificationItems.ToList();

                    foreach (var notificationItem in notificationItems)
                    {
                        entities = new IndustrialMonitoringEntities();
                        int notificationId = notificationItem.NotificationId;

                        if (notificationItem.DisableNotification)
                        {
                            NotificationItemsLog prev =
                                entities.NotificationItemsLogs.FirstOrDefault(x => x.NotificationId == notificationId);

                            if (!prev.Value)
                            {
                                NotificationItemsLog notificationItemsLog = new NotificationItemsLog();
                                notificationItemsLog.NotificationId = notificationId;
                                notificationItemsLog.Value          = true;
                                notificationItemsLog.Time           = DateTime.Now;

                                entities.NotificationItemsLogs.Add(notificationItemsLog);
                            }

                            NotificationItemsLogLatest latest =
                                entities.NotificationItemsLogLatests.FirstOrDefault(
                                    x => x.NotificationId == notificationId);

                            if (!latest.Value)
                            {
                                latest.Value = true;
                                latest.Time  = DateTime.Now;

                                entities.SaveChanges();
                            }


                            continue;
                        }

                        NotificationItemsLogLatest notificationItemsLogLatest = entities.NotificationItemsLogLatests.FirstOrDefault(x => x.NotificationId == notificationId);

                        if (notificationItemsLogLatest == null)
                        {
                            notificationItemsLogLatest = new NotificationItemsLogLatest();
                            notificationItemsLogLatest.NotificationId = notificationId;
                            notificationItemsLogLatest.Value          = false;
                            notificationItemsLogLatest.Time           = DateTime.Now;

                            entities.NotificationItemsLogLatests.Add(notificationItemsLogLatest);
                            entities.SaveChanges();
                        }
                        else
                        {
                            if (!notificationItem.DisableNotification)
                            {
                                ItemsLogLatest itemLogLatest =
                                    entities.ItemsLogLatests.FirstOrDefault(x => x.ItemId == notificationItem.ItemId);

                                double currentValue = double.Parse(itemLogLatest.Value);

                                bool withoutNotification = false;

                                if (notificationItem.NotificationType == (int)NotificationType.Lower)
                                {
                                    if (currentValue < notificationItem.High)
                                    {
                                        withoutNotification = true;
                                    }
                                }
                                else if (notificationItem.NotificationType == (int)NotificationType.Between)
                                {
                                    if (currentValue > notificationItem.Low & currentValue < notificationItem.High)
                                    {
                                        withoutNotification = true;
                                    }
                                }
                                else if (notificationItem.NotificationType == (int)NotificationType.Higher)
                                {
                                    if (currentValue > notificationItem.Low)
                                    {
                                        withoutNotification = true;
                                    }
                                }

                                if (withoutNotification)
                                {
                                    if (notificationItemsLogLatest.Value == false)
                                    {
                                        NotificationItemsLog notificationItemsLog = new NotificationItemsLog();
                                        notificationItemsLog.NotificationId = notificationId;
                                        notificationItemsLog.Value          = true;
                                        notificationItemsLog.Time           = DateTime.Now;

                                        entities.NotificationItemsLogs.Add(notificationItemsLog);
                                        entities.SaveChanges();

                                        //var bot = NotificationsBotInvoker.Instance;
                                        //bot.SendNotification(notificationItemsLog.NotificationLogId);

                                        NotificationsBotInvoker.RegisterNewRecord(notificationId, notificationItemsLog.NotificationLogId);
                                    }
                                }
                                else
                                {
                                    // we have notification

                                    if (notificationItemsLogLatest.Value)
                                    {
                                        // we have a change in notification state

                                        NotificationItemsLog notificationItemsLog = new NotificationItemsLog();
                                        notificationItemsLog.NotificationId = notificationId;
                                        notificationItemsLog.Value          = false;
                                        notificationItemsLog.Time           = DateTime.Now;

                                        entities.NotificationItemsLogs.Add(notificationItemsLog);
                                        entities.SaveChanges();

                                        //var bot = NotificationsBotInvoker.Instance;
                                        //bot.SendNotification(notificationItemsLog.NotificationLogId);

                                        NotificationsBotInvoker.RegisterNewRecord(notificationId, notificationItemsLog.NotificationLogId);
                                    }
                                }


                                notificationItemsLogLatest.Value = withoutNotification;
                                notificationItemsLogLatest.Time  = DateTime.Now;
                                entities.SaveChanges();
                            }
                            else
                            {
                                if (notificationItemsLogLatest.Value == false)
                                {
                                    NotificationItemsLog notificationItemsLog = new NotificationItemsLog();
                                    notificationItemsLog.NotificationId = notificationId;
                                    notificationItemsLog.Value          = true;
                                    notificationItemsLog.Time           = DateTime.Now;

                                    entities.NotificationItemsLogs.Add(notificationItemsLog);
                                    entities.SaveChanges();

                                    NotificationsBotInvoker.RegisterNewRecord(notificationId, notificationItemsLog.NotificationLogId);
                                }
                            }
                        }

                        Thread.Sleep(10);
                    }

                    Thread.Sleep(1000);
                }
                catch (Exception ex)
                {
                    Logger.LogMonitoringServiceLibrary(ex);
                }
            }

            IsThreadRunning = false;
        }
        public async void CheckNotificationBot()
        {
            while (true)
            {
                IndustrialMonitoringEntities entities         = null;
                List <NotificationBot>       notificationBots = new List <NotificationBot>();

                try
                {
                    entities = new IndustrialMonitoringEntities();

                    notificationBots = entities.NotificationBots.Where(x => x.IsCompleted == false).OrderBy(x => x.NotificationBotId).ToList();
                }
                catch (Exception ex)
                {
                    Logger.LogMonitoringServiceLibrary(ex);
                }

                foreach (NotificationBot n in notificationBots)
                {
                    try
                    {
                        if (n.Delay == 0)
                        {
                            await this.SendNotification(n.NotificationLogId, NotificationDelayType.Normal);

                            n.IsSent      = true;
                            n.IsCompleted = true;
                            n.SentTime    = DateTime.Now;

                            entities.SaveChanges();
                        }

                        bool timerElapsed = DateTime.Now - n.RegisterTime > TimeSpan.FromSeconds(n.Delay);

                        if (n.Delay > 0)
                        {
                            if (!n.NotificationItemsLog.Value)
                            {
                                // with alarm
                                // if still has alarm

                                if (timerElapsed)
                                {
                                    ItemsLogLatest itemLogLatest =
                                        entities.ItemsLogLatests.FirstOrDefault(x => x.ItemId == n.NotificationItem.ItemId);

                                    double currentValue = double.Parse(itemLogLatest.Value);

                                    bool withoutNotification = false;

                                    if (n.NotificationItem.NotificationType == (int)NotificationType.Lower)
                                    {
                                        if (currentValue < n.NotificationItem.High)
                                        {
                                            withoutNotification = true;
                                        }
                                    }
                                    else if (n.NotificationItem.NotificationType == (int)NotificationType.Between)
                                    {
                                        if (currentValue > n.NotificationItem.Low & currentValue < n.NotificationItem.High)
                                        {
                                            withoutNotification = true;
                                        }
                                    }
                                    else if (n.NotificationItem.NotificationType == (int)NotificationType.Higher)
                                    {
                                        if (currentValue > n.NotificationItem.Low)
                                        {
                                            withoutNotification = true;
                                        }
                                    }

                                    if (!withoutNotification)
                                    {
                                        await this.SendNotification(n.NotificationLogId, NotificationDelayType.Delayed);

                                        n.IsSent      = true;
                                        n.IsCompleted = true;
                                        n.SentTime    = DateTime.Now;

                                        entities.SaveChanges();
                                    }
                                    else
                                    {
                                        n.IsSent      = false;
                                        n.IsCompleted = true;

                                        entities.SaveChanges();
                                    }
                                }
                            }
                            else
                            {
                                // without alarm

                                if (timerElapsed)
                                {
                                    IndustrialMonitoringEntities entities2 = new IndustrialMonitoringEntities();
                                    var lastNotificationBot =
                                        entities2.NotificationBots.Where(x => x.NotificationId == n.NotificationId & x.WithoutAlarm == false &
                                                                         x.Delay > 0 & x.IsCompleted == true).
                                        OrderByDescending(x => x.NotificationBotId).FirstOrDefault();

                                    if (lastNotificationBot == null)
                                    {
                                        continue;
                                    }

                                    if (lastNotificationBot.IsSent)
                                    {
                                        await this.SendNotification(n.NotificationLogId, NotificationDelayType.Delayed);

                                        n.IsSent      = true;
                                        n.IsCompleted = true;
                                        n.SentTime    = DateTime.Now;

                                        entities.SaveChanges();
                                    }
                                    else
                                    {
                                        n.IsSent      = false;
                                        n.IsCompleted = true;

                                        entities.SaveChanges();
                                    }
                                }
                            }
                        }
                    }
                    catch (Exception ex)
                    {
                        Logger.LogMonitoringServiceLibrary(ex);
                    }
                }

                await Task.Delay(1000);
            }
        }