| 1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837 | using System;using System.Collections.Generic;using System.Linq;using System.Text;using System.Threading;using System.Threading.Tasks;using Xamarin.Forms;using Xamarin.Forms.Maps;using InABox.Core;using InABox.Configuration;using InABox.Clients;using InABox.Mobile;using Comal.Classes;using XF.Material.Forms.UI.Dialogs;using comal.timesheets.CustomControls;using comal.timesheets.StoreRequis;using PRSSecurity = InABox.Core.Security;using Plugin.LocalNotification;using comal.timesheets.Tasks;using System.IO;namespace comal.timesheets{    public partial class MainPage : ContentPage    {        #region Fields        List<ToolEntry> toolEntries = new List<ToolEntry>();        private TimeSheet _timesheet = null;        private Employee _employee = null;        private CoreTable _jobs = null;        public bool SettingsChanged { get; private set; }        bool bUpdatingTimesheet = false;        bool firstLoad = true;        bool recentlyAskedToUpdate = true;        int updateCounter;        public static ConnectionSettings connectionSettings = null;        bool midnightTimerOn = false;        DateTime oneSecondBeforeMidnight = DateTime.Today.AddSeconds(864399);        bool clockedOffInLast5Seconds = false;        bool bRecentlyUpdatedTiles = false;        bool bSharedDeviceFirstLoad = true;        bool bSharedDevice = false;        int NumberOfNotfications = 0;        private Job _job = new Job();        string deviceName = "";        string matchedDeviceName = "";        int notCount = 1;        #endregion        #region Constructor        public MainPage()        {            InitializeComponent();            try            {                App.GPS.OnLocationFound += LocationFound;                App.GPS.OnLocationError += LocationError;                App.Bluetooth.OnScanFinished += ScanFinished;                App.Data.DataChanged += DataChanged;                App.Data.DataRefreshed += DataRefreshed;                GlobalVariables.EmpID = GlobalVariables.GetEmployeeID();                GlobalVariables.EmpName = GlobalVariables.GetEmployeeName();                MessagingCenter.Subscribe<App>(this, App.MessageOnResume,                (o) =>                {                    if (!App.GPS.RecentlyLocated)                        App.GPS.GetLocation();                    RefreshScreen();                }                );                _timesheet = App.Data.TimeSheets?.Rows.FirstOrDefault()?.ToObject<TimeSheet>();                _employee = App.Data.Employee;                _jobs = App.Data.Jobs;                deviceName = MobileUtils.GetDeviceID();                LoadCacheLists();                InitToolEntryList();                Timer t = new Timer(RecentlyAskedToUpdateTimer, null, 600000, 600000); //user is reminded to update when opening screen after timer of 10 minutes                updateCounter = 1; //user is forced to update after 3rd reminder                Timer t1 = new Timer(RecentlyUpdatedTilesTimer, null, 30000, 30000);                //bluetooth data is allowed to upload once every minute, notifications refreshing is piggybacked to this too                InitNotificationCentre();                firstLoad = false;                //if (GlobalVariables.EmpID == Guid.Parse("40f6ccd9-5272-4b1a-99bf-de7542205aac"))                //    RunCustomScript();                NotifyChanges()                          }            catch (Exception e)            {            }            NavigationPage.SetHasBackButton(this, false);        }                private void RunCustomScript()        {        }        private void NotifyChanges()        {            string latestChanges = "";            List<string> changes = new List<string>            {                "- Upgrade to Setouts Module"            };            foreach (string s in changes)            {                latestChanges = s + System.Environment.NewLine + latestChanges;            }            Task.Run(() =>            {                if (App.Current.Properties.Count > 0)                {                    List<string> toDelete = new List<string>();                    foreach (string s in App.Current.Properties.Keys)                    {                        if (s.Contains("NotifiedOfChanges"))                        {                            if (!s.Equals("NotifiedOfChanges" + MobileUtils.AppVersion.InstalledVersionNumber))                            {                                toDelete.Add(s);                            }                        }                    }                    foreach (string s in toDelete)                    {                        App.Current.Properties.Remove(s);                    }                }                if (!App.Current.Properties.ContainsKey("NotifiedOfChanges" + MobileUtils.AppVersion.InstalledVersionNumber))                {                    App.Current.Properties.Add("NotifiedOfChanges" + MobileUtils.AppVersion.InstalledVersionNumber, "True");                    Thread.Sleep(7500);                    Device.BeginInvokeOnMainThread(() =>                    {                        DisplayAlert("Latest Changes", latestChanges                            , "OK");                    });                }            });        }        #endregion        #region OnAppearing and Display        protected override void OnAppearing()        {            if (!App.IsUserLoggedIn)            {                Navigation.PopAsync();                return;            }            //if (Application.Current.Properties.ContainsKey("IsSharedDevice"))            //{            //    if (Application.Current.Properties["IsSharedDevice"].Equals("True"))            //    {            //        bSharedDevice = true;            //        if (!bSharedDeviceFirstLoad)            //        {            //            App.LogoutUser();            //            Navigation.PopToRootAsync();            //        }            //        else            //        {            //            bSharedDeviceFirstLoad = false;            //            clockOnButton.IsEnabled = false;            //            clockOnButton.Text = "Shared Device";            //            clockOnButton.BackgroundColor = Color.CornflowerBlue;            //            CurrentLocation.IsVisible = false;            //            jobBtn.IsVisible = false;            //            addNoteBtn.IsVisible = false;            //            Grid.SetRowSpan(flexLayoutScrollView, 3);            //            Grid.SetRow(flexLayoutScrollView, 1);            //            Timer t = new Timer(AutoLogoutUser, null, 600000, Timeout.Infinite);            //        }            //    }            //    else            //        bSharedDevice = false;            //}            //getting strange results from .IsAllowed            //if (!PRSSecurity.IsAllowed<CanBypassTimeBench>())            //{            //    clockOnButton.IsVisible = false;            //    jobBtn.IsVisible = false;            //    addNoteBtn.IsVisible = false;            //    CurrentLocation.IsVisible = false;            //    row0.Height = 0;            //    row1.Height = 0;            //    row2.Height = 0;            //    ForceLayout();            //}            if (!firstLoad)                RefreshScreen();            Task.Run(async () =>            {                bool isLatest = true;                try                {                    isLatest = await MobileUtils.AppVersion.IsUsingLatestVersion();                }                catch (Exception eLatest)                {                    if (!recentlyAskedToUpdate)                    {                        Device.BeginInvokeOnMainThread(() =>                        {                        });                        recentlyAskedToUpdate = true;                    }                    string s = eLatest.Message;                }                if (!isLatest)                {                    if (!recentlyAskedToUpdate)                    {                        string latestVersionNumber = await MobileUtils.AppVersion.GetLatestVersionNumber();                        if (updateCounter < 3)                        {                            Device.BeginInvokeOnMainThread(async () =>                            {                                string chosenOption = await DisplayActionSheet(String.Format("Version {0} Available. Update now?", latestVersionNumber), "You will be reminded again in 10 minutes.", null, "Yes", "No");                                switch (chosenOption)                                {                                    case "No":                                        break;                                    case "Cancel":                                        break;                                    case "Yes":                                        Dispatcher.BeginInvokeOnMainThread(() => { MobileUtils.AppVersion.OpenAppInStore(); });                                        break;                                    default:                                        break;                                }                            });                        }                        else if (updateCounter >= 3)                        {                            Device.BeginInvokeOnMainThread(() =>                            {                                DisplayAlert(String.Format("Version {0} Available", latestVersionNumber), "Please update your software to the latest version.", "OK")                            .ContinueWith((Task task) =>                            {                                Dispatcher.BeginInvokeOnMainThread(() => { MobileUtils.AppVersion.OpenAppInStore(); });                            });                            });                        }                        recentlyAskedToUpdate = true;                        updateCounter++;                    }                }            });            base.OnAppearing();        }        private void RecentlyAskedToUpdateTimer(object o)        {            recentlyAskedToUpdate = false;        }        private void AutoLogoutUser(object o)        {            App.LogoutUser();            Navigation.PopToRootAsync();        }        private void RefreshScreen()        {            //if (bSharedDevice)            //    return;            try            {                Device.BeginInvokeOnMainThread(() =>                {                    homeScreenGrid.RaiseChild(CurrentLocation);                    bBusy = true;                    if (GlobalVariables.EmpID == Guid.Empty)                    {                        GlobalVariables.EmpID = GlobalVariables.GetEmployeeID();                        GlobalVariables.EmpName = GlobalVariables.GetEmployeeName();                    }                    clockOnButton.IsEnabled = false;                    bool PRSReady = (App.Data.Employee != null) && (App.Data.TimeSheets != null);                    bool GateReady = CheckLocation();                    CurrentLocation.Text = DisplayAddress();                    if (CurrentLocation.Text.Contains("ERROR"))                        CurrentLocation.Text = "Unknown Address";                    Title = null;                    Title = App.Data.Employee != null ? App.Data.Employee.Name : "";                    CoreRow timesheet = App.Data.TimeSheets?.Rows.FirstOrDefault();                    clockOnButton.Text = PRSReady && GateReady ? timesheet == null ? "CLOCK ON" : "CLOCK OFF" : "PLEASE WAIT";                    clockOnButton.IsEnabled = PRSReady && GateReady;                    clockOnButton.BackgroundColor = PRSReady && GateReady ? timesheet == null ? Color.FromHex("#e6e6fa") : Color.FromHex("#15C7C1") : Color.Gainsboro;                    clockOnButton.BorderColor = PRSReady && GateReady ? timesheet == null ? Color.Black : Color.FromHex("#15C7C1") : Color.Gainsboro;                    if (clockOnButton.Text == "CLOCK OFF")                    {                        addNoteBtn.IsEnabled = true;                        if (GlobalVariables.JobsLoaded)                            jobBtn.IsEnabled = true;                    }                    else                    {                        addNoteBtn.IsEnabled = false;                        jobBtn.IsEnabled = false;                    }                    if (firstLoad)                        RefreshJobFromTimeSheet(timesheet);                    homeScreenGrid.RaiseChild(CurrentLocation);                    firstLoad = false;                    bBusy = false;                });            }            catch (Exception e)            {            }            //CurrentLocation.IsEnabled = PRSReady && GateReady;        }        private void RefreshJobFromTimeSheet(CoreRow timesheet)        {            Guid jobid = timesheet == null ? Guid.Empty : timesheet.Get<TimeSheet, Guid>(x => x.JobLink.ID);            if (!jobid.Equals(Guid.Empty))            {                jobBtn.Text = String.Format("{0}: {1}", timesheet.Get<TimeSheet, String>(x => x.JobLink.JobNumber), timesheet.Get<TimeSheet, String>(x => x.JobLink.Name));                _job.ID = timesheet == null ? Guid.Empty : timesheet.Get<TimeSheet, Guid>(x => x.JobLink.ID);                _job.JobNumber = timesheet == null ? String.Empty : timesheet.Get<TimeSheet, String>(x => x.JobLink.JobNumber);                _job.Name = timesheet == null ? String.Empty : timesheet.Get<TimeSheet, String>(x => x.JobLink.Name);            }            else            {                jobBtn.Text = "No Job Selected";                _job = new Job();            }        }        #endregion        #region Clock on/off        private void DataChanged(object sender, Type type, Exception e)        {            //if (bSharedDevice)            //    return;            Device.BeginInvokeOnMainThread(() =>            {                if (e != null)                {                    //DisplayAlert("Connection error with server - double check your connection", e.Message, "OK");                }                else                    RefreshScreen();            });        }        private void DataRefreshed()        {            //if (bSharedDevice)            //    return;            Device.BeginInvokeOnMainThread(() => { RefreshScreen(); });        }        bool bBusy = false;        async void ClockOnOff_Clicked(object sender, System.EventArgs e)        {            if (bBusy)                return;            bBusy = true;            string chosenOption = "Continue";            if (clockOnButton.Text == "CLOCK OFF")            {                chosenOption = await DisplayActionSheet("Clock off?", "Cancel", null, "Continue", "Cancel");            }            switch (chosenOption)            {                case "Continue":                    break;                case "Cancel":                    bBusy = false;                    return;                    break;                default:                    bBusy = false;                    return;                    break;            }            if (clockOnButton.Text == "CLOCK ON" && clockedOffInLast5Seconds)            {                bBusy = false;                return;            }            try            {                using (await MaterialDialog.Instance.LoadingDialogAsync(message: "Loading"))                {                    InABox.Core.Location here = new InABox.Core.Location()                    {                        Latitude = App.GPS.Latitude,                        Longitude = App.GPS.Longitude,                        Timestamp = DateTime.Now                    };                    TimeSheet timesheet = App.Data.TimeSheets?.Rows.FirstOrDefault()?.ToObject<TimeSheet>();                    if (timesheet != null)                    {                        if (timesheet.ID != Guid.Empty)                        {                            if (ZeroLengthTimesheet())                            {                                bUpdatingTimesheet = true;                                new Client<TimeSheet>().Delete(timesheet, "Deleted due to zero duration timesheet");                                App.Data.TimeSheets.Rows.Clear();                            }                            else                            {                                FinishTimeSheet(timesheet, here);                            }                        }                    }                    else                    {                        Guid jobid = Guid.Empty;                        String jobnumber = "";                        String jobname = "";                        if (!App.Data.CanBypassGates)                        {                            CoreRow row = App.Data.Gates.Rows.FirstOrDefault(r => App.Bluetooth.Devices.Contains(r.Get<JobTracker, String>(c => c.TrackerLink.DeviceID)));                            if (row != null)                            {                                jobid = row.Get<JobTracker, Guid>(x => x.JobLink.ID);                                jobnumber = row.Get<JobTracker, String>(x => x.JobLink.JobNumber);                                jobname = row.Get<JobTracker, String>(x => x.JobLink.Name);                            }                            CreateTimeSheet(jobid, jobnumber, jobname, App.Data.Employee.UsualActivity.ID, App.Data.Employee.UsualActivity.Code, App.Data.Employee.UsualActivity.Description, here, App.GPS.Address, "Clocking On");                        }                        else                        {                            if ((!App.GPS.Latitude.Equals(0.0F)) && (!App.GPS.Longitude.Equals(0.0F)))                            {                                ChooseNearbyJob(here);                            }                        }                    }                    RefreshScreen();                }            }            catch (Exception e2)            {            }            bBusy = false;        }        #endregion        #region Bluetooth        private async void UploadTiles()        {            try            {                if (App.GPS.Latitude.Equals(0.0F) && App.GPS.Longitude.Equals(0.0F))                    return;                if (App.Bluetooth.DetectedBlueToothMACAddresses.Count == 0)                    return;                if (bRecentlyUpdatedTiles)                    return;                bRecentlyUpdatedTiles = true;                await Task.Run(() =>                {                    InABox.Core.Location curlocation = new InABox.Core.Location() { Latitude = App.GPS.Latitude, Longitude = App.GPS.Longitude };                    curlocation.Timestamp = DateTime.Now;                    List<GPSTrackerLocation> trackersToUpdate = new List<GPSTrackerLocation>();                    foreach (String id in App.Bluetooth.DetectedBlueToothMACAddresses)                    {                        GPSTracker tracker = GlobalVariables.GPSTrackerCache.Find(x => x.DeviceID.Equals(id));                        bool stale = tracker.Location.Timestamp < DateTime.Now.Subtract(new TimeSpan(0, 5, 0));                        bool moved = tracker.Location.DistanceTo(curlocation, UnitOfLength.Kilometers) > 0.1;                        if (stale || moved)                        {                            GlobalVariables.GPSTrackerCache.Remove(tracker);                            tracker.Location = curlocation;                            GlobalVariables.GPSTrackerCache.Add(tracker);                            //cache is updated                            GPSTrackerLocation gpsTrackerLocation = new GPSTrackerLocation();                            gpsTrackerLocation.DeviceID = tracker.DeviceID;                            gpsTrackerLocation.Location.Timestamp = tracker.Location.Timestamp;                            gpsTrackerLocation.Location = curlocation;                            trackersToUpdate.Add(gpsTrackerLocation);                        }                    }                    if (trackersToUpdate.Any())                    {                        if (ClientFactory.UserGuid != Guid.Empty)                            new Client<GPSTrackerLocation>().Save(trackersToUpdate, "Updating Bluetooth Device Locations");                    }                    App.Bluetooth.DetectedBlueToothMACAddresses.Clear();                }                );            }            catch (Exception e)            {            }            //if ((master != null) && (master.Location.Timestamp < DateTime.Now.Subtract(new TimeSpan(0, 15, 0))))            //{            //    GPSTrackerLocation device = new GPSTrackerLocation();            //    device.DeviceID = MobileUtils.GetDeviceID();            //    device.Location.Latitude = App.GPS.Latitude;            //    device.Location.Longitude = App.GPS.Longitude;            //    device.Location.Timestamp = DateTime.Now;            //    locations.Add(device);            //    //device.BatteryLevel = ((double)CrossBattery.Current.RemainingChargePercent);            //    //new Client<GPSTrackerLocation>().Save(device, "Updating Device Location"); //, SaveTrackerCallback);            //}            #region OLD            //for (int i = 0; i < App.Bluetooth.Devices.Length; i++)            //{            //    String id = App.Bluetooth.Devices[i];            //    int level = App.Bluetooth.BatteryLevels[i];            //    var btmaster = trackers.FirstOrDefault(x => x.DeviceID.Equals(id));            //    if ((btmaster != null) && (!locations.Any(x => x.DeviceID.Equals(btmaster.DeviceID))))            //    {            //        bool stale = btmaster.Location.Timestamp < DateTime.Now.Subtract(new TimeSpan(0, 15, 0));            //        bool moved = btmaster.Location.DistanceTo(curlocation, UnitOfLength.Kilometers) > 0.1;            //        if (stale || moved)            //        {            //            GPSTrackerLocation location = new GPSTrackerLocation();            //            location.DeviceID = id;            //            location.Location.Latitude = App.GPS.Latitude;            //            location.Location.Longitude = App.GPS.Longitude;            //            location.Location.Timestamp = DateTime.Now;            //            location.BatteryLevel = level;            //            locations.Add(location);            //        }            //    }            //    //new Client<GPSTrackerLocation>().Save(location, "Found Kontakt Device"); //, SaveTrackerCallback);            //}            //if (locations.Any())            //    new Client<GPSTrackerLocation>().Save(locations, "Updating Bluetooth Device Locations", (o, e) => { });            #endregion        }        private void RecentlyUpdatedTilesTimer(object o)        {            bRecentlyUpdatedTiles = false;            App.Data.Refresh(true);            SearchForNewNotifications();        }        private void LocationFound(LocationServices sender)        {            //if (bSharedDevice)            //    return;            if (App.Bluetooth.RecentlyScanned)                UploadTiles();            try            {                TimeSheet timesheet = App.Data.TimeSheets?.Rows.FirstOrDefault()?.ToObject<TimeSheet>();                if (timesheet != null)                {                    if (timesheet.StartLocation.Latitude.Equals(0.0F) && timesheet.StartLocation.Longitude.Equals(0.0F))                    {                        timesheet.StartLocation.Latitude = sender.Latitude;                        timesheet.StartLocation.Longitude = sender.Longitude;                        timesheet.StartLocation.Timestamp = sender.TimeStamp;                        timesheet.Address = sender.Address;                        new Client<TimeSheet>().Save(timesheet, "Updating Timesheet with GPS Coordinates", (o, e) => { });                    }                }                if (!string.IsNullOrWhiteSpace(matchedDeviceName))                {                    InABox.Core.Location curlocation = new InABox.Core.Location() { Latitude = App.GPS.Latitude, Longitude = App.GPS.Longitude };                    curlocation.Timestamp = DateTime.Now;                    GPSTrackerLocation gpsTrackerLocation = new GPSTrackerLocation();                    gpsTrackerLocation.DeviceID = matchedDeviceName;                    gpsTrackerLocation.Location.Timestamp = curlocation.Timestamp;                    gpsTrackerLocation.Location = curlocation;                    new Client<GPSTrackerLocation>().Save(gpsTrackerLocation, "Updated company device location from Timebench");                }                Device.BeginInvokeOnMainThread(() =>                {                    RefreshScreen();                });            }            catch { }        }        private void LocationError(LocationServices sebder, Exception error)        {        }        private void ScanFinished(Bluetooth sender)        {            try            {                //if (bSharedDevice)                //    return;                Device.BeginInvokeOnMainThread(() =>                {                    RefreshScreen();                    //if (Button2.BackgroundColor == Color.WhiteSmoke)                    //    Button2.BackgroundColor = Color.Red;                    //else                    //    Button2.BackgroundColor = Color.WhiteSmoke;                });                if (App.GPS.RecentlyLocated)                    UploadTiles();            }            catch { }        }        #endregion        #region Utilities        private void InitNotificationCentre()        {            try            {                LocalNotificationCenter.Current.NotificationActionTapped += (Plugin.LocalNotification.EventArgs.NotificationActionEventArgs e) =>                {                    string data = e.Request.ReturningData;                    int index = data.IndexOf("$");                    Guid ID = Guid.Parse(data.Remove(index));                    string type = data.Substring(index + 1);                    if (type == "Comal.Classes.Kanban")                    {                        Device.BeginInvokeOnMainThread(() =>                        {                            AddEditTask taskPage = new AddEditTask(ID);                            Navigation.PushAsync(taskPage);                        });                    }                };            }            catch { }        }        private async void SearchForNewNotifications()        {            //notifications poll reliably in the background for Anroid, unreliable for iOS due to difficulty with cross-platform plugins for notifications            try            {                await Task.Run(() =>                {                    if (ClientFactory.UserGuid != Guid.Empty)                    {                        CoreTable table = new Client<Notification>().Query                        (new Filter<Notification>(x => x.Employee.UserLink.ID).IsEqualTo(ClientFactory.UserGuid).And(X => X.Closed).IsEqualTo(DateTime.MinValue),                            new Columns<Notification>(                                   x => x.ID, //0                                   x => x.Sender.Name, //1                                      x => x.Title, //2                                   x => x.Created, //3                                   x => x.Description, //4                                   x => x.EntityType, //5                                   x => x.EntityID //6                                   )                        );                        if (NumberOfNotfications == table.Rows.Count()) //no new notifications or none present at all                            return;                        else //new notifications or previous notifications have now been dismissed                        {                            NumberOfNotfications = table.Rows.Count();                            RefreshOnNotificationsChange();                            CheckNotificationsPushed(table);                        }                    }                });            }            catch { }        }        private void RefreshOnNotificationsChange()        {            try            {                int index = toolEntries.FindIndex(x => x.Text.Equals("Notifications"));                toolEntries.RemoveAt(index);                string notificationsString = "";                if (NumberOfNotfications != 0)                {                    notificationsString = NumberOfNotfications.ToString();                }                ToolEntry Notifications = new ToolEntry(notificationsString)                {                    Text = "Notifications",                    Image = "notifications"                };                Notifications.OnTapped += (async (object sender, EventArgs e) =>                {                    using (await MaterialDialog.Instance.LoadingDialogAsync(message: "Loading"))                    {                        NotificationList notificationList = new NotificationList();                        notificationList.NotificationsClosed += (n) =>                        {                            NumberOfNotfications = n;                            RefreshOnNotificationsChange();                        };                        Navigation.PushAsync(notificationList);                    }                });                toolEntries.Insert(index, Notifications);                Device.BeginInvokeOnMainThread(() =>                {                    flexLayout.Children.RemoveAt(index);                    flexLayout.Children.Insert(index, toolEntries[index]);                });            }            catch { }        }        private void CheckNotificationsPushed(CoreTable table)        {            try            {                if (!Application.Current.Properties.ContainsKey("LastPushedNotifications"))                {                    Application.Current.Properties.Add("LastPushedNotifications", DateTime.Now);                }                DateTime lastPushed = DateTime.Parse(Application.Current.Properties["LastPushedNotifications"].ToString());                List<NotificationShell> toNotify = new List<NotificationShell>();                foreach (CoreRow row in table.Rows)                {                    List<object> list = row.Values;                    DateTime created = DateTime.Parse(list[3].ToString());                    if (created > new DateTime(2022, 8, 22)) // prevent spam from buildup of old notifications before this is released                    {                        if (created > lastPushed)                        {                            if (list[1] == null) list[1] = "";                            if (list[2] == null) list[2] = "";                            if (list[3] == null) list[3] = DateTime.MinValue;                            if (list[4] == null) list[4] = "";                            if (list[5] == null) list[5] = "";                            if (list[6] == null) list[6] = Guid.Empty;                            NotificationShell shell = new NotificationShell                            {                                ID = Guid.Parse(list[0].ToString()),                                Sender = list[1].ToString(),                                Title = list[2].ToString(),                                Created = DateTime.Parse(list[3].ToString()),                                EntityType = list[5].ToString(),                                EntityID = Guid.Parse(list[6].ToString())                            };                            toNotify.Add(shell); //add notification to be pushed                        }                    }                }                if (toNotify.Count > 0)                    PushNotificationsAsync(toNotify);            }            catch { }        }        private async Task PushNotificationsAsync(List<NotificationShell> shells)        {            try            {                int count = 1;                foreach (NotificationShell shell in shells)                {                    var notification = new NotificationRequest                    {                        BadgeNumber = 1,                        Description = shell.Title,                        Title = "New PRS Notification: ",                        ReturningData = shell.EntityID.ToString() + "$" + shell.EntityType,                        NotificationId = count,                    };                    count++;                    NotificationImage img = new NotificationImage();                    img.ResourceName = "icon16.png";                    notification.Image = img;                    await LocalNotificationCenter.Current.Show(notification);                    //if (Device.RuntimePlatform.Equals(Device.iOS))                    //{                    //    var content = new UNMutableNotificationContent();                    //    content.Title = "New PRS Notification: ";                    //    content.Subtitle = shell.Title;                    //    content.Body = "";                    //    content.Badge = 1;                    //    var trigger = UNTimeIntervalNotificationTrigger.CreateTrigger(1, false);                    //    var requestID = "request";                    //    var request = UNNotificationRequest.FromIdentifier(requestID, content, trigger);                    //    UNUserNotificationCenter.Current.AddNotificationRequest(request, (err) =>                    //    {                    //        if (err != null)                    //        {                    //            Do something with error...                    //        }                    //    });                    //}                }                Application.Current.Properties["LastPushedNotifications"] = DateTime.Now;            }            catch { }        }        private void StartMidnightTimeSheetTimer()        {            midnightTimerOn = true;            int msUntilMidnight = (int)(oneSecondBeforeMidnight - DateTime.Now).TotalMilliseconds;            Timer midnightTimer = new Timer(MidnightTimerCallback, null, msUntilMidnight, Timeout.Infinite);        }        private void MidnightTimerCallback(object o)        {            try            {                //if (bSharedDevice)                //    return;                if (midnightTimerOn)                {                    if (clockOnButton.Text == "CLOCK OFF")                    {                        InABox.Core.Location here = new InABox.Core.Location()                        {                            Latitude = App.GPS.Latitude,                            Longitude = App.GPS.Longitude,                            Timestamp = DateTime.Now                        };                        TimeSheet timesheet = App.Data.TimeSheets?.Rows.FirstOrDefault()?.ToObject<TimeSheet>();                        if (timesheet != null)                        {                            if (timesheet.ID != Guid.Empty)                            {                                if (ZeroLengthTimesheet())                                {                                    bUpdatingTimesheet = true;                                    new Client<TimeSheet>().Delete(timesheet, "Deleted due to zero duration timesheet");                                    App.Data.TimeSheets.Rows.Clear();                                }                                else                                {                                    timesheet.Finish = new TimeSpan(23, 59, 59);                                    timesheet.FinishLocation = here;                                    bUpdatingTimesheet = true;                                    new Client<TimeSheet>().Save(timesheet, "Auto Close timesheet at Midnight");                                    App.Data.TimeSheets.Rows.Clear();                                    Guid jobid = Guid.Empty;                                    String jobnumber = "";                                    String jobname = "";                                    if (!App.Data.CanBypassGates)                                    {                                        CoreRow row = App.Data.Gates.Rows.FirstOrDefault(r => App.Bluetooth.Devices.Contains(r.Get<JobTracker, String>(c => c.TrackerLink.DeviceID)));                                        if (row != null)                                        {                                            jobid = row.Get<JobTracker, Guid>(x => x.JobLink.ID);                                            jobnumber = row.Get<JobTracker, String>(x => x.JobLink.JobNumber);                                            jobname = row.Get<JobTracker, String>(x => x.JobLink.Name);                                        }                                        CreateTimeSheet(jobid, jobnumber, jobname, App.Data.Employee.UsualActivity.ID, App.Data.Employee.UsualActivity.Code, App.Data.Employee.UsualActivity.Description, here, App.GPS.Address, "Clocking On");                                    }                                    else                                    {                                        if ((!App.GPS.Latitude.Equals(0.0F)) && (!App.GPS.Longitude.Equals(0.0F)))                                        {                                            ChooseNearbyJob(here);                                        }                                    }                                }                            }                        }                    }                }            }            catch { }        }        private void FinishTimeSheet(TimeSheet timesheet, InABox.Core.Location here)        {            try            {                TimeSpan tod = DateTime.Now - DateTime.Today;                timesheet.Finish = new TimeSpan(tod.Hours, tod.Minutes, 0);                timesheet.FinishLocation = here;                bUpdatingTimesheet = true;                new Client<TimeSheet>().Save(timesheet, "Clocking Off");                App.Data.TimeSheets.Rows.Clear();                midnightTimerOn = false;                Timer last60Seconds = new Timer(Last60SecondsTimerCallBack, null, 5000, Timeout.Infinite);                clockedOffInLast5Seconds = true;            }            catch { }        }        private void Last60SecondsTimerCallBack(object o)        {            clockedOffInLast5Seconds = false;        }        private async void ChooseNearbyJob(InABox.Core.Location here)        {            try            {                JobShell selectedJob = new JobShell();                Dictionary<string, JobShell> nearbyJobs = new Dictionary<string, JobShell>();                foreach (CoreRow row in App.Data.Jobs.Rows)                {                    InABox.Core.Location jobLocation = new InABox.Core.Location() { Latitude = row.Get<Job, double>(X => X.SiteAddress.Location.Latitude), Longitude = row.Get<Job, double>(X => X.SiteAddress.Location.Longitude) };                    double distance = here.DistanceTo(jobLocation, UnitOfLength.Kilometers);                    if (distance < 1.0F)                    {                        JobShell jobShell = new JobShell();                        jobShell.ID = row.Get<Job, Guid>(X => X.ID);                        jobShell.JobNumber = row.Get<Job, String>(x => x.JobNumber);                        jobShell.Name = row.Get<Job, String>(x => x.Name);                        jobShell.DisplayName = jobShell.JobNumber + " " + jobShell.Name;                        nearbyJobs.Add(jobShell.DisplayName, jobShell);                    }                }                if (nearbyJobs.Count > 1)                {                    string[] array = nearbyJobs.Keys.ToArray();                    string chosenOption = await DisplayActionSheet("Choose job site", "Cancel", null, array);                    if (string.IsNullOrEmpty(chosenOption) || chosenOption.Equals("Cancel"))                    {                        CreateTimeSheet(selectedJob.ID, selectedJob.JobNumber, selectedJob.Name, App.Data.Employee.UsualActivity.ID, App.Data.Employee.UsualActivity.Code, App.Data.Employee.UsualActivity.Description, here, App.GPS.Address, "Clocking On");                        return;                    }                    else                    {                        selectedJob = nearbyJobs[chosenOption];                    }                }                else if (nearbyJobs.Count == 1)                {                    selectedJob = nearbyJobs.Values.First();                }                CreateTimeSheet(selectedJob.ID, selectedJob.JobNumber, selectedJob.Name, App.Data.Employee.UsualActivity.ID, App.Data.Employee.UsualActivity.Code, App.Data.Employee.UsualActivity.Description, here, App.GPS.Address, "Clocking On");            }            catch { }        }        void AddNote_Tapped(System.Object sender, System.EventArgs e)        {            try            {                TimeSheet timesheet = App.Data.TimeSheets?.Rows.FirstOrDefault()?.ToObject<TimeSheet>();                if (timesheet == null)                    return;                var notepage = new NotePage(timesheet);                Navigation.PushAsync(notepage);            }            catch { }        }        private void JobBtn_Tapped(object sender, EventArgs e)        {            try            {                JobSelectionPage jobSelectionPage = new JobSelectionPage();                jobSelectionPage.OnItemSelected += (() =>                {                    _job.ID = jobSelectionPage.Job.ID;                    _job.JobNumber = jobSelectionPage.Job.JobNumber;                    _job.Name = jobSelectionPage.Job.Name;                    JobPage_OnItemSelected(jobSelectionPage.Job);                });                Navigation.PushAsync(jobSelectionPage);            }            catch { }        }        private void JobPage_OnItemSelected(JobShell job)        {            try            {                TimeSheet timesheet = App.Data.TimeSheets?.Rows.FirstOrDefault()?.ToObject<TimeSheet>();                if (timesheet == null)                    return;                String auditmessage = String.Format("Changed Selected Job to: {0}: {1}", timesheet.JobLink.JobNumber, timesheet.JobLink.Name);                if (ZeroLengthTimesheet())                {                    timesheet.JobLink.ID = job.ID;                    timesheet.JobLink.JobNumber = job.JobNumber;                    timesheet.JobLink.Name = job.Name;                    bUpdatingTimesheet = true;                    new Client<TimeSheet>().Save(timesheet, auditmessage);                    Device.BeginInvokeOnMainThread(() =>                    {                        if (timesheet.JobLink.ID != Guid.Empty)                        {                            jobBtn.Text = "(" + timesheet.JobLink.JobNumber + ") " + timesheet.JobLink.Name;                        }                        else                        {                            jobBtn.Text = "No Job Selected";                        }                    });                }                else                {                    Guid activityid = timesheet.ActivityLink.ID;                    String activitycode = timesheet.ActivityLink.Code;                    String activitydescription = timesheet.ActivityLink.Description;                    InABox.Core.Location here = new InABox.Core.Location()                    {                        Latitude = App.GPS.Latitude,                        Longitude = App.GPS.Longitude,                        Timestamp = DateTime.Now                    };                    TimeSpan tod = DateTime.Now - DateTime.Today;                    timesheet.Finish = new TimeSpan(tod.Hours, tod.Minutes, 0);                    timesheet.FinishLocation = here;                    new Client<TimeSheet>().Save(timesheet, "Changing Job");                    CreateTimeSheet(                        job.ID,                        job.JobNumber,                        job.Name,                        activityid,                        activitycode,                        activitydescription,                        here,                        App.GPS.Address,                        auditmessage                    );                }                RefreshScreen();            }            catch { }        }        private bool CheckTimeSheetAgainstGates(TimeSheet timesheet)        {            DateTime now = DateTime.Now;            //var timesheet = CurrentTimeSheet();            //Can't confirm if there is no timesheet            if (timesheet == null)                return false;            // Can't confirm if there are no devices            if (App.Bluetooth.Devices.Length == 0)                return false;            if (App.Data.Gates == null)                return false;            long tsTicks = timesheet.Date.Add(timesheet.Start).Ticks;            long btTicks = App.Bluetooth.TimeStamp.Ticks;            if (Math.Abs(tsTicks - btTicks) > new TimeSpan(0, 2, 0).Ticks)                return false;            CoreRow firstgate = null;            List<String> gates = new List<string>();            // Scan every located d            foreach (var device in App.Bluetooth.Devices)            {                CoreRow gate = App.Data.Gates?.Rows.FirstOrDefault(r => r.Get<JobTracker, String>(c => c.TrackerLink.DeviceID) == device);                if (gate != null)                {                    if ((gate.Get<JobTracker, bool>(x => x.IsJobSite) == true) && (firstgate == null))                        firstgate = gate;                    gates.Add(gate.Get<JobTracker, String>(x => x.Gate));                }            }            if (gates.Any())            {                timesheet.Gate = String.Join(", ", gates.OrderBy(x => x));                if (firstgate != null)                {                    timesheet.JobLink.ID = firstgate.Get<JobTracker, Guid>(x => x.JobLink.ID);                    timesheet.JobLink.JobNumber = firstgate.Get<JobTracker, String>(x => x.JobLink.JobNumber);                    timesheet.JobLink.Name = firstgate.Get<JobTracker, String>(x => x.JobLink.Name);                }                return true;                //new Client<TimeSheet>().Save(timesheet, "Confirmed Gate Entry by Bluetooth Tracker", (o, e) => { });            }            return false;        }        private bool ZeroLengthTimesheet()        {            try            {                if (App.Data.TimeSheets == null)                    return true;                CoreRow row = App.Data.TimeSheets.Rows.FirstOrDefault();                if (row == null)                    return true;                String notes = row.Get<TimeSheet, String>(x => x.Notes);                if (!String.IsNullOrWhiteSpace(notes))                    return false;                DateTime date = row.Get<TimeSheet, DateTime>(x => x.Date);                TimeSpan start = row.Get<TimeSheet, TimeSpan>(x => x.Start);                if (date.Equals(DateTime.Today))                {                    TimeSpan tod = DateTime.Now - DateTime.Today;                    var diff = (tod - start).TotalSeconds;                    if (Math.Abs(diff) < 120.0F)                        return true;                }            }            catch { }            return false;        }        private async void CreateTimeSheet(Guid jobid, string jobnumber, String jobname, Guid activityid, String activitycode, String activitydescription, InABox.Core.Location location, String address, String auditmessage)        {            try            {                var timesheet = new TimeSheet();                using (await MaterialDialog.Instance.LoadingDialogAsync(message: "Loading"))                {                    timesheet.EmployeeID = App.Data.Employee.ID;                    timesheet.EmployeeLink.ID = App.Data.Employee.ID;                    timesheet.Date = DateTime.Today;                    TimeSpan tod = DateTime.Now - DateTime.Today;                    tod = new TimeSpan(tod.Hours, tod.Minutes, 0);                    timesheet.Start = tod;                    timesheet.StartLocation = location;                    timesheet.JobLink.ID = jobid;                    timesheet.JobLink.JobNumber = jobnumber;                    timesheet.JobLink.Name = jobname;                    timesheet.ActivityLink.ID = activityid;                    timesheet.ActivityLink.Code = activitycode;                    timesheet.ActivityLink.Description = activitydescription;                    timesheet.Address = address;                    timesheet.SoftwareVersion = MobileUtils.AppVersion.InstalledVersionNumber + GlobalVariables.DeviceString;                    //if (ClientFactory.IsAllowed<AllowTimeSheetRollover>()) CheckTimeSheetAgainstGates(timesheet);                    bUpdatingTimesheet = true;                    new Client<TimeSheet>().Save(timesheet, auditmessage);                    if (timesheet.ID == Guid.Empty)                    {                        DisplayAlert("Error creating new timesheet", "Please check your connection and try again", "OK");                        return;                    }                    StartMidnightTimeSheetTimer();                    // Don't Save Completed Timesheets!                    App.Data.TimeSheets.Rows.Clear();                    if (timesheet.Finish.Ticks == 0L)                    {                        CoreRow row = App.Data.TimeSheets.NewRow();                        App.Data.TimeSheets.LoadRow(row, timesheet);                        App.Data.TimeSheets.Rows.Add(row);                    }                }                Device.BeginInvokeOnMainThread(() =>                {                    if (timesheet.JobLink.ID != Guid.Empty)                    {                        jobBtn.Text = "(" + timesheet.JobLink.JobNumber + ") " + timesheet.JobLink.Name;                    }                    else                    {                        jobBtn.Text = "No Job Selected";                    }                });            }            catch { }        }        private bool CheckLocation()        {            try            {                if (App.Data.CanBypassGates)                {                    if (App.GPS.TimeStamp > DateTime.Now.Subtract(new TimeSpan(0, 5, 0)))                        return true;                    else                        return false;                }                if (App.Data.Gates == null)                    return false;                if (App.Bluetooth.TimeStamp < DateTime.Now.Subtract(new TimeSpan(0, 2, 0)))                    return false;                if (!App.Bluetooth.Devices.Any())                    return false;                return App.Data.Gates.Rows.Any(r => App.Bluetooth.Devices.Contains(r.Get<JobTracker, String>(c => c.TrackerLink.DeviceID)));            }            catch            {                return true;            }        }        private String DisplayAddress()        {            try            {                bool PRSReady = App.Data.Employee != null; // && (TimeSheet != null); // && (Activities != null);                if (!PRSReady)                    return "Retrieving Data";                if (App.Data.CanBypassGates)                {                    if (App.GPS.TimeStamp < DateTime.Now.Subtract(new TimeSpan(0, 5, 0)))                    {                        App.GPS.GetLocation(true);                        return "Searching for GPS";                    }                    else                        return App.GPS.Address;                }                else                {                    // Hmm.. this can/should be simplified                    // if in range of a gate                    //    Show Gate Description                    // else                    //    "Looking for Gate"                    if ((App.Data.Gates != null) && (App.Bluetooth.TimeStamp > DateTime.Now.Subtract(new TimeSpan(0, 2, 0))))                    {                        CoreRow row = App.Data.Gates.Rows.FirstOrDefault(r => App.Bluetooth.Devices.Contains(r.Get<JobTracker, String>(c => c.TrackerLink.DeviceID)));                        if (row != null)                            return row.Get<JobTracker, String>(x => x.Gate);                        //else if ((CurrentTimeSheet() != null) && (!GPS.TimeStamp.IsEmpty()))                        //    return GPS.Address;                        else                            return "Looking for Gate";                    }                    //else if ((CurrentTimeSheet() != null) && (GPS.TimeStamp > DateTime.Now.Subtract(new TimeSpan(0, 2, 0))))                    //    return GPS.Address;                    else                        return "Looking for Gate";                }            }            catch            {                return "Address error";            }        }        #region Background Loading        private void LoadCacheLists()        {            GlobalVariables.ProductsLoaded = false;            GlobalVariables.JobsLoaded = false;            GlobalVariables.GetXamarinWidth();            LoadJobShells();            LoadEmployeeShells();            LoadProducts();            LoadCompanyDevices();            LoadBlueToothAddresses();            //LoadHRToDos(); to be uncommented when ready for roll out        }        private void LoadCompanyDevices()        {            Task.Run(() =>            {                if (!string.IsNullOrWhiteSpace(deviceName) && deviceName != "unknown")                {                    List<Equipment> companyDevices = new List<Equipment>();                    CoreTable table = new Client<Equipment>().Query                    (                        new Filter<Equipment>(x => x.GroupLink.Code).IsEqualTo("DEVICE"),                        new Columns<Equipment>(                            x => x.TrackerLink.DeviceID                            )                        );                    if (table.Rows.Any())                    {                        foreach (CoreRow row in table.Rows)                        {                            List<object> list = row.Values;                            if (list[0].ToString().Equals(deviceName))                            {                                matchedDeviceName = deviceName;                            }                        }                    }                }            });        }        private async void LoadEmployeeShells()        {            await Task.Run(() =>            {                List<EmployeeShell> employeeShells = new List<EmployeeShell>();                List<EmployeeShell> teamEmployeeShells = new List<EmployeeShell>();                MultiQuery query = new MultiQuery();                query.Add<Employee>(                    LookupFactory.DefineFilter<Employee>(),                    new Columns<Employee>(x => x.ID)                        .Add(x => x.Code)                        .Add(x => x.Name),                    LookupFactory.DefineSort<Employee>()                );                query.Add<Team>(                    LookupFactory.DefineFilter<Team>(),                    new Columns<Team>(x => x.Name),                    new SortOrder<Team>(x => x.Name)                );                query.Add<EmployeeTeam>(                    LookupFactory.DefineFilter<EmployeeTeam>(),                    new Columns<EmployeeTeam>(x => x.EmployeeLink.ID)                        .Add(x => x.EmployeeLink.Code)                        .Add(x => x.EmployeeLink.Name)                        .Add(x => x.TeamLink.Name),                    new SortOrder<EmployeeTeam>(x => x.EmployeeLink.Name)                );                query.Query();                CoreTable emps = query.Get<Employee>();                foreach (var row in emps.Rows)                {                    employeeShells.Add(                        new EmployeeShell()                        {                            ID = row.Get<Employee, Guid>(x => x.ID),                            Code = row.Get<Employee, String>(x => x.Code),                            Name = row.Get<Employee, String>(x => x.Name),                            TeamName = "All Staff"                        }                    );                }                GlobalVariables.TeamNames = query.Get<Team>().Rows.Select(r => r.Get<Team, String>(c => c.Name)).ToList();                CoreTable members = query.Get<EmployeeTeam>();                foreach (var row in members.Rows)                {                    teamEmployeeShells.Add(                        new EmployeeShell()                        {                            ID = row.Get<EmployeeTeam, Guid>(x => x.EmployeeLink.ID),                            Code = row.Get<EmployeeTeam, String>(x => x.EmployeeLink.Code),                            Name = row.Get<EmployeeTeam, String>(x => x.EmployeeLink.Name),                            TeamName = row.Get<EmployeeTeam, String>(x => x.TeamLink.Name)                        }                    );                }                GlobalVariables.EmployeeShells = employeeShells;                GlobalVariables.TeamEmployeeShells = teamEmployeeShells;            });        }        async void LoadJobShells()        {            try            {                await Task.Run(() =>                {                    List<JobShell> jobShells = new List<JobShell>();                    CoreTable table = new Client<Job>().Query(                        new Filter<Job>(x => x.JobStatus.Active).IsEqualTo(true),                        new Columns<Job>(x => x.ID, x => x.Name, x => x.JobNumber, x => x.JobStatus.Description, x => x.Color),                        new SortOrder<Job>(x => x.JobNumber)                        );                    foreach (CoreRow row in table.Rows)                    {                        List<object> list = row.Values;                        if (list[0] == null) { list[0] = Guid.Empty; } //0                        if (list[1] == null) { list[1] = ""; } //1                        if (list[2] == null) { list[2] = ""; } //2                        if (list[3] == null) { list[3] = ""; } //3                        if (list[4] == null) { list[4] = ""; } //4                        JobShell jobshell = new JobShell                        {                            ID = Guid.Parse(list[0].ToString()),                            Name = list[1].ToString(),                            JobNumber = list[2].ToString(),                            JobStatusDescription = list[3].ToString(),                            Color = Color.FromHex(list[4].ToString())                        };                        if (jobshell.JobStatusDescription.Equals("Active Projects"))                            jobshell.JobStatusDescription = "Active";                        else if (jobshell.JobStatusDescription.Equals("Projects - Hidden from View"))                            jobshell.JobStatusDescription = "Hidden";                        else if (jobshell.JobStatusDescription.Equals("Projects in Defect Liability Period"))                            jobshell.JobStatusDescription = "Defect Liability";                        jobshell.DisplayName = "(" + jobshell.JobNumber + ") " + jobshell.Name;                        jobShells.Add(jobshell);                    }                    GlobalVariables.JobShells = jobShells;                    GlobalVariables.JobShells.Insert(0, new JobShell { ID = Guid.Empty, JobNumber = "No Job", Name = "Empty Job", JobStatusDescription = "Hidden" });                    GlobalVariables.JobsLoaded = true;                });            }            catch { }        }        private async void LoadHRToDos()        {            try            {                await Task.Run(() =>                {                    Thread.Sleep(10000);                    if (GlobalVariables.UpdateHRItemsNeedingAttention())                    {                        string message = "You have HR Items needing attention. Open My HR now?";                        Device.BeginInvokeOnMainThread(async () =>                        {                            string chosenOption = await DisplayActionSheet(message, "Cancel", null, "Yes", "No");                            switch (chosenOption)                            {                                case "Cancel":                                    break;                                case "No":                                    break;                                default:                                    break;                                case "Yes":                                    MyHRHome myHRHome = new MyHRHome();                                    Navigation.PushAsync(myHRHome);                                    break;                            }                        });                    }                });            }            catch { }        }        private async void LoadProducts()        {            try            {                await Task.Run(() =>                {                    ProductsLoader productsLoader = new ProductsLoader();                    //if (ClientFactory.IsAllowed<CanViewStoresRequisitions>())                    //{                    //}                });            }            catch { }        }        private async void LoadBlueToothAddresses()        {            try            {                //if (bSharedDevice)                //    return;                await Task.Run(() =>                {                    GlobalVariables.GPSTrackerCache = new List<GPSTracker>();                    CoreTable table = new Client<GPSTracker>().Query(new Filter<GPSTracker>(x => x.Type.Description).Contains("Kontakt"));                    foreach (CoreRow row in table.Rows)                    {                        GPSTracker tracker = row.ToObject<GPSTracker>();                        GlobalVariables.GPSTrackerCache.Add(tracker);                        App.Bluetooth.KnownBlueToothMACAddresses.Add(tracker.DeviceID);                    }                });            }            catch { }        }        #endregion        #endregion        #region Modules        public async void InitToolEntryList()        {            try            {                await Task.Run(() =>                {                    //Assignments                    ToolEntry Assignments = new ToolEntry                    {                        Text = "Assignments",                        Image = "calendar"                    };                    Assignments.IsVisible = PRSSecurity.CanView<Assignment>();                    Assignments.OnTapped += ((object sender, EventArgs e) =>                    {                        var assignment_form = new AssignmentList();                        Navigation.PushAsync(assignment_form);                    });                    toolEntries.Add(Assignments);                    //Deliveries                    ToolEntry Deliveries = new ToolEntry                    {                        Text = "Deliveries",                        Image = "deliveries"                    };                    Deliveries.IsVisible = PRSSecurity.CanView<Delivery>();                    Deliveries.OnTapped += ((object sender, EventArgs e) =>                    {                        var delivery_form = new DeliveryList();                        Navigation.PushAsync(delivery_form);                    });                    toolEntries.Add(Deliveries);                    //Digital Forms                    ToolEntry Forms = new ToolEntry                    {                        Text = "Forms",                        Image = "forms"                    };                    Forms.IsVisible = PRSSecurity.CanView<DigitalForm>();                    Forms.OnTapped += ((object sender, EventArgs e) =>                    {                        var qaFormPicker = new DigitalFormsPicker();                        Navigation.PushAsync(qaFormPicker);                    });                    toolEntries.Add(Forms);                    //Equipment                    ToolEntry Equipment = new ToolEntry                    {                        Text = "Equipment",                        Image = "digger"                    };                    Equipment.IsVisible = PRSSecurity.CanView<Equipment>();                    Equipment.OnTapped += (async (object sender, EventArgs e) =>                    {                        using (await MaterialDialog.Instance.LoadingDialogAsync(message: "Loading"))                        {                            var equipment = new EquipmentModule();                            Navigation.PushAsync(equipment);                        }                    });                    toolEntries.Add(Equipment);                    //InOut                    ToolEntry InOut = new ToolEntry                    {                        Text = "In/Out",                        Image = "inout"                    };                    InOut.IsVisible = PRSSecurity.IsAllowed<CanViewInOutBoard>();                    InOut.OnTapped += ((object sender, EventArgs e) =>                    {                        var staff_form = new StaffStatusPage();                        Navigation.PushAsync(staff_form);                    });                    toolEntries.Add(InOut);                    //Manufacturing                    ToolEntry Manufacturing = new ToolEntry                    {                        Text = "Manufacturing",                        Image = "manufacturingg"                    };                    if (Device.RuntimePlatform.Equals(Device.iOS))                    {                        Manufacturing.Image = "Image";                    }                    Manufacturing.IsVisible = PRSSecurity.IsAllowed<CanViewManufacturingOnMobile>();                    Manufacturing.OnTapped += ((object sender, EventArgs e) =>                    {                        ManufacturingScreen manufacturingScreen = new ManufacturingScreen();                        Navigation.PushAsync(manufacturingScreen);                    });                    toolEntries.Add(Manufacturing);                    //My HR                    ToolEntry MyHR = new ToolEntry                    {                        Text = "My HR",                        Image = "myhr"                    };                    MyHR.OnTapped += ((object sender, EventArgs e) =>                    {                        MyHRHome myHRHome = new MyHRHome();                        Navigation.PushAsync(myHRHome);                    });                    toolEntries.Add(MyHR);                    //Notifications                    ToolEntry Notifications = new ToolEntry()                    {                        Text = "Notifications",                        Image = "notifications"                    };                    Notifications.OnTapped += (object sender, EventArgs e) =>                    {                        NotificationList notificationList = new NotificationList();                        notificationList.NotificationsClosed += (n) =>                        {                            NumberOfNotfications = n;                            RefreshOnNotificationsChange();                        };                        Navigation.PushAsync(notificationList);                    };                    toolEntries.Add(Notifications);                    ToolEntry Products = new ToolEntry()                    {                        Text = "Products",                        Image = "products"                    };                    Products.OnTapped += ((object sender, EventArgs e) =>                    {                        if (GlobalVariables.ProductsLoaded)                        {                            ProductList products = new ProductList(GlobalVariables.ProductShells);                            Navigation.PushAsync(products);                        }                        else                        {                            ProductList products = new ProductList();                            Navigation.PushAsync(products);                        }                    });                    toolEntries.Add(Products);                    //Purchase Orders                    ToolEntry PurchaseOrders = new ToolEntry()                    {                        Text = "Purchase Orders",                        Image = "shoppingcart"                    };                    PurchaseOrders.IsVisible = PRSSecurity.CanView<PurchaseOrder>();                    PurchaseOrders.OnTapped += ((object sender, EventArgs e) =>                    {                        PurchaseOrderModule page = new PurchaseOrderModule();                        Navigation.PushAsync(page);                    });                    toolEntries.Add(PurchaseOrders);                    //Scanner                    ToolEntry Scanner = new ToolEntry                    {                        Text = "Scanner",                        Image = "scanner"                    };                    Scanner.OnTapped += ((object sender, EventArgs e) =>                    {                        ScannerPage scannerPage = new ScannerPage();                        Navigation.PushAsync(scannerPage);                    });                    toolEntries.Add(Scanner);                    //Site                    ToolEntry Site = new ToolEntry                    {                        Text = "Site",                        Image = "construction"                    };                    Site.OnTapped += ((object sender, EventArgs e) =>                    {                        Site site = new Site(_job);                        Navigation.PushAsync(site);                        //if (_job.ID == Guid.Empty)                        //{                        //    JobSelectionPage jobSelectionPage = new JobSelectionPage(true);                        //    jobSelectionPage.OnItemSelected += (async () =>                        //    {                        //        if (jobSelectionPage.Job.ID != Guid.Empty)                        //        {                        //            Job selectedJob = new Job();                        //            selectedJob.ID = jobSelectionPage.Job.ID;                        //            selectedJob.JobNumber = jobSelectionPage.Job.JobNumber;                        //            selectedJob.Name = jobSelectionPage.Job.Name;                        //            Site site = new Site(selectedJob);                        //            var previousPage = Navigation.NavigationStack.LastOrDefault();                        //            await Navigation.PushAsync(site);                        //            Navigation.RemovePage(previousPage);                        //        }                        //    });                        //    Navigation.PushAsync(jobSelectionPage);                        //}                    });                    toolEntries.Add(Site);                    //Store Requis                    ToolEntry StoreRequis = new ToolEntry                    {                        Text = "Store Requis",                        Image = "storerequis"                    };                    StoreRequis.IsVisible = PRSSecurity.CanView<Requisition>();                    StoreRequis.OnTapped += ((object sender, EventArgs e) =>                    {                        var storeRequisList = new StoreRequiList();                        Navigation.PushAsync(storeRequisList);                    });                    toolEntries.Add(StoreRequis);                    //Tasks                    ToolEntry Tasks = new ToolEntry                    {                        Text = "Tasks",                        Image = "tasks"                    };                    Tasks.IsVisible = PRSSecurity.IsAllowed<CanViewTasks>();                    Tasks.OnTapped += ((object sender, EventArgs e) =>                    {                        var tasksForm = new TasksList();                        Navigation.PushAsync(tasksForm);                    });                    toolEntries.Add(Tasks);                    //Warehousing                    ToolEntry Warehousing = new ToolEntry                    {                        Text = "Warehousing",                        Image = "newwarehousing"                    };                    Warehousing.IsVisible = PRSSecurity.CanView<StockWarehouse>();                    Warehousing.OnTapped += ((object sender, EventArgs e) =>                    {                        Warehousing2 locations = new Warehousing2();                        Navigation.PushAsync(locations);                    });                    toolEntries.Add(Warehousing);                    AddChildren();                });            }            catch { }        }        private void AddChildren()        {            Device.BeginInvokeOnMainThread(() =>            {                foreach (ToolEntry toolEntry in toolEntries)                {                    toolEntry.Margin = new Thickness(5, 0, 5, 0);                    flexLayout.Children.Add(toolEntry);                }                SearchForNewNotifications();                AddBlanks();            });        }        private void AddBlanks()        {            for (int x = 0; x < 6; x++)            {                ToolEntry toolEntry = new ToolEntry(true);                toolEntry.Margin = new Thickness(5, 0, 5, 0);                flexLayout.Children.Add(toolEntry);            }        }        private void Settings_Tapped(object sender, EventArgs e)        {            try            {                Settings settingsform = new Settings();                settingsform.Disappearing += (object sender2, EventArgs e2) =>                {                    settingsform = (Settings)sender2;                    if (settingsform.SettingsChanged)                        Navigation.PopModalAsync();                };                Navigation.PushAsync(settingsform);            }            catch { }        }        #endregion    }}
 |