Esempio n. 1
0
        private bool CompileFactoriesTable()
        {
            bool result = false;

            if (stopImport)
            {
                return(result);
            }

            StatusChanged("Importing Factories...");

            try
            {
                using (DBArchive db = new DBArchive())
                {
                    //Get enumerable rows fron datatable
                    IEnumerable <DataRow> collection = dtPlants.Rows.Cast <DataRow>();

                    foreach (DataRow r in collection)
                    {
                        if (stopImport)
                        {
                            break;
                        }

                        FactoryEVM f = new FactoryEVM();

                        try
                        {
                            f.Name        = r.Field <string>("dbf_Stabilimento");
                            f.CompanyName = r.Field <string>("dbf_RagioneSociale");
                            f.Address     = r.Field <string>("dbf_Indirizzo");
                            f.IsForfait   = r.Field <bool>("dbf_Forfettario");

                            long transferType = r.Field <byte>("dbf_Tipo_Trasf");
                            f.TransferType = transferType != 4 ? transferType : 0;

                            f.Save(db);

                            _factories.Add(r.Field <int>("dbf_Index"), f.Id);

                            Message($"Factory {f.Name} OK");
                        }
                        catch (Exception ex)
                        {
                            Error($"Failed to import factory {f.Name}. {ex}", ex);
                        }
                    }

                    result = true;
                }
            }
            catch (Exception ex)
            {
                result = false;
                Error($"Failed importing factories. {ex}", ex);
            }

            return(result);
        }
Esempio n. 2
0
        /// <summary>
        /// Initializes a new instance of the SettingsViewModel class.
        /// </summary>
        public OrderRecipientsViewModel(DBArchive db)
        {
            _db = db;

            AddCommand    = new RelayCommand <string>(AddRecipient);
            RemoveCommand = new RelayCommand <OrderEmailRecipient>(RemoveRecipient);

            Recipients = new ObservableCollection <OrderEmailRecipient>();
        }
Esempio n. 3
0
        /// <summary>
        /// Initializes a new instance of the NotificationsViewModel class.
        /// </summary>
        public NotificationsViewModel()
        {
            using (DBArchive db = new DBArchive())
            {
                NewFactoriesCount       = db.Factories.Count(factory => factory.NotifyAsNew);
                NewFDLCount             = db.FDLs.Count(fdl => fdl.NotifyAsNew);
                NewExpenseAccountsCount = db.ExpenseAccounts.Count(ea => ea.NotifyAsNew);
            }

            MessengerInstance.Register(this, (NewItemMessage <FDLEVM> x) => NewFDLCount++);
            MessengerInstance.Register(this, (NewItemMessage <FactoryEVM> x) => { if (x.Sender is FDLManager)
                                                                                  {
                                                                                      NewFactoriesCount++;
                                                                                  }
                                       });
            MessengerInstance.Register(this, (NewItemMessage <ExpenseAccountEVM> x) => NewExpenseAccountsCount++);
            MessengerInstance.Register <StatusChangeMessage <EProviderStatus> >(this, OnExchangeStatusChange);
        }
Esempio n. 4
0
        private void ApplyMigrations()
        {
            using (DBArchive db = new DBArchive())
            {
                using (var transaction = db.Database.BeginTransaction())
                {
                    try
                    {
                        var db_version = db.Database.SqlQuery <int>("PRAGMA user_version").First();

                        foreach (var f in Directory.GetFiles("UpgradeScripts/", "*.sql").OrderBy(f => Int32.Parse(Regex.Match(f, @"\d+").Value)))
                        {
                            if (!int.TryParse(Path.GetFileName(f).Split('_').First(), out int scriptVersion))
                            {
                                continue;
                            }

                            if (db_version >= scriptVersion)
                            {
                                continue;
                            }

                            db.Database.ExecuteSqlCommand(File.ReadAllText(f));
                            db.SaveChanges();
                        }
                        transaction.Commit();
                    }
                    catch (Exception ex)
                    {
                        transaction.Rollback();

                        MetroMessageBox.Show($"Error upgrading the database.\nException: {ex.Message}", "Fatal Error", MessageBoxButton.OK, MessageBoxImage.Error);

                        Environment.Exit(2);
                    }
                }
            }
        }
