예제 #1
0
        public Plant AddPlant(Users user, string plantName = null, string plantAddress = null)
        {
            Plant result = null;

            if (string.IsNullOrWhiteSpace(plantName))
            {
                plantName = "Default_" + user.Username;
            }

            try
            {
                var plant = new Plant();
                plant.Name    = plantName;
                plant.Address = plantAddress;
                plant.UserId  = user?.ID;
                _context.Set <Plant>().Add(plant);
                _context.SaveChanges();

                result = plant;
            }
            catch (Exception ex)
            {
                var errMessage = string.Format(ex.GetStringLog(), plantName, plantAddress);
                LogService.WriteLog(errMessage, LogService.TypeLevel.Error, ex);
            }
            return(result);
        }
예제 #2
0
        /**
         * Autentica l'utente partendo solamente FomMonitoringCore.SqlServerla UserID
         */
        public bool LoginUserWithoutPassword(Guid userId, out string message, out FomMonitoringCore.SqlServer.Users user)
        {
            try
            {
                user = _fomMonitoringEntities.Set <FomMonitoringCore.SqlServer.Users>().FirstOrDefault(i => i.ID == userId);

                if (null == user)
                {
                    message = "User not found"; new Exception(message); return(false);
                }
                if (user.Enabled == false)
                {
                    message = "User is not allowed to have accessed to this application"; new Exception(message); return(false);
                }

                //Cancella il record della richiesta
                _fomMonitoringEntities.SaveChanges();

                message = "Login done successfully";
                return(true);
            }
            catch (Exception ex)
            {
                throw new Exception($"Error: {ex.Message} Error (#111010)");
            }
        }
예제 #3
0
        public void SetOverrideTimeZoneMachine(int idMachine, Guid idUser, string timezone)
        {
            var mapping = _fomMonitoringEntities.Set <UserMachineMapping>()
                          .FirstOrDefault(m => m.MachineId == idMachine && m.UserId == idUser);

            if (mapping != null)
            {
                mapping.TimeZone = timezone;
            }

            _fomMonitoringEntities.SaveChanges();
        }
예제 #4
0
        public void HistoricizingStates(IFomMonitoringEntities context, int idMachine)
        {
            var maxHpDate = context.Set <HistoryState>().Where(historyState => historyState.MachineId == idMachine)
                            .Max(a => a.Day);

            maxHpDate = maxHpDate?.Date ?? DateTime.MinValue;

            var historyStates = context.Set <StateMachine>()
                                .Where(p => p.Day >= maxHpDate && p.MachineId == idMachine).ToList()
                                .GroupBy(g => new { g.Day.Value.Date, g.Operator, g.StateId })
                                .Select(n => new HistoryState
            {
                Id          = 0,
                Day         = n.Key.Date,
                MachineId   = idMachine,
                Operator    = n.Key.Operator,
                Period      = n.Key.Date.Year * 10000 + n.Key.Date.Month * 100 + n.Key.Date.Day,
                TypeHistory = "d",
                ElapsedTime = n.Sum(i => i.ElapsedTime),
                StateId     = n.Key.StateId,
                OverfeedAvg = n.Key.StateId == 1 ? (n.Sum(i => i.ElapsedTime) > 0 ? n.Sum(i => i.Overfeed * i.ElapsedTime) / n.Sum(i => i.ElapsedTime) : 0) : null,
            }).ToList();

            var aggregato = historyStates.GroupBy(c => new { c.Day, c.StateId }).Select(n => new HistoryState
            {
                Id          = 0,
                Day         = n.Key.Day.Value,
                MachineId   = idMachine,
                Operator    = null,
                Period      = n.Key.Day.Value.Year * 10000 + n.Key.Day.Value.Month * 100 + n.Key.Day.Value.Day,
                ElapsedTime = n.Sum(i => i.ElapsedTime),
                TypeHistory = "d",
                StateId     = n.Key.StateId,
                OverfeedAvg = n.Key.StateId == 1 ? n.Sum(i => i.ElapsedTime) > 0 ? n.Sum(i => i.OverfeedAvg * i.ElapsedTime) / n.Sum(i => i.ElapsedTime) : 0 : null
            }).ToList();

            historyStates.AddRange(aggregato);


            foreach (var cur in historyStates)
            {
                var row = context.Set <HistoryState>().FirstOrDefault(historyState => historyState.MachineId == idMachine &&
                                                                      historyState.Day == cur.Day && historyState.StateId == cur.StateId &&
                                                                      (historyState.Operator == cur.Operator ||
                                                                       historyState.Operator == null && cur.Operator == null));
                if (row != null)
                {
                    row.ElapsedTime = cur.ElapsedTime;
                    row.OverfeedAvg = cur.OverfeedAvg;
                }
                else
                {
                    context.Set <HistoryState>().Add(cur);
                }
            }

            context.SaveChanges();
        }
