| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836 | 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;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    }}
 |