private void SetBatchNumber(bool regenerate) { Context mContext = Application.Context; AppPreferences applicationPreferences = new AppPreferences(mContext); if (string.IsNullOrEmpty(applicationPreferences.GetAccessKey("batchnumber")) || regenerate) { batch = Guid.NewGuid(); applicationPreferences.SaveAccessKey("batchnumber", batch.ToString()); } batchnumber = applicationPreferences.GetAccessKey("batchnumber"); }
protected override void OnCreate(Bundle savedInstanceState) { RequestedOrientation = ScreenOrientation.Portrait; Context mContext = Application.Context; AppPreferences applicationPreferences = new AppPreferences(mContext); base.OnCreate(savedInstanceState); SetContentView(Resource.Layout.activity_settings); Android.Support.V7.Widget.Toolbar toolbar = FindViewById <Android.Support.V7.Widget.Toolbar>(Resource.Id.toolbar); SetSupportActionBar(toolbar); // Load up any stored applicationPreferences TextView submitDataUrl = FindViewById <TextView>(Resource.Id.submit_data_url); submitDataUrl.Text = applicationPreferences.GetAccessKey("submitDataUrl"); submitDataUrl.Text = submitDataUrl.Text.TrimEnd('\r', '\n'); TextView loadConfigUrl = FindViewById <TextView>(Resource.Id.load_config_url); loadConfigUrl.Text = applicationPreferences.GetAccessKey("loadConfigUrl"); loadConfigUrl.Text = loadConfigUrl.Text.TrimEnd('\r', '\n'); TextView applicationKey = FindViewById <TextView>(Resource.Id.application_key); applicationKey.Text = applicationPreferences.GetAccessKey("applicationKey"); applicationKey.Text = applicationKey.Text.TrimEnd('\r', '\n'); TextView retentionPeriod = FindViewById <TextView>(Resource.Id.retention_period); retentionPeriod.Text = applicationPreferences.GetAccessKey("retentionPeriod"); retentionPeriod.Text = retentionPeriod.Text.TrimEnd('\r', '\n'); string databasePath = System.IO.Path.Combine( System.Environment.GetFolderPath(System.Environment.SpecialFolder.Personal), "localscandata.db3"); SQLiteConnection databaseConnection = new SQLiteConnection(databasePath); databaseConnection.CreateTable <DespatchBayExpressDataBase.TrackingNumberPatterns>(); PopulateRecycleView(); TrackingScan = FindViewById <EditText>(Resource.Id.txtentry); TrackingScan.Text = ""; TrackingScan.RequestFocus(); TrackingScan.KeyPress += (object sender, View.KeyEventArgs e) => { if ((e.Event.Action == KeyEventActions.Down) && (e.KeyCode == Keycode.Enter)) { if (e.Event.RepeatCount == 0) { string jsonstring = TrackingScan.Text; //jsonstring = Regex.Replace(jsonstring, @"\s+", ""); Configuration configuration = new Configuration(); try { configuration = JsonConvert.DeserializeObject <Configuration>(jsonstring); if (configuration.UpdateConfiguration.Count == 1) { foreach (UpdateConfiguration configItem in configuration.UpdateConfiguration) { submitDataUrl.Text = configItem.UploadEndPoint.ToString(); loadConfigUrl.Text = configItem.RegexEndPoint.ToString(); applicationKey.Text = configItem.ApplicationKey.ToString(); retentionPeriod.Text = configItem.RetentionPeriod.ToString(); } // Save some application preferences applicationPreferences.SaveAccessKey("submitDataUrl", submitDataUrl.Text, true); applicationPreferences.SaveAccessKey("loadConfigUrl", loadConfigUrl.Text, true); applicationPreferences.SaveAccessKey("applicationKey", applicationKey.Text, true); applicationPreferences.SaveAccessKey("retentionPeriod", retentionPeriod.Text, true); try { applicationPreferences.SaveAccessKey("serialNumber", Android.OS.Build.Serial.ToString(), true); } catch { applicationPreferences.SaveAccessKey("serialNumber", "", true); } Log.Info("TAG-SETTINGS", "Settings - Call FetchTrackingRegExData"); System.Threading.Tasks.Task taskA = System.Threading.Tasks.Task.Factory.StartNew(() => FetchTrackingRegExData(loadConfigUrl.Text)); taskA.Wait(); Toast.MakeText(this, "Config QR code read successful", ToastLength.Long).Show(); } } catch (Exception ex) { // Any Error in the above block will cause this catch to fire - Even if the json keys don't exist Toast.MakeText(this, "Config QR code not recognised", ToastLength.Long).Show(); } PopulateRecycleView(); TrackingScan.Text = ""; } } }; }
protected override void OnCreate(Bundle savedInstanceState) { RequestedOrientation = ScreenOrientation.Portrait; Context applicationContext = Application.Context; AppPreferences applicationPreferences = new AppPreferences(applicationContext); // Check application Preferences have been saved previously if not open Settings Activity and wait there. if ( string.IsNullOrEmpty(applicationPreferences.GetAccessKey("submitDataUrl")) || string.IsNullOrEmpty(applicationPreferences.GetAccessKey("loadConfigUrl")) || string.IsNullOrEmpty(applicationPreferences.GetAccessKey("applicationKey")) || string.IsNullOrEmpty(applicationPreferences.GetAccessKey("retentionPeriod")) ) { // No, well start the setting activity StartActivity(typeof(SettingsActivity)); } base.OnCreate(savedInstanceState); SetContentView(Resource.Layout.activity_main); Android.Support.V7.Widget.Toolbar toolbar = FindViewById <Android.Support.V7.Widget.Toolbar>(Resource.Id.toolbar); SetSupportActionBar(toolbar); // We only want to create a batch number here once when the app first starts and not everytime the activity loads if (batch == Guid.Empty) { SetBatchNumber(false); } databasePath = System.IO.Path.Combine( System.Environment.GetFolderPath(System.Environment.SpecialFolder.Personal), "localscandata.db3"); databaseConnection = new SQLiteConnection(databasePath); // Create the ParcelScans table databaseConnection.CreateTable <DespatchBayExpressDataBase.ParcelScans>(); if (ContextCompat.CheckSelfPermission(this, Manifest.Permission.AccessFineLocation) == (int)Permission.Granted) { mediaPlayer = MediaPlayer.Create(this, Resource.Raw.beep_07); TrackingNumberDataProvider(); // We have permission, go ahead and use the GPS. Log.Debug("GPS", "We have permission, go ahead and use the GPS."); InitializeLocationManager(); coordinates = FindViewById <TextView>(Resource.Id.footer_text); TrackingScan = FindViewById <EditText>(Resource.Id.txtentry); TrackingScan.Text = ""; TrackingScan.RequestFocus(); TrackingScan.KeyPress += (object sender, View.KeyEventArgs e) => { if ((e.Event.Action == KeyEventActions.Down) && (e.KeyCode == Keycode.Enter)) { if (e.Event.RepeatCount == 0) { /// need to regex the scan against the Tracking Patterns /// TableQuery <TrackingNumberPatterns> trackingPatterns = databaseConnection.Table <TrackingNumberPatterns>(); bool patternFound = false; try { foreach (var trackingPattern in trackingPatterns) { Match m = Regex.Match(@TrackingScan.Text, @trackingPattern.Pattern, RegexOptions.IgnoreCase); if (m.Success) { patternFound = true; } } } catch { } if (patternFound) { var newScan = new DespatchBayExpressDataBase.ParcelScans { TrackingNumber = TrackingScan.Text.ToUpper(), ScanTime = DateTime.Now.ToString("yyyy-MM-ddTHH:mm:ss"), Batch = batchnumber, Sent = null }; try { newScan.Longitude = currentLocation.Longitude; } catch { newScan.Longitude = null; } try { newScan.Latitude = currentLocation.Latitude; } catch { newScan.Latitude = null; } try { databaseConnection.Insert(newScan); mBarcodeScannerList.FetchUnCollected(); mAdapter.NotifyDataSetChanged(); mRecyclerView.RefreshDrawableState(); mediaPlayer.Start(); } catch (SQLiteException ex) { Toast.MakeText(this, "Scan Error : Duplicated Barcode Scan", ToastLength.Long).Show(); Log.Info("SCANNER", "Scan Error : " + ex.Message); } } else { Toast.MakeText(this, "Barcode format not recognised", ToastLength.Short).Show(); } TrackingScan.RequestFocus(); TrackingScan.Text = ""; } } }; } else { // GPS permission is not granted. If necessary display rationale & request. Log.Debug("GPS", "GPS permission is not granted"); if (ActivityCompat.ShouldShowRequestPermissionRationale(this, Manifest.Permission.AccessFineLocation)) { // Provide an additional rationale to the user if the permission was not granted // and the user would benefit from additional context for the use of the permission. // For example if the user has previously denied the permission. Log.Info("GPS", "Displaying GPS permission rationale to provide additional context."); var rootView = FindViewById <CoordinatorLayout>(Resource.Id.root_view); var requiredPermissions = new String[] { Manifest.Permission.AccessFineLocation }; ActivityCompat.RequestPermissions(this, requiredPermissions, REQUEST_LOCATION); } else { ActivityCompat.RequestPermissions(this, new String[] { Manifest.Permission.AccessFineLocation }, REQUEST_LOCATION); } } }
/// <summary> /// Menu options /// </summary> /// <param name="item"></param> /// <returns></returns> public override bool OnOptionsItemSelected(IMenuItem item) { switch (item.ItemId) { case Resource.Id.menu_location: Toast.MakeText(this, "Not implemented", ToastLength.Short).Show(); break; case Resource.Id.menu_settings: StartActivity(typeof(SettingsActivity)); break; case Resource.Id.menu_about: StartActivity(typeof(AboutActivity)); break; case Resource.Id.menu_sqldata: StartActivity(typeof(SqliteActivity)); break; case Resource.Id.menu_exportdata: ExportScanData(); break; case Resource.Id.menu_exit: // This should exit the app this.FinishAffinity(); break; case Resource.Id.menu_upload: // Begin the process of uploading the data Context mContext = Application.Context; AppPreferences ap = new AppPreferences(mContext); string httpEndPoint = ap.GetAccessKey("submitDataUrl"); string loadConfigUrl = ap.GetAccessKey("loadConfigUrl"); string applicationKey = ap.GetAccessKey("applicationKey"); string retentionPeriod = ap.GetAccessKey("retentionPeriod"); // Create a Dictionary for the parameters Dictionary <string, string> Parameters = new Dictionary <string, string> { { "httpEndPoint", httpEndPoint }, { "userAgent", "Man-In-VAN Handheld Device" }, { "token", applicationKey }, { "retentionPeriod", retentionPeriod }, }; try { Parameters.Add("serialNumber", ap.GetAccessKey("serialNumber")); } catch { Parameters.Add("serialNumber", ""); } try { Parameters.Add("lontitude", currentLocation.Longitude.ToString()); Parameters.Add("latitude", currentLocation.Latitude.ToString()); } catch { Parameters.Add("lontitude", ""); Parameters.Add("latitude", ""); } Parameters.Add("databasePath", databasePath); bool status = false; try { // Run the SubmitCollectionData as a Async Task System.Threading.Tasks.Task taskA = System.Threading.Tasks.Task.Factory.StartNew(() => status = SubmitCollectionData(Parameters)); taskA.Wait(); } catch (Exception ex) { Log.Info("SubmitCollectionData", ex.Message); } if (status == false) { Toast.MakeText(this, "There was a problem with the upload", ToastLength.Long).Show(); // Instantiate the builder and set notification elements: Notification.Builder builder = null; try { builder = new Notification.Builder(this, "NOTI_CH_ID"); } catch { builder = new Notification.Builder(this); } builder.SetContentTitle("Failed Uploads"); builder.SetContentText("There are uploads that may have failed."); builder.SetSmallIcon(Resource.Mipmap.ic_warning_black_24dp); // Build the notification: Notification notification = builder.Build(); // Get the notification manager: NotificationManager notificationManager = GetSystemService(Context.NotificationService) as NotificationManager; const int notificationId = 0; notificationManager.Notify(notificationId, notification); } else { Toast.MakeText(this, "Upload complete", ToastLength.Long).Show(); } TrackingNumberDataProvider(); // Create a new Batch number; SetBatchNumber(true); break; case Resource.Id.menu_sqldatadelete: databaseConnection.DeleteAll <DespatchBayExpressDataBase.ParcelScans>(); TrackingNumberDataProvider(); break; } return(base.OnOptionsItemSelected(item)); }