Esempio n. 5
0
        private bool CompileHourTable()
        {
            bool result = false;

            if (stopImport)
            {
                return(result);
            }

            StatusChanged("Importing Hours...");

            try
            {
                using (DBArchive db = new DBArchive())
                {
                    //Get enumerable rows fron datatable
                    IEnumerable <DataRow> collection = dtHours.Rows.Cast <DataRow>();

                    foreach (DataRow r in collection)
                    {
                        if (stopImport)
                        {
                            break;
                        }

                        DayEVM d = new DayEVM();

                        try
                        {
                            d.Timestamp = r.Field <DateTime>("Dbf_Data").ToUnixTimestamp();

                            d.Type = r.Field <byte>("dbf_Tipo_Giorno");

                            if (d.Type != 3 && d.Type != 6)
                            {
                                d.Type = 0;
                            }
                            else if (d.Type == 3)
                            {
                                d.Type = 1;
                            }
                            else if (d.Type == 6)
                            {
                                d.Type = 2;
                            }

                            d.Save(db);

                            //t = new Timesheet();
                            long timestamp = r.Field <DateTime>("Dbf_Data").ToUnixTimestamp();

                            //Add office hours
                            if (
                                r.Field <Int16>("Dbf_Uff_Inizio_AM") != 0 |
                                r.Field <Int16>("Dbf_Uff_Fine_AM") != 0 |
                                r.Field <Int16>("Dbf_Uff_Inizio_PM") != 0 |
                                r.Field <Int16>("Dbf_Uff_Fine_PM") != 0)
                            {
                                TimesheetEVM office = new TimesheetEVM();
                                office.Timestamp = timestamp;

                                office.TravelStartTimeAM = null;
                                office.WorkStartTimeAM   = r.Field <Int16>("Dbf_Uff_Inizio_AM") > 0 ? (long?)TimeSpan.FromMinutes(r.Field <Int16>("Dbf_Uff_Inizio_AM")).TotalSeconds : null;
                                office.WorkEndTimeAM     = r.Field <Int16>("Dbf_Uff_Fine_AM") > 0 ? (long?)TimeSpan.FromMinutes(r.Field <Int16>("Dbf_Uff_Fine_AM")).TotalSeconds : null;
                                office.TravelEndTimeAM   = null;
                                office.TravelStartTimePM = null;
                                office.WorkStartTimePM   = r.Field <Int16>("Dbf_Uff_Inizio_PM") > 0 ? (long?)TimeSpan.FromMinutes(r.Field <Int16>("Dbf_Uff_Inizio_PM")).TotalSeconds : null;
                                office.WorkEndTimePM     = r.Field <Int16>("Dbf_Uff_Fine_PM") > 0 ? (long?)TimeSpan.FromMinutes(r.Field <Int16>("Dbf_Uff_Fine_PM")).TotalSeconds : null;
                                office.TravelEndTimePM   = null;

                                if (db.Timesheets.Where(x => x.Timestamp == office.Timestamp && office.FDL == string.Empty).Count() == 0)
                                {
                                    office.Save(db);
                                }
                            }

                            // Factory association
                            short? factoryId = r.Field <short?>("Dbf_Impianto");
                            string fdlId     = FormatFDL(r.Field <string>("Dbf_Foglio"));

                            if (factoryId.HasValue && _factories.ContainsKey(factoryId.Value) && !string.IsNullOrEmpty(fdlId))
                            {
                                FDL fdl = db.FDLs.SingleOrDefault(f => f.Id == fdlId);

                                if (fdl != null)
                                {
                                    if (!fdl.Factory.HasValue)
                                    {
                                        fdl.Factory = _factories[factoryId.Value];
                                        db.FDLs.AddOrUpdate(fdl);
                                        db.SaveChanges();
                                    }
                                }
                                else
                                {
                                    Warning($"The FDL {fdlId} is missing on database. Impossible to assign the factory to the current timesheet. Day: {d.Date.ToShortDateString()}");
                                }
                            }

                            short? factory2Id = r.Field <short?>("Dbf_SecondoImpianto");
                            string fdl2Id     = FormatFDL(r.Field <string>("Dbf_SecondoFoglio"));

                            if (factory2Id.HasValue && _factories.ContainsKey(factory2Id.Value) && !string.IsNullOrEmpty(fdl2Id))
                            {
                                FDL fdl = db.FDLs.SingleOrDefault(f => f.Id == fdl2Id);

                                if (fdl != null && !fdl.Factory.HasValue)
                                {
                                    fdl.Factory = _factories[factory2Id.Value];
                                    db.FDLs.AddOrUpdate(fdl);
                                    db.SaveChanges();
                                }
                                else
                                {
                                    Warning($"The second FDL {fdlId} is missing on database. Impossible to assign the factory to the current timesheet. Day: {d.Date.ToShortDateString()}");
                                }
                            }

                            Message($"Day {d.Date.ToShortDateString()} OK");
                        }
                        catch (Exception ex)
                        {
                            Error($"Failed to import the Timesheet {d.Date.ToShortDateString()}. {ex}", ex);
                        }
                    }

                    db.SaveChanges();
                    result = true;
                }
            }
            catch (Exception ex)
            {
                Error($"Failed importing the timesheets. {ex}", ex);
            }

            return(result);
        }
        private void UpdaterThread()
        {
            bool           exit    = false;
            XmlDocument    xdoc    = new XmlDocument();
            HttpWebRequest request = null;

            while (!exit)
            {
                try
                {
                    using (DBArchive db = new DBArchive())
                    {
                        // try to get user Id
                        if (sharepointUserId == 0)
                        {
                            request = (HttpWebRequest)WebRequest.Create($"{ApplicationSettings.General.IntranetAddress}/_api/web/currentuser");

                            if (UserSettings.Email.UseDefaultCredentials)
                            {
                                request.UseDefaultCredentials = true;
                            }
                            else
                            {
                                request.Credentials = new NetworkCredential(UserSettings.Email.Username, UserSettings.Email.EmailPassword);
                            }

                            request.Method = "GET";

                            var webResponse = new StreamReader(request.GetResponse().GetResponseStream()).ReadToEnd();
                            xdoc.LoadXml(webResponse);
                            sharepointUserId = Convert.ToInt32(xdoc.GetElementsByTagName("content")[0].FirstChild.FirstChild.LastChild.Value.ToString());
                        }

                        //take in account only if current user id is retrieved
                        if (sharepointUserId > 0)
                        {
                            // try to get all submitted events
                            string req = $"{ApplicationSettings.General.IntranetAddress}/_api/web/Lists/GetByTitle('Vacations ITA')/Items?$filter=Author/Id eq {sharepointUserId}";

                            request = (HttpWebRequest)WebRequest.Create(req);

                            if (UserSettings.Email.UseDefaultCredentials)
                            {
                                request.UseDefaultCredentials = true;
                            }
                            else
                            {
                                request.Credentials = new NetworkCredential(UserSettings.Email.Username, UserSettings.Email.EmailPassword);
                            }

                            request.Method = "GET";

                            var webResponse = new StreamReader(request.GetResponse().GetResponseStream()).ReadToEnd();
                            xdoc.LoadXml(webResponse);

                            foreach (XmlElement el in xdoc.GetElementsByTagName("entry"))
                            {
                                Int64 shpid  = Convert.ToInt64(el.GetElementsByTagName("content")[0]?.FirstChild["d:Id"].InnerText);
                                int   status = Convert.ToInt32(el.GetElementsByTagName("content")[0]?.FirstChild["d:OData__ModerationStatus"].InnerText);

                                if (shpid == 0)
                                {
                                    continue;
                                }

                                EventEVM tmp = new EventEVM();
                                tmp.IsSent       = true; // the event is on calendar. Not necessary to send it
                                tmp.SharePointId = shpid;
                                tmp.Title        = el.GetElementsByTagName("content")[0]?.FirstChild["d:Title"].InnerText.Trim('*');
                                tmp.Location     = el.GetElementsByTagName("content")[0]?.FirstChild["d:Location"].InnerText;
                                tmp.Description  = el.GetElementsByTagName("content")[0]?.FirstChild["d:Description"].InnerText;
                                tmp.Status       = status;
                                tmp.IsAllDay     = Convert.ToBoolean(el.GetElementsByTagName("content")[0]?.FirstChild["d:fAllDayEvent"].InnerText);
                                tmp.SendDateTime = Convert.ToDateTime(el.GetElementsByTagName("content")[0]?.FirstChild["d:Created"].InnerText);

                                if (tmp.IsAllDay)
                                {
                                    tmp.StartDate = Convert.ToDateTime(el.GetElementsByTagName("content")[0]?.FirstChild["d:EventDate"].InnerText.TrimEnd('Z'));
                                    tmp.EndDate   = Convert.ToDateTime(el.GetElementsByTagName("content")[0]?.FirstChild["d:EndDate"].InnerText.TrimEnd('Z'));
                                }
                                else
                                {
                                    tmp.StartDate = Convert.ToDateTime(el.GetElementsByTagName("content")[0]?.FirstChild["d:EventDate"].InnerText);
                                    tmp.EndDate   = Convert.ToDateTime(el.GetElementsByTagName("content")[0]?.FirstChild["d:EndDate"].InnerText);
                                }

                                if (el.GetElementsByTagName("content")[0]?.FirstChild["d:Category"].InnerText == "Vacations")
                                {
                                    tmp.EType = EEventType.Vacations;
                                }
                                else if (el.GetElementsByTagName("content")[0]?.FirstChild["d:Category"].InnerText == "Customer Visit")
                                {
                                    tmp.EType = EEventType.CustomerVisit;
                                }
                                else if (el.GetElementsByTagName("content")[0]?.FirstChild["d:Category"].InnerText == "Business Trip")
                                {
                                    tmp.EType = EEventType.BusinessTrip;
                                }
                                else if (el.GetElementsByTagName("content")[0]?.FirstChild["d:Category"].InnerText == "Education")
                                {
                                    tmp.EType = EEventType.Education;
                                }
                                else if (el.GetElementsByTagName("content")[0]?.FirstChild["d:Category"].InnerText == "Other")
                                {
                                    tmp.EType = EEventType.Other;
                                }
                                else if (el.GetElementsByTagName("content")[0]?.FirstChild["d:Category"].InnerText == "Old Vacations")
                                {
                                    tmp.EType = EEventType.OldVacations;
                                }

                                if (tmp.EStatus == EEventStatus.Accepted)
                                {
                                    tmp.ApprovationDate = Convert.ToDateTime(el.GetElementsByTagName("content")[0]?.FirstChild["d:Modified"].InnerText);
                                    tmp.Approver        = el.GetElementsByTagName("content")[0]?.FirstChild["d:Approver"].InnerText;
                                }



                                if (db.Events.SingleOrDefault(x => x.SharepointId == shpid) == null)
                                {
                                    tmp.Save(db);
                                    NotifyEventImported(tmp);
                                }

                                else
                                {
                                    var existing = new EventEVM(db.Events.SingleOrDefault(x => x.SharepointId == shpid));
                                    if (existing != null)
                                    {
                                        tmp.Id = existing.Id;
                                        if (!tmp.Equals(existing) && !existing.IsCancelRequested)
                                        {
                                            tmp.Id    = existing.Id;
                                            tmp.Notes = existing.Notes;
                                            //Global.Mapper.Map(tmp, existing);
                                            tmp.Save(db);
                                            NotifyEventChanged(tmp);
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
                catch (Exception ex)
                {
                }

                Thread.Sleep(ApplicationSettings.General.WaitForNextEventCheck);
            }
        }
Esempio n. 7
0
        private bool CompileCarRents()
        {
            bool result = false;
            IDictionary <string, long> _cars = new Dictionary <string, long>();

            if (stopImport)
            {
                return(result);
            }

            StatusChanged("Importing Car Rents...");

            try
            {
                using (DBArchive db = new DBArchive())
                {
                    //Get enumerable rows fron datatable
                    IEnumerable <DataRow> collection = dtCars.Rows.Cast <DataRow>();

                    var cars = collection.GroupBy(c => c.Field <string>("dbf_Targa")).Select(c => c.First());

                    // Import Cars
                    foreach (DataRow r in cars)
                    {
                        if (stopImport)
                        {
                            break;
                        }

                        Car car = new Car();

                        try
                        {
                            car.LicensePlate     = r.Field <string>("dbf_Targa").Trim();
                            car.Brand            = r.Field <string>("dbf_Marca").Trim();
                            car.Model            = r.Field <string>("dbf_Modello").Trim();
                            car.CarRentalCompany = r.Field <short>("dbf_Nolo");

                            db.Cars.AddOrUpdate(x => x.LicensePlate, car);
                            db.SaveChanges();

                            _cars.Add(r.Field <string>("dbf_Targa"), car.Id);

                            Message($"Car {car.LicensePlate} | {car.Brand} {car.Model} OK");
                        }
                        catch (Exception ex)
                        {
                            Error($"Failed to import the car {car.LicensePlate}. {ex}", ex);
                        }
                    }

                    // Import Rents
                    foreach (DataRow r in collection)
                    {
                        if (stopImport)
                        {
                            break;
                        }

                        string licensePlate = r.Field <string>("dbf_Targa");
                        if (_cars.ContainsKey(licensePlate))
                        {
                            CarRentalHistory his = new CarRentalHistory();
                            try
                            {
                                his.Car           = _cars[licensePlate];
                                his.StartKm       = r.Field <int>("dbf_KmInizio");
                                his.EndKm         = r.Field <int>("dbf_KmFine");
                                his.StartLocation = r.Field <string>("dbf_LuogoPrel").Trim();
                                his.EndLocation   = r.Field <string>("dbf_LuogoDepo").Trim();

                                his.StartDate = (r.Field <DateTime>("dbf_DataPrel") + r.Field <DateTime>("dbf_OraPrel").TimeOfDay).ToUnixTimestamp();
                                his.EndDate   = (r.Field <DateTime>("dbf_DataDepo") + r.Field <DateTime>("dbf_OraDepo").TimeOfDay).ToUnixTimestamp();

                                his.StartFuelLevel = r.Field <short>("dbf_SerbPrel");
                                his.EndFuelLevel   = r.Field <short>("dbf_SerbRicon");
                                his.Notes          = r.Field <string>("dbf_Note").Trim();

                                db.CarRentalHistories.AddOrUpdate(x => x.StartDate, his);

                                Message($"Rent {DateTime.Now.FromUnixTimestamp(his.StartDate).ToShortDateString()} Car {licensePlate} OK");
                            }
                            catch (Exception ex)
                            {
                                Error($"Failed to import the rent in date {DateTime.Now.FromUnixTimestamp(his.StartDate).ToShortDateString()}, Car {licensePlate}. {ex}", ex);
                            }
                        }
                    }

                    db.SaveChanges();
                }
            }
            catch (Exception ex)
            {
                Error($"Failed importing car rents. {ex}", ex);
            }

            return(result);
        }
Esempio n. 8
0
        private void SenderThread()
        {
            bool exit = false;

            while (!exit)
            {
                using (DBArchive db = new DBArchive())
                {
                    foreach (EventEVM ev in db.Events.ToList().Select(v => new EventEVM(v)).Where(e => !e.IsSent))
                    {
                        try
                        {
                            XmlDocument xdoc;
                            XmlNode     request = null;

                            switch (ev.EStatus)
                            {
                            case EEventStatus.Pending:

                                if (ev.SharePointId > 0)
                                {
                                    request = GenerateBatchUpdateXML(ev);
                                }
                                else
                                {
                                    request = GenerateBatchInsertXML(ev);
                                }

                                using (SharepointReference.Lists l = new SharepointReference.Lists())
                                {
                                    l.Credentials = new NetworkCredential(UserSettings.Email.Username, UserSettings.Email.EmailPassword);
                                    xdoc          = new XmlDocument();

                                    var response = l.UpdateListItems("Vacations ITA", request.FirstChild);
                                    xdoc.LoadXml(response.OuterXml);
                                    var eventId = Convert.ToInt32(xdoc.GetElementsByTagName("z:row")[0]?.Attributes["ows_ID"].Value ?? "0");
                                    var ecode   = Convert.ToInt32(xdoc.GetElementsByTagName("ErrorCode")[0].Value);

                                    if (eventId > 0 && ecode == 0)
                                    {
                                        ev.SharePointId = eventId;
                                        ev.SendDateTime = DateTime.Now;
                                        ev.IsSent       = true;
                                        ev.Save(db);

                                        NotifyEventChanged(ev);
                                    }
                                }
                                break;

                            case EEventStatus.Rejected:

                                if (ev.SharePointId == 0)
                                {
                                    ev.IsSent = true;
                                    ev.Save(db);
                                    continue;
                                }
                                request = GenerateBatchDeletetXML(ev);
                                using (SharepointReference.Lists l = new SharepointReference.Lists())
                                {
                                    l.Credentials = new NetworkCredential(UserSettings.Email.Username, UserSettings.Email.EmailPassword);
                                    xdoc          = new XmlDocument();

                                    var response = l.UpdateListItems("Vacations ITA", request.FirstChild);
                                    xdoc.LoadXml(response.OuterXml);
                                    var ecode = Convert.ToInt32(xdoc.GetElementsByTagName("ErrorCode")[0].Value);

                                    if (ecode == 0)
                                    {
                                        ev.IsSent = true;
                                        ev.Save(db);
                                        NotifyEventChanged(ev);
                                    }
                                }

                                break;
                            }
                        }
                        catch (Exception)
                        {
                            continue;
                        }
                    }
                }

                Thread.Sleep(ApplicationSettings.General.WaitForNextEventChek);
            }
        }
Esempio n. 9
0
        private void UpdaterThread()
        {
            bool           exit    = false;
            XmlDocument    xdoc    = new XmlDocument();
            HttpWebRequest request = null;

            while (!exit)
            {
                try
                {
                    using (DBArchive db = new DBArchive())
                    {
                        // try to get user Id
                        if (sharepointUserId == 0)
                        {
                            request             = (HttpWebRequest)WebRequest.Create("https://intranet.elettric80.it/_api/web/currentuser");
                            request.Credentials = new NetworkCredential(UserSettings.Email.Username, UserSettings.Email.EmailPassword);
                            request.Method      = "GET";

                            var webResponse = new StreamReader(request.GetResponse().GetResponseStream()).ReadToEnd();
                            xdoc.LoadXml(webResponse);
                            sharepointUserId = Convert.ToInt32(xdoc.GetElementsByTagName("content")[0].FirstChild.FirstChild.LastChild.Value.ToString());
                        }

                        //take in account only if current user id is retrieved
                        if (sharepointUserId > 0)
                        {
                            // try to get all submitted events
                            string req = string.Format("https://intranet.elettric80.it/_api/web/Lists/GetByTitle('Vacations ITA')/Items?$filter=Author/Id eq {0}", sharepointUserId);

                            request             = (HttpWebRequest)WebRequest.Create(req);
                            request.Credentials = new NetworkCredential(UserSettings.Email.Username, UserSettings.Email.EmailPassword);
                            request.Method      = "GET";

                            var webResponse = new StreamReader(request.GetResponse().GetResponseStream()).ReadToEnd();
                            xdoc.LoadXml(webResponse);

                            foreach (XmlElement el in xdoc.GetElementsByTagName("entry"))
                            {
                                Int64 shpid  = Convert.ToInt64(el.GetElementsByTagName("content")[0]?.FirstChild["d:Id"].InnerText);
                                int   status = Convert.ToInt32(el.GetElementsByTagName("content")[0]?.FirstChild["d:OData__ModerationStatus"].InnerText);

                                var existing = db.Events.SingleOrDefault(x => x.SharepointId == shpid);

                                if (shpid == 0)
                                {
                                    continue;
                                }
                                if (existing == null)
                                {
                                    //manually added to calendar. Import it!
                                    EventEVM tmp = new EventEVM();
                                    tmp.IsSent       = true; // the event is on calendar. Not necessary to send it
                                    tmp.SharePointId = shpid;
                                    tmp.Title        = el.GetElementsByTagName("content")[0]?.FirstChild["d:Title"].InnerText.Trim('*');
                                    tmp.Location     = el.GetElementsByTagName("content")[0]?.FirstChild["d:Location"].InnerText;
                                    tmp.StartDate    = Convert.ToDateTime(el.GetElementsByTagName("content")[0]?.FirstChild["d:EventDate"].InnerText);
                                    tmp.EndDate      = Convert.ToDateTime(el.GetElementsByTagName("content")[0]?.FirstChild["d:EndDate"].InnerText);
                                    tmp.Description  = el.GetElementsByTagName("content")[0]?.FirstChild["d:Description"].InnerText;
                                    tmp.Status       = status;
                                    tmp.IsAllDay     = Convert.ToBoolean(el.GetElementsByTagName("content")[0]?.FirstChild["d:fAllDayEvent"].InnerText);
                                    tmp.SendDateTime = Convert.ToDateTime(el.GetElementsByTagName("content")[0]?.FirstChild["d:Created"].InnerText);

                                    //FIx 2:00 am on sharepoint calendar that broke timestamp relation!
                                    if (tmp.IsAllDay)
                                    {
                                        tmp.StartDate = new DateTime(tmp.StartDate.Year, tmp.StartDate.Month, tmp.StartDate.Day, 0, 0, 0);
                                        tmp.EndDate   = new DateTime(tmp.EndDate.Year, tmp.EndDate.Month, tmp.EndDate.Day, 0, 0, 0);
                                    }

                                    if (el.GetElementsByTagName("content")[0]?.FirstChild["d:Category"].InnerText == "Vacations")
                                    {
                                        tmp.EType = EEventType.Vacations;
                                    }
                                    else if (el.GetElementsByTagName("content")[0]?.FirstChild["d:Category"].InnerText == "Customer Visit")
                                    {
                                        tmp.EType = EEventType.CustomerVisit;
                                    }
                                    else if (el.GetElementsByTagName("content")[0]?.FirstChild["d:Category"].InnerText == "Business Trip")
                                    {
                                        tmp.EType = EEventType.BusinessTrip;
                                    }
                                    else if (el.GetElementsByTagName("content")[0]?.FirstChild["d:Category"].InnerText == "Education")
                                    {
                                        tmp.EType = EEventType.Education;
                                    }
                                    else if (el.GetElementsByTagName("content")[0]?.FirstChild["d:Category"].InnerText == "Other")
                                    {
                                        tmp.EType = EEventType.Other;
                                    }
                                    else if (el.GetElementsByTagName("content")[0]?.FirstChild["d:Category"].InnerText == "Old Vacations")
                                    {
                                        tmp.EType = EEventType.OldVacations;
                                    }

                                    if (tmp.EStatus == EEventStatus.Accepted)
                                    {
                                        tmp.ApprovationDate = Convert.ToDateTime(el.GetElementsByTagName("content")[0]?.FirstChild["d:Modified"].InnerText);
                                        tmp.Approver        = el.GetElementsByTagName("content")[0]?.FirstChild["d:Approver"].InnerText;
                                    }

                                    tmp.Save(db);

                                    if (tmp.EStatus != EEventStatus.Rejected)
                                    {
                                        NotifyEventImported(tmp);
                                    }
                                }
                                else
                                {
                                    EventEVM tmp = new EventEVM(existing);

                                    //if event does not have relations create it this is to patch error on previous releases
                                    if (!db.DayEvents.Any(x => x.EventId == tmp.Id))
                                    {
                                        if (tmp.EStatus != EEventStatus.Pending || tmp.EType != EEventType.Vacations)
                                        {
                                            continue;
                                        }
                                    }

                                    if ((EEventStatus)status < tmp.EStatus)
                                    {
                                        tmp.EStatus         = (EEventStatus)status;
                                        tmp.ApprovationDate = Convert.ToDateTime(el.GetElementsByTagName("content")[0]?.FirstChild["d:Modified"].InnerText);

                                        tmp.Save(db);
                                        NotifyEventChanged(tmp);
                                    }
                                }
                            }
                        }
                    }
                }
                catch (Exception)
                {
                }

                Thread.Sleep(ApplicationSettings.General.WaitForNextEventChek);
            }
        }
Esempio n. 10
0
        private bool ImportFDLFiles()
        {
            bool result = false;

            if (stopImport)
            {
                return(result);
            }

            StatusChanged("Importing FDL files...");

            try
            {
                foreach (FileInfo file in new DirectoryInfo(FDLFolder).GetFiles("*.pdf", SearchOption.AllDirectories))
                {
                    if (stopImport)
                    {
                        break;
                    }

                    if (FDLManager.GetFileType(file.Name) != EFileType.FDL)
                    {
                        continue;
                    }

                    FDLEVM fdl = null;

                    try
                    {
                        fdl = FDLManager.ImportFDLFromFile(file.FullName, false, false, false, false, true);

                        // try with XFA format
                        if (fdl == null)
                        {
                            fdl = FDLManager.ImportFDLFromFile(file.FullName, true, false, false, false, true);
                        }

                        if (fdl != null)
                        {
                            File.Copy(file.FullName, Path.Combine(ApplicationSettings.Directories.FDL, file.Name), true);

                            if (UserSettings.Advanced.ExcelExpenseAccount)
                            {
                                FDLManager.CreateExcelEA(fdl);
                            }

                            using (DBArchive db = new DBArchive())
                            {
                                // we must override received fdl with the same of current dbcontext istance
                                FDL currentFdl = db.FDLs.SingleOrDefault(f => f.Id == fdl.Id);

                                if (currentFdl != null)
                                {
                                    FDLEVM tmpFdl = new FDLEVM(currentFdl);

                                    if (tmpFdl.StartDayDate.Year < DateTime.Now.Year || (tmpFdl.StartDayDate.Year == DateTime.Now.Year && tmpFdl.WeekNr < DateTime.Now.WeekNr()))
                                    {
                                        tmpFdl.EStatus = EFDLStatus.Accepted;
                                        tmpFdl.Save(db);
                                    }
                                }
                                else
                                {
                                    Error("Missing FDL on database. Should never happen.");
                                }
                            }

                            Message($"FDL {fdl.Id} OK");
                        }
                        else
                        {
                            Error($"Failed to import FDL from file: {file.FullName}");
                        }
                    }
                    catch (Exception ex)
                    {
                        Error($"Failed importing FDL {fdl?.Id}. {ex}", ex);
                    }
                }

                result = true;
            }
            catch (Exception ex)
            {
                Error($"Failed importing FDLs. {ex}", ex);
            }

            return(result);
        }
Esempio n. 11
0
        private bool ImportEAFiles()
        {
            bool result = false;

            if (stopImport)
            {
                return(result);
            }

            StatusChanged("Importing Expense Account files...");

            try
            {
                foreach (FileInfo file in new DirectoryInfo(FDLFolder).GetFiles("*.pdf", SearchOption.AllDirectories))
                {
                    if (stopImport)
                    {
                        break;
                    }

                    if (FDLManager.GetFileType(file.Name) != EFileType.ExpenseAccount)
                    {
                        continue;
                    }

                    ExpenseAccountEVM ea = null;

                    try
                    {
                        ea = FDLManager.ImportEAFromFile(file.FullName, false, false, true);

                        if (ea != null)
                        {
                            File.Copy(file.FullName, Path.Combine(ApplicationSettings.Directories.ExpenseAccount, file.Name), true);

                            using (DBArchive db = new DBArchive())
                            {
                                // we must override recived EA with the same of current dbcontext istance
                                ExpenseAccount currentEA = db.ExpenseAccounts.SingleOrDefault(e => e.Id == ea.Id);

                                if (currentEA != null)
                                {
                                    currentEA.Status = currentEA.FDL1.Status;

                                    if (currentEA.Status == (long)EFDLStatus.Accepted)
                                    {
                                        currentEA.IsRefunded = true;
                                    }

                                    db.ExpenseAccounts.AddOrUpdate(currentEA);
                                    db.SaveChanges();
                                }
                                else
                                {
                                    Error("Missing EA on database. Should never happen.");
                                }
                            }

                            Message($"Expense Account {ea.FDL} OK");
                        }
                        else
                        {
                            Error($"Failed to import EA from file: {file.FullName}");
                        }
                    }
                    catch (Exception ex)
                    {
                        Error($"Failed importing EA {ea?.FDL}. {ex}", ex);
                    }
                }

                result = true;
            }
            catch (Exception ex)
            {
                Error($"Failed importing expense accounts. {ex}", ex);
            }

            return(result);
        }
Esempio n. 12
0
 public abstract bool Delete(DBArchive db);
Esempio n. 13
0
        private bool CompileFdlTable()
        {
            bool result = false;

            if (stopImport)
            {
                return(result);
            }

            StatusChanged("Importing PDF files...");

            try
            {
                IEnumerable <DataRow> sentFiles = dtSentFiles.Rows.Cast <DataRow>();

                foreach (FileInfo file in new DirectoryInfo(_sourceFdlPath).GetFiles("*.pdf", SearchOption.AllDirectories))
                {
                    if (stopImport)
                    {
                        break;
                    }

                    FDLEVM fdl = null;

                    try
                    {
                        fdl = FDLManager.ImportFDLFromFile(file.FullName, false, false, false, true, true);

                        // try with XFA format
                        if (fdl == null)
                        {
                            fdl = FDLManager.ImportFDLFromFile(file.FullName, true, false, false, true, true);
                        }

                        if (fdl != null)
                        {
                            File.Copy(file.FullName, Path.Combine(ApplicationSettings.Directories.FDL, file.Name), true);

                            DataRow sent = sentFiles.Where(f => !string.IsNullOrEmpty(f.Field <string>("Dbf_Foglio")) && FormatFDL(f.Field <string>("Dbf_Foglio")) == fdl.Id && (f.Field <int>("dbf_TipoInvio") == 2 || f.Field <int>("dbf_TipoInvio") == 4)).Select(f => f)
                                           .OrderBy(x => x.Field <int>("Dbf_NumeroInviiPrima") == 0)
                                           .ThenBy(x => string.IsNullOrEmpty(x.Field <string>("Dbf_Impianto")))
                                           .ThenBy(x => string.IsNullOrEmpty(x.Field <string>("Dbf_Commessa")))
                                           .FirstOrDefault();

                            if (sent != null)
                            {
                                using (DBArchive db = new DBArchive())
                                {
                                    // we must override recived fdl with the same of current dbcontext istance
                                    FDL currentFdl = db.FDLs.SingleOrDefault(f => f.Id == fdl.Id);

                                    if (currentFdl != null)
                                    {
                                        if (sent.Field <int>("Dbf_NumeroInviiPrima") == 0)
                                        {
                                            currentFdl.Status = (long)EFDLStatus.Waiting;
                                        }
                                        else if (sent.Field <string>("Dbf_Impianto") != string.Empty && sent.Field <string>("Dbf_Commessa") != string.Empty)
                                        {
                                            currentFdl.Status = (long)EFDLStatus.Accepted;
                                        }
                                        else
                                        {
                                            currentFdl.Status = (long)EFDLStatus.Cancelled;
                                        }

                                        if (currentFdl.Status != (long)EFDLStatus.New)
                                        {
                                            currentFdl.IsReadOnly = true;
                                        }

                                        db.FDLs.AddOrUpdate(currentFdl);
                                        db.SaveChanges();
                                        Message($"FDL {currentFdl.Id} OK");
                                    }
                                    else
                                    {
                                        Error("Missing FDL on database. Should never happen.");
                                    }
                                }
                            }
                            else
                            {
                                Error("Missing FDL sent status!");
                            }
                        }
                        else
                        {
                            Error($"Failed to import FDL from file: {file.FullName}");
                        }
                    }
                    catch (Exception ex)
                    {
                        Error($"Failed importing FDL {fdl?.Id}. {ex}", ex);
                    }
                }

                result = true;
            }
            catch (Exception ex)
            {
                Error($"Failed importing FDLs. {ex}", ex);
            }

            return(result);
        }
Esempio n. 14
0
 public bool Delete()
 {
     using (DBArchive db = new DBArchive())
         return(Delete(db));
 }
Esempio n. 15
0
 public abstract bool Save(DBArchive db);
Esempio n. 16
0
 public bool Save()
 {
     using (DBArchive db = new DBArchive())
         return(Save(db));
 }
Esempio n. 17
0
 public abstract bool Refresh(DBArchive db);
Esempio n. 18
0
 public bool Refresh()
 {
     using (DBArchive db = new DBArchive())
         return(Refresh(db));
 }
Esempio n. 19
0
        private bool CompileEATable()
        {
            bool result = false;

            if (stopImport)
            {
                return(result);
            }

            StatusChanged("Importing Expense Account files...");

            try
            {
                IEnumerable <DataRow> expenses = dtExpenseReview.Rows.Cast <DataRow>();

                foreach (FileInfo file in new DirectoryInfo(_sourceEAPath).GetFiles("*.pdf", SearchOption.AllDirectories))
                {
                    if (stopImport)
                    {
                        break;
                    }

                    ExpenseAccountEVM ea = null;

                    try
                    {
                        ea = FDLManager.ImportEAFromFile(file.FullName, false, false, true);

                        if (ea != null)
                        {
                            File.Copy(file.FullName, Path.Combine(ApplicationSettings.Directories.ExpenseAccount, file.Name), true);

                            using (DBArchive db = new DBArchive())
                            {
                                // we must override recived EA with the same of current dbcontext istance
                                ExpenseAccount currentEA = db.ExpenseAccounts.SingleOrDefault(e => e.Id == ea.Id);

                                if (currentEA != null)
                                {
                                    FDL fdl = db.FDLs.SingleOrDefault(f => f.Id == currentEA.FDL);

                                    if (fdl != null)
                                    {
                                        currentEA.Status = fdl.Status;
                                    }
                                    else
                                    {
                                        currentEA.Status = (long)EFDLStatus.Accepted;
                                    }

                                    var expense = expenses.SingleOrDefault(e => !string.IsNullOrEmpty(e.Field <string>("Dbf_Foglio")) && FormatFDL(e.Field <string>("Dbf_Foglio")) == fdl.Id);
                                    currentEA.IsRefunded = expense != null && expense.Field <bool>("Dbf_Restituito");

                                    if (currentEA.Status != (long)EFDLStatus.New)
                                    {
                                        currentEA.IsReadOnly = true;
                                    }

                                    db.ExpenseAccounts.AddOrUpdate(currentEA);
                                    db.SaveChanges();
                                    Message($"Expense Account {currentEA.FDL} OK");
                                }
                                else
                                {
                                    Error("Missing EA on database. Should never happen.");
                                }
                            }
                        }
                        else
                        {
                            Error($"Failed to import EA from file: {file.FullName}");
                        }
                    }
                    catch (Exception ex)
                    {
                        Error($"Failed importing EA {ea?.FDL}. {ex}", ex);
                    }
                }

                result = true;
            }
            catch (Exception ex)
            {
                Error($"Failed importing expense accounts. {ex}", ex);
            }

            return(result);
        }
Esempio n. 20
0
        private bool CompileFactoriesTable()
        {
            bool result = false;

            if (stopImport)
                return result;

            StatusChanged("Importing Factories...");

            try
            {
                using (DBArchive db = new DBArchive())
                {
                    //Get enumerable rows fron datatable
                    IEnumerable<DataRow> collection = dtPlants.Rows.Cast<DataRow>();

                    foreach (DataRow r in collection)
                    {
                        if (stopImport)
                            break;

                        string FactoryName = r.Field<string>("dbf_Stabilimento");

                        FactoryEVM factory = db.Factories.Where(f => f.Name == FactoryName).ToList().Select(f => new FactoryEVM(f)).FirstOrDefault();

                        if (factory == null)
                            factory = new FactoryEVM();

                        try
                        {
                            factory.Name = FactoryName;
                            factory.CompanyName = r.Field<string>("dbf_RagioneSociale");
                            factory.Address = r.Field<string>("dbf_Indirizzo");
                            //factory.IsForfait = r.Field<bool>("dbf_Forfettario"); DEPRECATED

                            long transferType = r.Field<byte>("dbf_Tipo_Trasf");
                            factory.TransferType = transferType != 4 ? transferType : 0;

                            factory.Save(db);

                            _factories.Add(r.Field<int>("dbf_Index"), factory.Id);

                            Message($"Factory {factory.Name} OK");
                        }
                        catch (Exception ex)
                        {
                            Error($"Failed to import factory {factory.Name}. {ex}", ex);
                        }
                    }

                    db.SaveChanges();

                    result = true;
                }
            }
            catch (Exception ex)
            {
                result = false;
                Error($"Failed importing factories. {ex}", ex);
            }

            return result;
        }