예제 #5
0
        public bool IgnoreMessage(int messageId)
        {
            try
            {
                var cur = _context.Set <MessageMachine>().Find(messageId);
                cur.IgnoreDate = DateTime.UtcNow;
                cur.UserId     = _accountService.GetLoggedUser().ID.ToString();
                _context.SaveChanges();
                return(true);
            }
            catch (Exception ex)
            {
                var errMessage = string.Format(ex.GetStringLog(),
                                               messageId.ToString(), "");
                LogService.WriteLog(errMessage, LogService.TypeLevel.Error, ex);
            }

            return(false);
        }
예제 #6
0
        private void ClearNotificationTable()
        {
            var user     = _accountService.GetLoggedUser();
            var toRemove = _dbContext.Set <MessageMachineNotification>().Where(m => m.UserId == user.ID.ToString());

            if (toRemove.Any())
            {
                _dbContext.Set <MessageMachineNotification>().RemoveRange(toRemove);
                _dbContext.SaveChanges();
            }
        }
예제 #7
0
        public bool DeletePlant(int id)
        {
            try
            {
                var plant = _context.Set <Plant>().Find(id);
                if (plant != null)
                {
                    _context.Set <Plant>().Remove(plant);
                }

                _context.SaveChanges();
                return(true);
            }
            catch (Exception ex)
            {
                string errMessage = ex.GetStringLog();
                LogService.WriteLog(errMessage, LogService.TypeLevel.Error, ex);
                throw ex;
            }
        }
예제 #8
0
        public void RemoveUsers(List <UserModel> users)
        {
            if (users == null || users.Count == 0)
            {
                return;
            }
            try
            {
                var ids = users.Select(a => a.ID).ToList();
                var rem = _fomMonitoringEntities.Set <Users>().Where(y => ids.Contains(y.ID)).ToList();

                _fomMonitoringEntities.Set <Users>().RemoveRange(rem);

                _fomMonitoringEntities.SaveChanges();
            }
            catch (Exception ex)
            {
                var errMessage = string.Format(ex.GetStringLog());
                LogService.WriteLog(errMessage, LogService.TypeLevel.Error, ex);
            }
        }
예제 #9
0
        public void CleanHistoryJobs()
        {
            //elimino solo quelli degli ultimi 10 giorni che non hanno piece
            //perchè altrimenti andrebbe sempre su tutta la tabella e sarebbe sempre più lenta
            //quando si avvia il task si fa una prima pulizia generale.
            var start    = DateTime.UtcNow.AddDays(int.Parse(System.Configuration.ConfigurationManager.AppSettings.Get("CleanInterval")));
            var toDelete = _context.Set <HistoryJob>()
                           .Where(j => DbFunctions.TruncateTime(j.Day) >= start.Date && !j.Piece.Any()).ToList();

            if (!toDelete.Any())
            {
                return;
            }

            _context.Set <HistoryJob>().RemoveRange(toDelete);
            _context.SaveChanges();
        }
예제 #10
0
        public void InsertAuditLogin(bool accessed, string username, Guid?userId, string message)
        {
            ExtensionMethods.CheckGuidIsValidAndNotEmpty(userId.ToString(), out userId);

            var al = new FomMonitoringCore.SqlServer.AuditLogin
            {
                ID          = Guid.NewGuid(),
                Accessed    = accessed,
                Username    = username,
                UserID      = userId,
                MessageInfo = message,
                DateAndTime = DateTime.Now,
                IP          = ExtensionMethods.GetUserConnectionIP()
            };

            _fomMonitoringEntities.Set <FomMonitoringCore.SqlServer.AuditLogin>().Add(al);
            _fomMonitoringEntities.SaveChanges();
        }
