public ComingIn(string Lat, string Long, string DeviceId, string LocAddress, string distanceFromOrigin) : base() { this.Latitude = Lat; this.Longitude = Long; this.UniqueDeviceID = DeviceId; this.LocationAddress = LocAddress; this.distanceFromOrigin = distanceFromOrigin; BackgroundColor = ColorResources.PageBackgroundColor; zxing = new ZXingScannerView { HorizontalOptions = LayoutOptions.FillAndExpand, VerticalOptions = LayoutOptions.FillAndExpand }; zxing.OnScanResult += (result) => { zxing.IsAnalyzing = false;// Stop analysis until we navigate away so we don't keep reading barcodes Device.BeginInvokeOnMainThread(async() => { if (result.Text == "nWorks Technologies (India) Pvt. Ltd., 206 Garden Plaza, Rahatani, Pune, Maharashtra, 411 017, INDIA") { comingIn_goingOut obj = new comingIn_goingOut(); try { //get geolocation obj.empId = ColorResources.LIVE_USER_ID; obj.qrValue = result.Text; obj.DeviceID = this.UniqueDeviceID; obj.latitude = this.Latitude; obj.longitude = this.Longitude; obj.Location = this.LocationAddress; obj.distanceFromOrigin = this.distanceFromOrigin; await this.Navigation.PopAsync(); zxing.IsScanning = false; var json = JsonConvert.SerializeObject(obj); var content = new StringContent(json, Encoding.UTF8, "application/json"); HttpClient Client = new HttpClient(); HttpResponseMessage response = null; response = await Client.PostAsync(ColorResources.baseUrl + "comingIn", content); if (response.IsSuccessStatusCode) { var responseContent = await response.Content.ReadAsStringAsync(); var res = JsonConvert.DeserializeObject <string>(responseContent); await DisplayAlert(" nWorksLeaveApp", res.ToString(), "OK"); } } catch (Exception exc) { // await DisplayAlert(" nWorksLeaveApp",exc.ToString(),"OK"); Debug.WriteLine(exc.ToString()); } } else { await DisplayAlert(" nWorksLeaveApp", "Invalid QR Code!", "OK"); } }); }; overlay = new ZXingDefaultOverlay { TopText = "Hold your phone up to the barcode", BottomText = "Scanning will happen automatically", ShowFlashButton = zxing.HasTorch, }; overlay.FlashButtonClicked += (sender, e) => { zxing.IsTorchOn = !zxing.IsTorchOn; }; var grid = new Grid { VerticalOptions = LayoutOptions.FillAndExpand, HorizontalOptions = LayoutOptions.FillAndExpand, HeightRequest = 500, }; grid.Children.Add(zxing); grid.Children.Add(overlay); Content = new StackLayout { Padding = new Thickness(0, 15, 0, 10), VerticalOptions = LayoutOptions.Center, Children = { new Label { Text = "I am coming...", TextColor = Color.Red, FontSize = 25, VerticalOptions = LayoutOptions.StartAndExpand, HorizontalOptions = LayoutOptions.Center, }, grid } }; }
public CustomScannerPage() : base() { zxing = new ZXingScannerView { HorizontalOptions = LayoutOptions.FillAndExpand, VerticalOptions = LayoutOptions.FillAndExpand }; zxing.OnScanResult += (result) => Device.BeginInvokeOnMainThread(() => { // Stop analysis until we navigate away so we don't keep reading barcodes zxing.IsAnalyzing = false; OnUpcResultEvent(result.Text); }); overlay = new ZXingDefaultOverlay { TopText = "Hold your phone up to the barcode", BottomText = "Scanning will happen automatically", ShowFlashButton = zxing.HasTorch, }; overlay.FlashButtonClicked += (sender, e) => { zxing.IsTorchOn = !zxing.IsTorchOn; }; var grid = new Grid { VerticalOptions = LayoutOptions.FillAndExpand, HorizontalOptions = LayoutOptions.FillAndExpand, }; grid.Children.Add(zxing); grid.Children.Add(overlay); var upcEntry = new Entry { Placeholder = "UPC", HorizontalOptions = LayoutOptions.FillAndExpand }; upcEntry.Completed += (sender, e) => Device.BeginInvokeOnMainThread(() => { zxing.IsAnalyzing = false; zxing.IsScanning = false; zxing.IsEnabled = false; OnUpcResultEvent(((Entry)sender).Text); }); var endButton = new Button { Text = "Enter", HorizontalOptions = LayoutOptions.End }; endButton.Clicked += (sender, e) => Device.BeginInvokeOnMainThread(() => { zxing.IsAnalyzing = false; zxing.IsScanning = false; zxing.IsEnabled = false; OnUpcResultEvent(upcEntry.Text); }); var brewerEntry = new Entry { Placeholder = "Brewery Name", HorizontalOptions = LayoutOptions.FillAndExpand, Text = "Left Hand Brewing Company" }; var beerEntry = new Entry { Placeholder = "Beer Name", HorizontalOptions = LayoutOptions.FillAndExpand, Text = "Milk Stout Nitro" }; var manualEndButton = new Button { Text = "Enter", HorizontalOptions = LayoutOptions.End }; manualEndButton.Clicked += (sender, e) => Device.BeginInvokeOnMainThread(() => { zxing.IsAnalyzing = false; zxing.IsScanning = false; zxing.IsEnabled = false; OnManualResultEvent(brewerEntry.Text + "|" + beerEntry.Text); }); var content = new StackLayout { Children = { grid, new StackLayout { Margin = new Thickness(20, 20, 20, 5), Children = { new Label { Text = "Or, manually enter your UPC",FontSize = 20 }, new StackLayout { Orientation = StackOrientation.Horizontal, Children = { upcEntry, endButton } } } }, new StackLayout { Margin = new Thickness(20, 0, 20, 20), Children = { new Label { Text = "Or even just lookup manually by name!",FontSize = 20 }, new StackLayout { Orientation = StackOrientation.Horizontal, Children = { brewerEntry, beerEntry, manualEndButton } } } } } }; Content = content; }
//public string localHostUrl = "http://192.168.0.174:8080/PSM2017/"; public ScanPage() { zxings = new ZXingScannerView { HorizontalOptions = LayoutOptions.FillAndExpand, VerticalOptions = LayoutOptions.FillAndExpand, AutomationId = "zxingScannerView", IsScanning = true }; zxings.OnScanResult += (result) => Device.BeginInvokeOnMainThread(async() => { zxings.IsAnalyzing = false; string barcode = result.Text; if (App.Database.GetProducts().Count < 10) { string data = ""; string postData = "barcode=" + barcode; string url = localHostUrl + "dbGetProduct.php"; WebService searchProduct = new WebService(); data = searchProduct.postService(postData, url); if (data.Contains("{")) { Product product = JsonConvert.DeserializeObject <Product>(data); //Product product = products.Find(x => x.barcode == Int32.Parse(barcode)); App.Database.AddProduct(product); await DisplayAlert("Item Added", product.name + " added into list.", "OK"); } else { XFToast.LongMessage(data); } } else { await DisplayAlert("Alert!", "Your cart has 10 items. The cart could only hold up to 10 items. " + "Please pay for the item(s) or delete item!!!", "OK"); } // Stop analysis until we navigate away so we don't keep reading barcodes zxings.IsAnalyzing = true; // Show an alert //await DisplayAlert("Scanned Barcode", result.Text, "OK"); // Navigate away //await Navigation.PopAsync(); }); var scanOverlay = new RelativeLayout { HorizontalOptions = LayoutOptions.FillAndExpand, VerticalOptions = LayoutOptions.FillAndExpand }; Xamarin.Forms.Label text = new Xamarin.Forms.Label { Text = "Hold your phone up to the barcode", VerticalOptions = LayoutOptions.Center, HorizontalOptions = LayoutOptions.Center, TextColor = Color.White }; Xamarin.Forms.Label text2 = new Xamarin.Forms.Label { Text = "Scanning will happen automatically", VerticalOptions = LayoutOptions.Center, HorizontalOptions = LayoutOptions.Center, TextColor = Color.White }; BoxView redLine = new BoxView { BackgroundColor = Color.Red, Opacity = 0.6 }; BoxView boxView = new BoxView { BackgroundColor = Color.Black, Opacity = 0.7 }; BoxView boxView2 = new BoxView { BackgroundColor = Color.Black, Opacity = 0.7 }; BoxView boxView3 = new BoxView { BackgroundColor = Color.Black, Opacity = 0.7 }; BoxView boxView4 = new BoxView { BackgroundColor = Color.Black, Opacity = 0.7 }; scanOverlay.Children.Add(boxView, Constraint.RelativeToParent((parent) => { return(parent.X); }), Constraint.RelativeToParent((parent) => { return(parent.Y); }), Constraint.RelativeToParent((parent) => { return(parent.Width * 0.1); }), Constraint.RelativeToParent((parent) => { return(parent.Height); }) ); scanOverlay.Children.Add(boxView2, Constraint.RelativeToParent((parent) => { return(parent.Width * 0.9); }), Constraint.RelativeToParent((parent) => { return(parent.Y); }), Constraint.RelativeToParent((parent) => { return(parent.Width * 0.1); }), Constraint.RelativeToParent((parent) => { return(parent.Height); }) ); scanOverlay.Children.Add(boxView3, Constraint.RelativeToParent((parent) => { return(parent.Width * 0.1); }), Constraint.RelativeToParent((parent) => { return(parent.Y); }), Constraint.RelativeToParent((parent) => { return(parent.Width * 0.8); }), Constraint.RelativeToParent((parent) => { return(parent.Height * 0.2); }) ); scanOverlay.Children.Add(boxView4, Constraint.RelativeToParent((parent) => { return(parent.Width * 0.1); }), Constraint.RelativeToParent((parent) => { return(parent.Height * 0.6); }), Constraint.RelativeToParent((parent) => { return(parent.Width * 0.8); }), Constraint.RelativeToParent((parent) => { return(parent.Height * 0.4); }) ); scanOverlay.Children.Add(redLine, Constraint.RelativeToParent((parent) => { return(parent.Width * 0.1); }), Constraint.RelativeToParent((parent) => { return(parent.Height * 0.4); }), Constraint.RelativeToParent((parent) => { return(parent.Width * 0.8); }), Constraint.RelativeToParent((parent) => { return(3); }) ); scanOverlay.Children.Add(text, Constraint.RelativeToParent((parent) => { return(parent.Width * 0.2); }), Constraint.RelativeToParent((parent) => { return(parent.Height * 0.1); }) ); scanOverlay.Children.Add(text2, Constraint.RelativeToParent((parent) => { return(parent.Width * 0.2); }), Constraint.RelativeToParent((parent) => { return(parent.Height * 0.8); }) ); defaultOverlay = new ZXingDefaultOverlay { TopText = "Hold your phone up to the barcode", BottomText = "Scanning will happen automatically", //ShowFlashButton = true, AutomationId = "zxingDefaultOverlay", }; defaultOverlay.BindingContext = defaultOverlay; var customOverlay = new RelativeLayout { HorizontalOptions = LayoutOptions.FillAndExpand, VerticalOptions = LayoutOptions.FillAndExpand }; var torchFAB = new FAB.Forms.FloatingActionButton(); torchFAB.Source = "flashlight_icon.png"; torchFAB.NormalColor = Color.FromHex("FFE066"); torchFAB.Size = FAB.Forms.FabSize.Normal; torchFAB.Clicked += (sender, args) => { zxings.ToggleTorch(); }; var listFAB = new FAB.Forms.FloatingActionButton(); listFAB.Source = "shoping_cart.png"; listFAB.NormalColor = Color.FromHex("FFE066"); listFAB.Size = FAB.Forms.FabSize.Normal; listFAB.Clicked += async(sender, args) => { //zxing.IsAnalyzing = false; //XFToast.LongMessage("Hello"); await Navigation.PushAsync(new ListViewProduct()); }; var addFAB = new FAB.Forms.FloatingActionButton(); addFAB.Source = "plus_black_symbol.png"; addFAB.NormalColor = Color.FromHex("FFE066"); addFAB.Size = FAB.Forms.FabSize.Normal; addFAB.Clicked += async(sender, args) => { if (App.Database.GetProducts().Count < 10) { var config = new PromptConfig(); config.Title = "Manual enter product barcode"; config.InputType = InputType.Number; config.OnAction = async(result) => { if (result.Ok) { string barcode = result.Text; string postData = "barcode=" + barcode; string url = localHostUrl + "dbGetProduct.php"; WebService searchProduct = new WebService(); string data = searchProduct.postService(postData, url); if (data.Contains("{")) { Product product = JsonConvert.DeserializeObject <Product>(data); //Product product = products.Find(x => x.barcode == Int32.Parse(barcode)); App.Database.AddProduct(product); await DisplayAlert("Item Added", product.name + " added into list.", "OK"); } else { XFToast.LongMessage(data); } } zxings.IsAnalyzing = true; }; await Task.Run(() => { Device.BeginInvokeOnMainThread(() => { zxings.IsAnalyzing = false; UserDialogs.Instance.Prompt(config); }); }); } else { await DisplayAlert("Alert!", "Your cart has 10 items.The cart could only hold up to 10 items. " + "Please pay for the item(s) or delete item!!!", "OK"); } //App.Database.AddProduct(new Product {Name = "Milo", Price = 20.587, Barcode = 00001 }); }; var checkOutFAB = new FAB.Forms.FloatingActionButton(); checkOutFAB.Source = "cash_register_machine.png"; checkOutFAB.NormalColor = Color.FromHex("FFE066"); checkOutFAB.Size = FAB.Forms.FabSize.Normal; checkOutFAB.Clicked += (sender, args) => { //XFToast.LongMessage("Check out"); var products = App.Database.GetProducts(); if (products.Count > 0) { Task.Run(async() => { PayPalItem[] paypalItems = new PayPalItem[products.Count]; int i = 0; foreach (Product product in products) { PayPalItem paypalItem = new PayPalItem(product.name, 1, Convert.ToDecimal(product.price), "MYR" , product.barcode); paypalItems[i] = paypalItem; i++; } var result = await CrossPayPalManager.Current.Buy(paypalItems, new Decimal(0.0), new Decimal(0.00)); if (result.Status == PayPalStatus.Cancelled) { Debug.WriteLine("Cancelled"); } else if (result.Status == PayPalStatus.Error) { Debug.WriteLine(result.ErrorMessage); } else if (result.Status == PayPalStatus.Successful) { Debug.WriteLine(result.ServerResponse.Response.Id); var jsonArray = JsonConvert.SerializeObject(products); string jsnArray = jsonArray.ToString(); string postData = "receipt=" + jsnArray; string url = localHostUrl + "genReceipt.php"; WebService searchProduct = new WebService(); string data = searchProduct.postService(postData, url); if (data.ToLower().Contains(".pdf")) { Device.BeginInvokeOnMainThread(async() => { await DisplayAlert("Payment Success", "The payment is success!!", "OK"); App.Database.ClearList(); downloadPDF(data); await DisplayAlert("Download Success", "Receipt downloaded", "OK"); }); } } }); } else { DisplayAlert("Alert!", "There are no item in the cart list.", "OK"); } }; var receiptFAB = new FAB.Forms.FloatingActionButton(); receiptFAB.Source = "receiptIcon"; receiptFAB.NormalColor = Color.FromHex("FFE066"); receiptFAB.Size = FAB.Forms.FabSize.Normal; receiptFAB.Clicked += async(sender, args) => { await Navigation.PushAsync(new ListPDF()); }; /* * customOverlay.Children.Add( * torchFAB, * xConstraint: Constraint.RelativeToParent((parent) => { return parent.Width - 48; }), * yConstraint: Constraint.RelativeToParent((parent) => { return 8; }) * ); * * customOverlay.Children.Add( * listFAB, * Constraint.RelativeToView(torchFAB, (Parent, sibling) => { return sibling.X; }), * Constraint.RelativeToView(torchFAB, (Parent, sibling) => { return sibling.Y + 48; }) * ); * customOverlay.Children.Add( * addFAB, * Constraint.RelativeToView(listFAB, (Parent, sibling) => { return sibling.X; }), * Constraint.RelativeToView(listFAB, (Parent, sibling) => { return sibling.Y + 48; }) * ); * customOverlay.Children.Add( * checkOutFAB, * Constraint.RelativeToView(addFAB, (Parent, sibling) => { return sibling.X; }), * Constraint.RelativeToView(addFAB, (Parent, sibling) => { return sibling.Y + 48; }) * ); * customOverlay.Children.Add( * receiptFAB, * Constraint.RelativeToView(checkOutFAB, (Parent, sibling) => { return sibling.X; }), * Constraint.RelativeToView(checkOutFAB, (Parent, sibling) => { return sibling.Y + 48; }) * ); */ customOverlay.Children.Add( torchFAB, xConstraint: Constraint.RelativeToParent((parent) => { return(parent.X + 6); }), yConstraint: Constraint.RelativeToParent((parent) => { return(parent.Height * 0.6 + 24); }) ); customOverlay.Children.Add( listFAB, Constraint.RelativeToView(torchFAB, (Parent, sibling) => { return(sibling.X + 72); }), Constraint.RelativeToView(torchFAB, (Parent, sibling) => { return(sibling.Y); }) ); customOverlay.Children.Add( addFAB, Constraint.RelativeToView(listFAB, (Parent, sibling) => { return(sibling.X + 72); }), Constraint.RelativeToView(listFAB, (Parent, sibling) => { return(sibling.Y); }) ); customOverlay.Children.Add( checkOutFAB, Constraint.RelativeToView(addFAB, (Parent, sibling) => { return(sibling.X + 72); }), Constraint.RelativeToView(addFAB, (Parent, sibling) => { return(sibling.Y); }) ); customOverlay.Children.Add( receiptFAB, Constraint.RelativeToView(checkOutFAB, (Parent, sibling) => { return(sibling.X + 72); }), Constraint.RelativeToView(checkOutFAB, (Parent, sibling) => { return(sibling.Y); }) ); var grid = new Grid { VerticalOptions = LayoutOptions.FillAndExpand, HorizontalOptions = LayoutOptions.FillAndExpand, }; grid.Children.Add(zxings); //grid.Children.Add(defaultOverlay); grid.Children.Add(scanOverlay); grid.Children.Add(customOverlay); Content = grid; }
public CodeScannerPage() { InitializeComponent(); // 取得這個頁面的檢視模型(ViewModel)物件 foo本頁面的檢視模型 = this.BindingContext as CodeScannerPageViewModel; #region 指定要掃描的條碼類型 var fooMobileBarcodeScanningOptions = new MobileBarcodeScanningOptions(); fooMobileBarcodeScanningOptions.PossibleFormats = new List <ZXing.BarcodeFormat>() { BarcodeFormat.QR_CODE, BarcodeFormat.CODE_128, BarcodeFormat.CODE_39, BarcodeFormat.CODABAR }; #endregion #region 建立條碼掃描控制項 zxing = new ZXingScannerView { HorizontalOptions = LayoutOptions.FillAndExpand, VerticalOptions = LayoutOptions.FillAndExpand, AutomationId = "zxingScannerView", }; #region 設定完成條碼掃描後,要進行處理的工作 zxing.OnScanResult += (result) => Device.BeginInvokeOnMainThread(async() => { // 停止分析掃描條碼工作 zxing.IsAnalyzing = false; // 將掃描結果回傳到首頁 foo本頁面的檢視模型._eventAggregator.GetEvent <ScanResultEvent>().Publish(new ScanResultPayload { Result = result.Text, }); // 回到上一頁 await foo本頁面的檢視模型._navigationService.GoBackAsync(); }); #endregion #endregion #region 建立條碼掃描遮罩 overlay = new ZXingDefaultOverlay { ShowFlashButton = zxing.HasTorch, }; // 當按下 Flash 按鈕,就會顯示燈光,幫助更順利讀取條碼 overlay.FlashButtonClicked += (sender, e) => { zxing.IsTorchOn = !zxing.IsTorchOn; }; #endregion // 將條碼掃描與分析控制項,加入到頁面上 ScannerGrid.Children.Add(zxing); // 將遮罩加入到頁面上 ScannerGrid.Children.Add(overlay); }
void AddPageContent() { this.Title = "Scan Barcode"; zxing = new ZXingScannerView { HorizontalOptions = LayoutOptions.FillAndExpand, VerticalOptions = LayoutOptions.FillAndExpand }; zxing.OnScanResult += (result) => //Device.BeginInvokeOnMainThread(async () => { // // Stop analysis until we navigate away so we don't keep reading barcodes // zxing.IsAnalyzing = false; // // Show an alert // await DisplayAlert("Scanned Barcode", result.Text, "OK"); // // Navigate away // await Navigation.PopAsync(); //}); Device.BeginInvokeOnMainThread(async() => { // Stop analysis until we navigate away so we don't keep reading barcodes zxing.IsAnalyzing = false; //Binding data try { if (!CommonLib.checkconnection()) { RacoonAlertPopup.textmsg = "Check your internet connection."; await App.Current.MainPage.Navigation.PushPopupAsync(new RacoonAlertPopup()); return; } await App.Current.MainPage.Navigation.PushPopupAsync(new LoadPopup()); string postData = "barcode=" + result + "&userId=" + LoginDetails.userId + ""; var response = await CommonLib.BarcodeScanner(CommonLib.ws_MainUrl + "AccountApi/ScanBarcode?" + postData, ""); if (response != null && response.Status != 0) { LoadPopup.CloseAllPopup(); RacoonAlertPopup.textmsg = response.msg; await App.Current.MainPage.Navigation.PushPopupAsync(new RacoonAlertPopup()); await Navigation.PopAsync(); } else { LoadPopup.CloseAllPopup(); RacoonAlertPopup.textmsg = response.msg; await App.Current.MainPage.Navigation.PushPopupAsync(new RacoonAlertPopup()); await Navigation.PopAsync(); } } catch (Exception ex) { LoadPopup.CloseAllPopup(); await App.Current.MainPage.DisplayAlert("", ex.Message, "OK"); } finally { } // Show an alert // Navigate away }); overlay = new ZXingDefaultOverlay { TopText = "Hold your phone up to the barcode", BottomText = "Scanning will happen automatically", ShowFlashButton = zxing.HasTorch, }; overlay.FlashButtonClicked += (sender, e) => { zxing.IsTorchOn = !zxing.IsTorchOn; }; var grid = new Grid { VerticalOptions = LayoutOptions.FillAndExpand, HorizontalOptions = LayoutOptions.FillAndExpand, }; grid.Children.Add(zxing); grid.Children.Add(overlay); // The root page of your application Content = grid; }
//сканирование штрихкода public void ScanAsync() { ZXingScannerView zxing = new ZXingScannerView() { HorizontalOptions = LayoutOptions.FillAndExpand, VerticalOptions = LayoutOptions.FillAndExpand, IsAnalyzing = true, IsScanning = true, }; //промежуток между сканированием zxing.Options.DelayBetweenContinuousScans = 3000; zxing.Options.BuildMultiFormatReader(); //результат сканирования zxing.OnScanResult += (result) => { Device.BeginInvokeOnMainThread(() => { //получение места и имя БД string documentsPath = Environment.GetFolderPath(Environment.SpecialFolder.Personal); var path = Path.Combine(documentsPath, "barecode.db"); string databasePath = DependencyService.Get <ISQLite>().GetDatabasePath(path); SQLiteConnection database = new SQLiteConnection(databasePath); //проверка есть ли такой штрихкод в локальной таблице товаров var codeGoodsCount = database.Table <MapsGoods>().Where(a => a.BarCode == result.Text).Count(); //получаем количество таких штрихкодов var codeGoods = database.Table <MapsGoods>().Where(a => a.BarCode == result.Text).Select(a => a.CodeGoods).FirstOrDefault(); //получаем код товара var userName = database.Table <Users>().Select(a => a.MapsUserName).FirstOrDefault().ToString(); //получаем текущего пользователя if (userName == "" | userName == null) //если каким-то образом пользователь не определился или отсутствовал в бд, то устанавливается значение НЕОПРЕДЕЛЕНО { userName = "******"; } if (codeGoodsCount != 0 && codeGoods != null) //если данных штрихкод есть в локальной БД, то выводим код товара, если нет, то выводим "нет совпадений" { DisplayAlert("Код товара: " + codeGoods, "Штрихкод: " + result.Text, "OK"); } else { DisplayAlert("Нет совпадений", "Штрихкод: " + result.Text, "OK"); } //добавление в БД полученного результата сканирования BarecodeResult barecodeResult = new BarecodeResult(); barecodeResult.BarecodeFormat = result.BarcodeFormat.ToString(); barecodeResult.TextResult = result.Text; barecodeResult.CodeGoods = codeGoods; barecodeResult.Status = 0; barecodeResult.dateTime = DateTime.Now; barecodeResult.UserName = userName; if (!String.IsNullOrEmpty(barecodeResult.TextResult)) { try { App.Database.SaveItem(barecodeResult); } catch { DisplayAlert("Ошибка", "В процессе добавления произошла ошибка", "OK"); } } else { DisplayAlert("Ошибка", "Данные не добавлены.", "OK"); } }); }; //текст снизу страницы сканирования var overlay = new ZXingDefaultOverlay { TopText = null, BottomText = "Автомаическое сканирование каждые 3 сек.", ShowFlashButton = true, //кнопка фонарика }; //обработчик кнопки фонарика overlay.FlashButtonClicked += (a, b) => { zxing.IsTorchOn = !zxing.IsTorchOn; }; //кнопка отмены var cancel = new Button() { Text = "Отмена", BackgroundColor = Color.Red, VerticalOptions = LayoutOptions.EndAndExpand, HorizontalOptions = LayoutOptions.EndAndExpand }; //обработчик кнопки отмены cancel.Clicked += (a, b) => { Navigation.PopToRootAsync(); NavigationPage navPage = (NavigationPage)App.Current.MainPage; }; //данная страница постоена на Grid var grid = new Grid { VerticalOptions = LayoutOptions.FillAndExpand, HorizontalOptions = LayoutOptions.FillAndExpand, }; //добавленик в Grid элементов grid.Children.Add(zxing); grid.Children.Add(overlay); grid.Children.Add(cancel); // объявляем элементы на страницу Content = grid; }
public async Task <string> SkanowanieEan() { opts = new ZXing.Mobile.MobileBarcodeScanningOptions() { AutoRotate = false, PossibleFormats = new List <ZXing.BarcodeFormat>() { //ZXing.BarcodeFormat.CODE_128, //ZXing.BarcodeFormat.CODABAR, ZXing.BarcodeFormat.CODE_39, ZXing.BarcodeFormat.EAN_13 } }; opts.TryHarder = true; zxing = new ZXingScannerView { IsScanning = false, IsTorchOn = false, IsAnalyzing = false, AutomationId = "zxingDefaultOverlay", //zxingScannerView Opacity = 22, Options = opts }; var torch = new Switch { }; torch.Toggled += delegate { scanPage.ToggleTorch(); }; var grid = new Grid { VerticalOptions = LayoutOptions.Center, HorizontalOptions = LayoutOptions.Center, }; var Overlay = new ZXingDefaultOverlay { TopText = "Włącz latarkę", BottomText = "Skanowanie rozpocznie się automatycznie", ShowFlashButton = true, AutomationId = "zxingDefaultOverlay", }; var customOverlay = new StackLayout { HorizontalOptions = LayoutOptions.EndAndExpand, VerticalOptions = LayoutOptions.EndAndExpand }; grid.Children.Add(Overlay); Overlay.Children.Add(torch); Overlay.BindingContext = Overlay; scanPage = new ZXingScannerPage(opts, customOverlay: Overlay) { DefaultOverlayTopText = "Zeskanuj kod ", //DefaultOverlayBottomText = " Skanuj kod "; DefaultOverlayShowFlashButton = true }; scanPage.OnScanResult += (result) => { scanPage.IsScanning = false; scanPage.AutoFocus(); Device.BeginInvokeOnMainThread(() => { Device.StartTimer(new TimeSpan(0, 0, 0, 2), () => { if (scanPage.IsScanning) { scanPage.AutoFocus(); } return(true); }); Navigation.PopModalAsync(); resultat = result.Text; }); }; await Navigation.PushModalAsync(scanPage); return(resultat); }
public CustomScanPage() : base() { try { zxing = new ZXingScannerView { HorizontalOptions = LayoutOptions.FillAndExpand, VerticalOptions = LayoutOptions.FillAndExpand }; var abort = new Button { Text = "Abort", }; abort.Clicked += Abort_Clicked; zxing.OnScanResult += (result) => Device.BeginInvokeOnMainThread(async() => { // Stop analysis until we navigate away so we don't keep reading barcodes zxing.IsAnalyzing = false; // Show an alert //await DisplayAlert("Scanned Barcode", result.Text, "OK"); // Navigate away // await Navigation.PopAsync(); MessagingCenter.Send(result.Text, "Result"); //var myMainPage = new ScannerSuccess(); //var navPage = new NavigationPage(myMainPage); //Navigation.PopModalAsync(); //zxing.IsScanning = false; //if (!string.IsNullOrEmpty(result.Text)) // await _navigationService.NavigateAsync("ScannerSuccess"); //else //await _navigationService.NavigateAsync("ScannerFail"); }); overlay = new ZXingDefaultOverlay { TopText = "Hold your phone up to the barcode", BottomText = "Scanning will happen automatically", //ShowFlashButton = zxing.HasTorch, }; overlay.FlashButtonClicked += (sender, e) => { zxing.IsTorchOn = !zxing.IsTorchOn; }; var grid = new Grid { VerticalOptions = LayoutOptions.FillAndExpand, HorizontalOptions = LayoutOptions.FillAndExpand, }; grid.Children.Add(zxing); grid.Children.Add(overlay); grid.Children.Add(abort); // The root page of your application Content = grid; //Content = abort; } catch (Exception) { } }
bool EnteredQtyBool = false; //tells us if we have entered quantity to scan. public ScanPage(OrderItem scannableItem, IList <OrderItem> list) { InitializeComponent(); //calling content formed in ScanPage.xaml OIList = list; this.scannableItem = scannableItem; //Taking the OrderItem from OrderListView. remainingScans = (int)scannableItem.QtyOrdered; itemLabel.Text = "Item to be scanned: " + scannableItem.Name; //sets our label with the name of the item in case of mis tap. /** * var "options" allows you to choose what options you want your scanner to * allow. Currently using it to AutoRotate. Another option, "TryHarder", * gets or sets a flag which cause a deeper look into the bitmap.This * just makes it so the camera focuses on the barcode quicker, though it * does add room for misscans. */ var options = new MobileBarcodeScanningOptions { AutoRotate = true, UseFrontCameraIfAvailable = false, TryHarder = false }; Button EnterQtyToScan = new Button { IsVisible = true, BorderColor = Color.DarkGray, Text = "Enter Amount", }; /* * Overlay sets our top and bottom texts, these texts will change once we scan items. */ var overlay = new ZXingDefaultOverlay { TopText = "Quantity scanned: " + qtyScanned.ToString() + "\t" + "Quantity remaining: " + scannableItem.QtyOrdered.ToString(), BottomText = "Item Scanning: " + scannableItem.Name + "\r" + "Located in Section: " + scannableItem.LocationQOH.Replace(Environment.NewLine, " ") + "\r" + " You can enter amount up to one less than quantity remaining." }; //Removes red line across screen var redLine = overlay.Children.First(x => x.BackgroundColor == Color.Red); overlay.Children.Remove(redLine); //Removes top background color var topLine = overlay.Children.First(); overlay.Children.Remove(topLine); //Adding a clear lines to have more space to scan. var clearLine = overlay.Children[2]; overlay.Children.AddVertical(clearLine); overlay.Children.AddVertical(clearLine); //Removes bottom background color var bottomLine = overlay.Children.First(); overlay.Children.Remove(bottomLine); //Setting our elements for our button on the scanner page EnterQtyToScan.Scale = 1; EnterQtyToScan.HorizontalOptions = LayoutOptions.Center; EnterQtyToScan.Margin = 20; EnterQtyToScan.BackgroundColor = Color.Gray; overlay.Children.AddVertical(EnterQtyToScan); //adding our "Enter Amount" button to our overlay //Once button is clicked, create a new scanPage with the options and overlay set above btnScan.Clicked += async(a, s) => { scanPage = new ZXingScannerPage(options, overlay); overlay.FlashButtonClicked += (t, ed) => //Can be removed if target device has no flash capability { scanPage.ToggleTorch(); //If flash button is clicked it will toggle on/off. }; EnterQtyToScan.Clicked += async(w, q) => { EnteredQtyBool = true; //we pressed the "enter quantity to scan" button while (tempEnteredAmount > scannableItem.QtyOrdered || tempEnteredAmount == -1) //while the amount we entered is greater than qtyOrdered or has not been entered yet. { //Prompt that will have us enter the quantity we wish to scan at once string EnteredAmountToScan = await DisplayPromptAsync(scannableItem.Name, "How many of this item do you intend to pack?", "accept", "cancel", maxLength : 4, keyboard : Keyboard.Numeric); if (EnteredAmountToScan == null) { EnterQtyToScan.Unfocus(); //Cancel button pressed we unfocus the prompt. EnteredQtyBool = false; return; } try { //tempEnteredAmount must be a valid number (0-one less than remainingScans) otherwise you will get an Error message. tempEnteredAmount = Int32.Parse(EnteredAmountToScan); //try and set our global var if (tempEnteredAmount > remainingScans) //if it exceeds our qty ordered we must display an error { await DisplayAlert("Error", "Amount entered exceeds quantity ordered.", "OK"); tempEnteredAmount = -1; } if (tempEnteredAmount < 0) //if it is negative we must display an error { await DisplayAlert("Error", "Amount must be a positive number.", "OK"); tempEnteredAmount = -1; } if (tempEnteredAmount == remainingScans) //if it equals our qty ordered we must display an error { await DisplayAlert("Error", "Amount entered must be at least one less than quantity ordered.", "OK"); tempEnteredAmount = -1; } } catch { //If the number is a decimal we display an Error message. await DisplayAlert("Error", "Invalid entry: entry must be a whole number.", "OK"); } } RemainingScans(); //After we leave our while loop we call our method to update our variables. overlay.TopText = "Quantity scanned: " + qtyScanned.ToString() + "\r\n\r\n" + "Quantity remaining: " + remainingScans.ToString(); //overlay to represent how many scans remain after we enter our amount. tempEnteredAmount = -1; //allows us to reenter our loop if we press the button again. }; //Once we capture a barcode we "BeginInvokeOnMainThread" to check what we scanned scanPage.OnScanResult += (result) => { Device.BeginInvokeOnMainThread(async() => { if (_isScanning) { _isScanning = false; //bool to stop _isScanning from allowing us to enter if() statement. scanPage.IsAnalyzing = false; //stops scanning barcodes once this is implemented. barCodeRead = result.Text; //sets barcode scanned in as a string if (barCodeMatcher()) //If the scan matches the barcode from the OrderItem list, display the "Barcode Matches" alert. { RemainingScans(); //tells us how many more scan we have overlay.TopText = "Quantity scanned: " + qtyScanned.ToString() + "\r\n\r\n" + "Quantity remaining: " + remainingScans.ToString(); //overlay to represent how many scans remain. await DisplayAlert("Barcode Matches", result.Text + " , " + " Remaining Scans: " + remainingScans.ToString() + " , " + "QtyScanned: " + qtyScanned.ToString(), "OK"); if (doneScanning) { await Navigation.PopModalAsync(); //Takes us back to the page with the scan button to know we are done. await DisplayAlert("Finished Scanning: ", scannableItem.Name + " is completed.", "OK"); //Alert to know we are done scanning an item. await Navigation.PopAsync(); //Takes us back to the page where we choose which item we are about to scan. OIList[OIList.IndexOf(scannableItem)].IsPacked = true; //sets our binding property to true } } else { await DisplayAlert("Scanned Barcode", result.Text + " , " + result.BarcodeFormat + " ," + result.ResultPoints[0].ToString() + " , " + " Barcode does NOT match that of the selected item.", "OK"); //Every barcode scanned that does not match will display as an alert. } scanPage.IsAnalyzing = true; //Allows us to scan again once we "ok" the popup. _isScanning = true; //Allows us to be able to reenter our if() statement. } }); }; await Navigation.PushModalAsync(scanPage); //Takes us to the page where we see what the camera is picking up }; //If the wrong item is clicked hit the back button to get back to the list of items to be scanned. btnBack.Clicked += async(a, s) => { await Navigation.PopAsync(); //Takes us back to the page where we choose which item we are about to scan. }; this.Content = Content; //sets our content from the .xaml }
public async void Scan() { try { var options = new MobileBarcodeScanningOptions { AutoRotate = false, UseFrontCameraIfAvailable = false, TryHarder = true, }; var overlay = new ZXingDefaultOverlay { TopText = "Please scan QR code", BottomText = "Align the QR code within the frame" }; var grid = new Grid(); RowDefinition row1 = new RowDefinition() { Height = 100 }; RowDefinition row2 = new RowDefinition(); RowDefinition row3 = new RowDefinition() { Height = 150 }; grid.RowDefinitions.Add(row1); grid.RowDefinitions.Add(row2); grid.RowDefinitions.Add(row3); Label edit = new Label() { Text = "Đặt mã QR vào khung hình", FontSize = 24, HorizontalTextAlignment = TextAlignment.Center, HorizontalOptions = LayoutOptions.CenterAndExpand, VerticalTextAlignment = TextAlignment.Center, VerticalOptions = LayoutOptions.CenterAndExpand, TextColor = Color.Red, }; Grid grid1 = new Grid() { BackgroundColor = Color.Black, Opacity = 0.4f, VerticalOptions = LayoutOptions.FillAndExpand, HorizontalOptions = LayoutOptions.FillAndExpand }; grid1.Children.Add(edit); Grid.SetRow(grid1, 0); grid.Children.Add(grid1); var QRScanner = new ZXingScannerPage(options, grid); await Navigation.PushModalAsync(QRScanner); QRScanner.OnScanResult += (result) => { // Stop scanning QRScanner.IsScanning = false; // Pop the page and show the result Device.BeginInvokeOnMainThread(async() => { TableOrderViewModel model = new TableOrderViewModel(); try { await Navigation.PopModalAsync(false); if (result.Text.Contains("TABLE")) { IRES_Global.GlobalInfo.TableCode = result.Text; string s = result.Text.Replace("TABLE", ""); var res = await model.OrderTable(int.Parse(s), DateTime.Now); BtnMenu_Clicked(null, null); } else if (result.Text.Contains("ORDER")) { string z = result.Text.Replace("ORDER", ""); model.getOrderByCode(z); } } catch { await Navigation.PopModalAsync(false); if (result.Text.Contains("TABLE")) { IRES_Global.GlobalInfo.TableCode = result.Text; string s = result.Text.Replace("TABLE", ""); var res = await model.OrderTable(int.Parse(s), DateTime.Now); BtnMenu_Clicked(null, null); } else if (result.Text.Contains("ORDER")) { string z = result.Text.Replace("ORDER", ""); model.getOrderByCode(z); } } }); }; } catch (Exception ex) { // GlobalScript.SeptemberDebugMessages("ERROR", "BtnScanQR_Clicked", "Opening ZXing Failed: " + ex); Device.BeginInvokeOnMainThread(() => { // DisplayAlert("Scanned Barcode", ex.ToString(), "OK"); }); } }