예제 #11
0
        public void HistoricizingMessages(IFomMonitoringEntities context, int idMachine)
        {
            var maxHpDate = context.Set <HistoryMessage>().Where(hp => hp.MachineId == idMachine)
                            .OrderByDescending(a => a.Day).FirstOrDefault()?.Day;

            maxHpDate = maxHpDate?.Date ?? DateTime.MinValue;

            var historyMessages = context.Set <MessageMachine>()
                                  .Where(p => p.Day >= maxHpDate && p.MachineId == idMachine && p.MessagesIndex.IsVisibleLOLA &&
                                         (p.MessagesIndex.MessageTypeId == 11 ||
                                          p.MessagesIndex.MessageTypeId == 12 ||
                                          p.MessagesIndex.MessageType.Id == 13)).ToList()
                                  .GroupBy(g => new{ g.Day.Value.Date, g.Params, g.MessagesIndexId })
                                  .Select(n => new HistoryMessage
            {
                Day             = n.Key.Date,
                Params          = n.Key.Params,
                MessagesIndexId = n.Key.MessagesIndexId,
                MachineId       = idMachine,
                Period          = n.Key.Date.Year * 10000 + n.Key.Date.Month * 100 + n.Key.Date.Day,
                Count           = n.Count(),
                TypeHistory     = "d"
            }).ToList();

            foreach (var cur in historyMessages)
            {
                var row = context.Set <HistoryMessage>().FirstOrDefault(hp => hp.MachineId == idMachine &&
                                                                        hp.Day == cur.Day &&
                                                                        hp.TypeHistory == cur.TypeHistory &&
                                                                        hp.MessagesIndexId == cur.MessagesIndexId &&
                                                                        hp.Params == cur.Params);
                if (row != null)
                {
                    row.Count = cur.Count;
                }
                else
                {
                    context.Set <HistoryMessage>().Add(cur);
                }
            }

            context.SaveChanges();
        }
예제 #12
0
        public bool ElaborateJsonData(string json)
        {
            var result = false;

            try
            {
                var jObject = JsonConvert.DeserializeObject <JObject>(json);
                var token   = jObject.Root.First;
                if (token.Path.ToLower() == "currentstate")
                {
                    var    currentStateDynamic = JsonConvert.DeserializeObject <List <dynamic> >(JsonConvert.SerializeObject(token.First)).First();
                    string machineSerial       = currentStateDynamic.MachineSerial;
                    var    machine             = _context.Set <Machine>().FirstOrDefault(f => f.Serial == machineSerial);
                    if (machine != null)
                    {
                        var currentState       = _context.Set <CurrentState>().FirstOrDefault(f => f.MachineId == machine.Id);
                        var currentStateExists = true;
                        if (currentState == null)
                        {
                            currentState       = new CurrentState();
                            currentStateExists = false;
                        }
                        currentState.JobCode               = currentStateDynamic.JobCode;
                        currentState.JobProducedPieces     = (int?)currentStateDynamic.JobProducedPieces;
                        currentState.JobTotalPieces        = (int?)currentStateDynamic.JobTotalPieces;
                        currentState.LastUpdated           = (currentStateDynamic.LastUpdated.Value is string || currentStateDynamic.LastUpdated.Value == null || ((DateTime)currentStateDynamic.LastUpdated).Year < 1900 ? (DateTime?)null : (DateTime)currentStateDynamic.LastUpdated);
                        currentState.MachineId             = machine.Id;
                        currentState.Operator              = currentStateDynamic.Operator;
                        currentState.StateId               = (int?)currentStateDynamic.State;
                        currentState.StateTransitionCode   = currentStateDynamic.StateTransitionCode;
                        currentState.ResidueWorkingTime    = currentStateDynamic.ResidueWorkingTime;
                        currentState.ResidueWorkingTimeJob = currentStateDynamic.ResidueWorkingTimeJob;
                        currentState.ResidueWorkingTimeBar = currentStateDynamic.ResidueWorkingTimeBar;
                        if (!currentStateExists)
                        {
                            _context.Set <CurrentState>().Add(currentState);
                        }

                        machine.LastUpdate = currentState.LastUpdated;
                        _context.SaveChanges();
                        result = true;

                        /*var historyJobExist = _context.Set<HistoryJob>().Any(h =>
                         *  h.Code == currentState.JobCode && h.MachineId == machine.Id && h.Day != null &&
                         *  DbFunctions.TruncateTime(h.Day.Value) == DbFunctions.TruncateTime(currentState.LastUpdated));
                         * if (!historyJobExist && currentState.JobCode?.Trim().Length > 0 && currentState.JobProducedPieces > 0)
                         * {
                         *  var newJob = new HistoryJob
                         *  {
                         *      Day = DateTime.UtcNow.Date,
                         *      Code = currentState.JobCode,
                         *      ElapsedTime = 0,
                         *      MachineId = machine.Id,
                         *      Period = (DateTime.UtcNow.Year * 10000) + (DateTime.UtcNow.Month * 100) + (DateTime.UtcNow.Day),
                         *      PiecesProduced = currentState.JobProducedPieces,
                         *      TotalPieces = currentState.JobTotalPieces,
                         *      TypeHistory = "d"
                         *  };
                         *  _context.Set<HistoryJob>().Add(newJob);
                         *  _context.SaveChanges();
                         * }*/
                    }
                }
            }
            catch (Exception ex)
            {
                var errMessage = string.Format(ex.GetStringLog(), json);
                LogService.WriteLog(errMessage, LogService.TypeLevel.Error, ex);
            }
            return(result);
        }
예제 #13
0
        public bool UpdateActiveCustomersAndMachines()
        {
            var result = true;

            try
            {
                var apiUrl      = ApplicationSettingService.GetWebConfigKey("UpdateCustomersAndMachinesSOAPUrl");
                var apiUsername = ApplicationSettingService.GetWebConfigKey("UpdateCustomersAndMachinesSOAPUsername");
                var apiPassword = ApplicationSettingService.GetWebConfigKey("UpdateCustomersAndMachinesSOAPPassword");

                var webRequest = (HttpWebRequest)WebRequest.Create(apiUrl);
                webRequest.Headers.Add("SOAPAction", "http://tempuri.org/IService/ottieniListaMacchineRegistrate");
                webRequest.ContentType     = "text/xml;charset=\"utf-8\"";
                webRequest.Accept          = "text/xml";
                webRequest.Method          = "POST";
                webRequest.CookieContainer = new CookieContainer();
                webRequest.Credentials     = new NetworkCredential(apiUsername, apiPassword, "");

                var soapEnvelopeXml = new XmlDocument();
                soapEnvelopeXml.LoadXml(@"<soapenv:Envelope xmlns:soapenv=""http://schemas.xmlsoap.org/soap/envelope/"" xmlns:tem=""http://tempuri.org/""><soapenv:Header></soapenv:Header><soapenv:Body><tem:ottieniListaMacchineRegistrate/></soapenv:Body></soapenv:Envelope>");

                using (var stream = webRequest.GetRequestStream())
                {
                    soapEnvelopeXml.Save(stream);
                }

                var asyncResult = webRequest.BeginGetResponse(null, null);
                asyncResult.AsyncWaitHandle.WaitOne();

                string soapResult;
                using (var webResponse = webRequest.EndGetResponse(asyncResult))
                {
                    using (var rd = new StreamReader(webResponse.GetResponseStream()))
                    {
                        soapResult = rd.ReadToEnd();
                    }
                }

                var document = new XmlDocument();
                document.LoadXml(soapResult);

                var customers = JsonConvert.DeserializeObject <JsonCustomersModel>(document.InnerText, new IsoDateTimeConverter {
                    DateTimeFormat = "dd/MM/yyyy"
                });


                //elimino i customer non più presenti nella vip area

                var dbCustomers     = _userManagerService.GetAllCustomers();
                var customerNames   = customers.customers.Select(j => j.username).Distinct();
                var custmerToRemove = dbCustomers.Where(e => !customerNames.Contains(e.Username)).ToList();

                if (custmerToRemove.Any())
                {
                    //rimuovo prima le associazioni
                    var ids   = custmerToRemove.Select(a => a.ID).ToList();
                    var names = custmerToRemove.Select(a => a.Username).ToList();
                    var us    = _context.Set <UserCustomerMapping>().Where(uc => names.Contains(uc.CustomerName)).ToList();

                    //utenti associati al customer
                    var usCust = new List <UserModel>();

                    if (us.Any())
                    {
                        foreach (var item in us)
                        {
                            usCust.AddRange(_userManagerService.GetUsers(item.CustomerName));
                        }
                        _context.Set <UserCustomerMapping>().RemoveRange(us);
                        _context.SaveChanges();
                    }

                    var um = _context.Set <UserMachineMapping>().Where(mh => ids.Contains(mh.UserId)).ToList();
                    if (um.Any())
                    {
                        _context.Set <UserMachineMapping>().RemoveRange(um);
                        _context.SaveChanges();
                    }

                    usCust.AddRange(custmerToRemove);
                    using (var transactionSuppress = new TransactionScope(TransactionScopeOption.Suppress))
                    {
                        _userManagerService.RemoveUsers(usCust);
                        transactionSuppress.Complete();
                    }
                }


                //pulizia della tabella UserCustomerMapping, potrebbero esserci record inseriti a mano con customerName non esistenti

                var machines = _context.Set <Machine>().ToList();
                var users    = _context.Set <Users>().ToList();
                foreach (var customer in customers.customers)
                {
                    try
                    {
                        //Aggiungo eventuali nuovi clienti
                        var user = new UserModel();
                        using (var transactionSuppress = new TransactionScope(TransactionScopeOption.Suppress))
                        {
                            user = users.FirstOrDefault(u => u.Username == customer.username)?.Adapt <Users, UserModel>();
                            if (user == null)
                            {
                                user = new UserModel
                                {
                                    Username     = customer.username,
                                    FirstName    = customer.firstName,
                                    LastName     = customer.lastName,
                                    CompanyName  = customer.companyName,
                                    Enabled      = true,
                                    Role         = enRole.Customer,
                                    CustomerName = customer.username
                                };
                                user.ID = _userManagerService.CreateUser(user);
                            }
                            else
                            {
                                user.FirstName   = customer.firstName;
                                user.LastName    = customer.lastName;
                                user.CompanyName = customer.companyName;
                                _userManagerService.UpdateUserName(user);
                            }
                            transactionSuppress.Complete();
                        }

                        //Aggiungo eventuali nuovi clienti nel DB dei dati
                        var userCustomer = _context.Set <UserCustomerMapping>().FirstOrDefault(f => f.UserId == user.ID);
                        if (userCustomer == null)
                        {
                            userCustomer = new UserCustomerMapping
                            {
                                UserId       = user.ID,
                                CustomerName = user.Username
                            };
                            _context.Set <UserCustomerMapping>().Add(userCustomer);
                            _context.SaveChanges();
                        }

                        //Prendo la lista delle macchine esistenti nel DB a partire da quelle arrivate da JSON
                        var machinesSerial    = customer.machines.Select(s => s.serial).ToList();
                        var customersMachines = machines.Where(w => machinesSerial.Contains(w.Serial)).ToList();

                        //Rimuovo le associazioni cliente <=> macchina per macchine non più monitorate
                        var machinesId            = customersMachines.Select(s => s.Id).ToList();
                        var clientUsersMachines   = _context.Set <UserMachineMapping>().Where(w => machinesId.Contains(w.MachineId)).Select(s => s.UserId).Distinct().ToList();
                        var usersMachinesToRemove = _context.Set <UserMachineMapping>().Where(w => !machinesId.Contains(w.MachineId) && clientUsersMachines.Contains(w.UserId)).ToList();
                        _context.Set <UserMachineMapping>().RemoveRange(usersMachinesToRemove);
                        _context.SaveChanges();
                        var plant = _mesService.GetOrSetPlantDefaultByUser(user.ID);

                        //Inserisco i nuovi mapping cliente <=> macchina
                        foreach (var machine in customersMachines)
                        {
                            var jm = customer.machines.FirstOrDefault(f => f.serial == machine.Serial);
                            if (jm != null)
                            {
                                var expirationDate     = jm.expirationDate;
                                var activationDate     = jm.activationDate;
                                var machineName        = jm.machineName;
                                var usersMachineMapped = _context.Set <UserMachineMapping>().Where(w => w.MachineId == machine.Id).ToList();
                                if (!usersMachineMapped.Any())
                                {
                                    var userMachine = new UserMachineMapping()
                                    {
                                        MachineId = machine.Id,
                                        UserId    = user.ID
                                    };
                                    _context.Set <UserMachineMapping>().Add(userMachine);
                                    _context.SaveChanges();
                                }
                                //aggiorno l'activationDate della macchina prendendo la più vecchia
                                // aggiorno anche il plantId
                                var ma = _context.Set <Machine>().Find(machine.Id);
                                if (ma.PlantId == null)
                                {
                                    ma.PlantId = plant;
                                }
                                if (ma.ActivationDate == null || ma.ActivationDate > activationDate)
                                {
                                    ma.ActivationDate = activationDate;
                                }
                                if (ma.ExpirationDate == null || ma.ExpirationDate < expirationDate)
                                {
                                    ma.ExpirationDate = expirationDate;
                                }
                                if (!string.IsNullOrWhiteSpace(machineName))
                                {
                                    ma.MachineName = machineName;
                                }
                                _context.SaveChanges();
                            }
                        }
                    }
                    catch (Exception ex)
                    {
                        LogService.WriteLog(ex.Message, LogService.TypeLevel.Error, ex);
                        result = false;
                    }
                }
            }
            catch (Exception ex)
            {
                LogService.WriteLog(ex.Message, LogService.TypeLevel.Error, ex);
            }

            return(result);
        }