I'm using the ZXing plugin to scan bar codes and I'm using a custom overlay to display information and make a button visible/invisible when I need to perform an action, which in this case is to set a flag and make the button invisible again.
In this code I set up the scanning plugin:
MyButton_Scan.Click += async (sender, e) =>
{
var selectedEvent = string.Format("{0}", MyEventsSpinner.GetItemAtPosition(MyEventsSpinner.SelectedItemPosition));
if (selectedEvent.ToUpper() != "SELECT EVENT")
{
MobileBarcodeScanner.Initialize(Application);
scanner = new MobileBarcodeScanner();
scanner.UseCustomOverlay = true;
zxingOverlay = LayoutInflater.FromContext(this).Inflate(Resource.Layout.scanner, null);
MyScanScreenButton = zxingOverlay.FindViewById<Android.Widget.Button>(Resource.Id.okButton);
MyScanScreenButton.Click += btnOk_Click;
MyScanScreenButton.Visibility = Android.Views.ViewStates.Invisible;
scanner.CustomOverlay = zxingOverlay;
var opt = new MobileBarcodeScanningOptions();
opt.DelayBetweenContinuousScans = 5000;
//Start scanning
scanner.ScanContinuously(this, opt, HandleScanResult);
} else
{
Utils.showMessage("Please select an event from the drop down list");
}
};
The code that handles the scan result and button click:
void btnOk_Click(object sender, System.EventArgs e)
{
popUpOpen = false;
MyScanScreenButton.Visibility = Android.Views.ViewStates.Invisible;
}
void HandleScanResult(ZXing.Result result)
{
if (!popUpOpen)
{
Boolean ConversionGood = true;
TextView MyTextView = zxingOverlay.FindViewById<TextView>(Resource.Id.ticketInfo);
Int32 convertedResult = 0;
Stream successbeepStream = GetType().Assembly.GetManifestResourceStream("eTicket_Scanner.beep.wav");
Stream failbeepStream = GetType().Assembly.GetManifestResourceStream("eTicket_Scanner.buzzer.wav");
MyTextView.SetBackgroundColor(Color.White);
try
{
convertedResult = Convert.ToInt32(result.Text);
}
catch (Exception ex)
{
ConversionGood = false;
bool isSuccess = _simpleAudioPlayer.Load(failbeepStream);
_simpleAudioPlayer.Play();
popUpOpen = true;
MyScanScreenButton.Visibility = Android.Views.ViewStates.Visible;
MyTextView.SetBackgroundColor(Color.Red );
MyTextView.Text = "Not a valid ticket for this event.\nErrorif applicable): " + ex.Message;
}
string scanResult = "";
if (ConversionGood)
{
scanResult = MyEventsService.VerifyScannedCode(MyUser.Username, MyUser.Password, currentEventID, convertedResult);
if (scanResult == "Y")
{
MyTextView.SetBackgroundColor(Color.Green);
bool isSuccess = _simpleAudioPlayer.Load(successbeepStream);
popUpOpen = true;
MyTextView.SetBackgroundColor(Color.Green);
MyTextView.Text = MyEventsService.GetTicketInfo(MyUser.Username, MyUser.Password, currentEventID, convertedResult);
_simpleAudioPlayer.Play();
MyScanScreenButton.Visibility = Android.Views.ViewStates.Visible;
}
else
{
bool isSuccess = _simpleAudioPlayer.Load(failbeepStream);
popUpOpen = true;
MyTextView.SetBackgroundColor(Color.Red);
MyTextView.Text = MyEventsService.GetFailedScanTicketInfo(MyUser.Username, MyUser.Password, currentEventID, convertedResult);
_simpleAudioPlayer.Play();
MyScanScreenButton.Visibility = Android.Views.ViewStates.Visible;
}
}
}
}
Its not a very complicated app, scan barcodes and verify the code, set the color of the textview background and display the info. The "Ok" button is never visible, but if I click in the space where the button should appear, it executes the button click code. I'm assuming that there is some sort of thread issue here with the interface, but anything I've tried with the thread hasn't worked. Anyone have any ideas?
Related
I have an active Google Places autocomplete working with Xamarin Forms or Cross Platform. I have a working solution that auto populates the address when the user types in the address. My problem is when the user selects it from the list the address does not go to the search_bar.text… The search bar just remains with the text that was typed? how can I get the text when selected to populate in the search bar.
I am new to Xamarin forms and C#.
public Createbusinessaccount ()
{
InitializeComponent ();
search_bar.ApiKey = GooglePlacesApiKey;
search_bar.Type = PlaceType.Address;
search_bar.Components = new Components("country:us"); // Restrict results to Australia and New Zealand
search_bar.PlacesRetrieved += Search_Bar_PlacesRetrieved;
search_bar.TextChanged += Search_Bar_TextChanged;
search_bar.MinimumSearchText = 2;
results_list.ItemSelected += Results_List_ItemSelected;
}
void Search_Bar_PlacesRetrieved(object sender, AutoCompleteResult result)
{
results_list.ItemsSource = result.AutoCompletePlaces;
spinner.IsRunning = false;
spinner.IsVisible = false;
if (result.AutoCompletePlaces != null && result.AutoCompletePlaces.Count > 0)
results_list.IsVisible = true;
}
void Search_Bar_TextChanged(object sender, TextChangedEventArgs e)
{
if (!string.IsNullOrEmpty(e.NewTextValue))
{
results_list.IsVisible = false;
spinner.IsVisible = true;
spinner.IsRunning = true;
}
else
{
results_list.IsVisible = true;
spinner.IsRunning = false;
spinner.IsVisible = false;
}
}
async void Results_List_ItemSelected(object sender, SelectedItemChangedEventArgs e)
{
if (e.SelectedItem == null)
return;
var prediction = (AutoCompletePrediction)e.SelectedItem;
results_list.SelectedItem = null;
var place = await Places.GetPlace(prediction.Place_ID, GooglePlacesApiKey);
if (place != null)
await DisplayAlert(
place.Name, string.Format("Lat: {0}\nLon: {1}", place.Latitude, place.Longitude), "OK");
}
In your ItemSelected method, you need to set the text of the searchbar:
async void Results_List_ItemSelected(object sender, SelectedItemChangedEventArgs e)
{
if (e.SelectedItem == null)
return;
var prediction = (AutoCompletePrediction)e.SelectedItem;
search_bar.Text = prediction.Name? // Your property here
results_list.SelectedItem = null;
var place = await Places.GetPlace(prediction.Place_ID, GooglePlacesApiKey);
if (place != null)
await DisplayAlert(
place.Name, string.Format("Lat: {0}\nLon: {1}", place.Latitude, place.Longitude), "OK");
}
I am still trying to fix this, it only adds the street name and number not the whole address
I have the following code that I use to update my datagridview:
public readonly BindingList<InventoryTransaction> InventoryTransactions = new BindingList<InventoryTransaction>() { RaiseListChangedEvents = true };
private bool _scanning;
private string _checkData;
public BarCodeForm()
{
InitializeComponent();
barCodeForm_InventoryTransactionBindingSource.DataSource = InventoryTransactions;
panel1.Enabled = false;
_scanning = true;
timer_ScanTimer.Enabled = false;
//InventoryTransactions.AddingNew += InventoryTransactions_AddingNew;
}
private void timer_ScanTimer_Tick(object sender, EventArgs e)
{
panel1.Enabled = true;
label_Message.Text = "Please press ENTER or click RESET to scan again.";
timer_ScanTimer.Enabled = false;
textBox_ModelNumber.Text = _checkData;
textBox_Quantity.Text = "1";
var qry = (from x in InventoryTransactions
where x.ModelNumber == _checkData
select x).FirstOrDefault();
_checkData = string.Empty;
if (qry == null)
{
textBox_Quantity.Focus();
return;
}
qry.Quantity += qry.Quantity;
barCodeForm_InventoryTransactionBindingSource.EndEdit();
panel1.Enabled = false;
_scanning = true;
timer_ScanTimer.Enabled = false;
panel1.Text = "Scan now!";
ResetForm();
}
The problem is that I have updated the quantity of the InventoryTransactions but my datagridview is not updating. Do I have to issue a command of some sort to force the update or to apply the changes?
Thanks!
After doing lots of debugging, I've narrowed down as to why my dbContext update does not work.
I have a script that runs on Page_Load that will populate a form based on the query string category_Id which is the primary key of my table.
protected void Page_Load(object sender, EventArgs e)
{
// Populate Edit Fields
if (Request.QueryString["categoryId"] != null)
{
CategoryDAL categoryDAL = new CategoryDAL();
RecipeCategory myCategory = new RecipeCategory();
try
{
addDiv.Attributes["class"] = "hidden";
editDiv.Attributes["class"] = "display";
int categoryToGet = Convert.ToInt32(Request.QueryString["categoryId"]);
myCategory = categoryDAL.GetCategory(categoryToGet);
tbEditCategoryName.Text = myCategory.Category_Name;
tbEditCategoryDescription.Text = myCategory.Description;
ddlEditCategoryGroupList.SelectedValue = Convert.ToString(myCategory.CatGroup_Id);
ddlEditCategoryGroupList.DataBind();
}
catch(Exception ex)
{
updateStatus.Attributes["class"] = "alert alert-info alert-dismissable fade in";
updateStatus.Visible = true;
lblStatus.Text = "Could not get Category Info, please try again.";
}
}
This is my script that runs when the edit_Button is clicked, it should update the row in the database and redirect to the viewCategories page.
protected void btnEditCategory_Click(object sender, EventArgs e)
{
if (Request.QueryString["categoryId"] != null)
{
CategoryDAL categoryDAL = new CategoryDAL();
RecipeCategory myCategory = new RecipeCategory();
try
{
int categoryToEdit = Convert.ToInt32(Request.QueryString["categoryId"]);
myCategory.Category_Name = tbEditCategoryName.Text;
myCategory.Description = tbEditCategoryDescription.Text;
myCategory.CatGroup_Id = Convert.ToInt32(ddlEditCategoryGroupList.SelectedValue);
try
{
bool editStatus = categoryDAL.EditCategory(categoryToEdit, myCategory);
if (editStatus)
{
HttpContext.Current.Session["editStatus"] = "Successful";
Response.Redirect("~/Admin/ManageCategories.aspx");
}
else
{
lblEditStatus.Text = "Unable to update category, please try again";
lblEditStatus.CssClass = "alert-danger";
}
}
catch (Exception ex)
{
lblEditStatus.Text = Convert.ToString(ex);
lblEditStatus.CssClass = "alert-danger";
}
}
catch (Exception ex)
{
updateStatus.Attributes["class"] = "alert alert-info alert-dismissable fade in";
updateStatus.Visible = true;
lblStatus.Text = "Invalid categoryId.";
}
}
else
{
updateStatus.Attributes["class"] = "alert alert-info alert-dismissable fade in";
updateStatus.Visible = true;
lblStatus.Text = "Nothing to update.";
}
}
And this is in my DALayer which holds the functions that has anything to do with categories.
public bool EditCategory(int categoryToEdit, RecipeCategory newCategoryInfo)
{
RecipeXchangeDBContext dbContext = new RecipeXchangeDBContext();
RecipeCategory myCategory = new RecipeCategory();
bool status = false;
myCategory = (from c in dbContext.RecipeCategories
where c.Category_Id == categoryToEdit
select c).First();
myCategory.Category_Name = newCategoryInfo.Category_Name;
myCategory.Description = newCategoryInfo.Description;
myCategory.CatGroup_Id = newCategoryInfo.CatGroup_Id;
try
{
if (dbContext.SaveChanges() == 1)
status = true;
else
status = false;
}
catch (InvalidOperationException ex)
{
status = false;
}
return status;
}
For some reason, whenever I try to update a row with a prepopulated form, the code will always return 0 from dbContext.SaveChanges() and does not update the row in the database.
Note: if I do not populate the form, it works perfectly as normal.
Page_Load doesn't just run the first time the page is loaded, it runs every time the page is loaded, including when the user submits the form. The result is that you're overwriting the user's input before saving it.
In this case, since you're using regular browser navigation to go to a specific category page, you can just check Page.IsPostBack in Page_Load and not set anything in that case.
Can anybody help me with this code in my Xamarin project. I am trying to set a loading wheel (to signify that an action is happening and to let the user know to wait) when the "Login" button is clicked. For some reason since the function is asynchronous the loading wheel is never set to visible when the API code is run. It just fails to show up when I click login, however, it still does the login function.
// Defined up above in the file
var loginButton = new Button
{
Text = "Login",
};
loginButton.BackgroundColor = Color.Navy;
loginButton.TextColor = Color.White;
loginButton.Clicked += OnLoginButtonClicked;
async void OnLoginButtonClicked(object sender, EventArgs e)
{
loadingWheel.IsVisible = true;
try
{
var restUrl = "*******";
var content = string.Empty;
using (var client = new HttpClient())
{
string body = "{\"UserName\":\"" + usernameEntry.Text + "\", \"Password\":\"" + passwordEntry.Text + "\"}";
var contentType = new StringContent(body, Encoding.UTF8, "application/json");
var result = client.PostAsync(restUrl, contentType).Result;
content = await result.Content.ReadAsStringAsync();
}
if (content.ToLower() != "false")
{
var menuPage = new MenuPage();
NavigationPage = new NavigationPage(new HomePage());
RootPage = new Views.MainPage();
RootPage.Master = menuPage;
RootPage.Detail = NavigationPage;
MainPage = RootPage;
}
else
{
messageLabel.Text = "Username or password incorrect. Please try again.";
passwordEntry.Text = string.Empty;
}
}
catch (Exception ex)
{
messageLabel.Text = "Please check the internet connection for the connectivity.";
}
}
If I comment out the entire try block then the loading wheel does show up. It just does not work with the code in there.
Can anybody help me solve this problem? Thanks.
I think you can try with BeginInvokeOnMainThread
Device.BeginInvokeOnMainThread (() => {
loadingWheel.IsVisible = true;
});
UPDATE
I have also create this REPO... it works without BeginInvodeOnMainThread
public class MyPage6 : ContentPage
{
ActivityIndicator _ac = new ActivityIndicator { IsVisible = false, IsRunning = false };
public MyPage6()
{
Button b = new Button {Text = "Press for ActivityIndicator" };
b.Clicked += B_Clicked;
Content = new StackLayout
{
Children = {
_ac,
b,
new Label { Text = "Hello ContentPage" }
}
};
}
async void B_Clicked(object sender, EventArgs e)
{
_ac.IsRunning = true;
_ac.IsVisible = true;
await Task.Delay(2000);
_ac.IsRunning = false;
_ac.IsVisible = false;
}
}
We have aspx page that is being used as a dialog box.
Page has ascx control which has Text box to search available users from oracle DB tables.
Every search click posts back to same control and renders search results.
If I click search and before response is back from server I close the dialog aspx page, then next time I try to open same dialog box it takes forever to render.
Please suggest what could be happening, going wrong?
Any help is highly appreciated
Here is the code
protected void UserListControl_PreRender(object sender, EventArgs e)
{
//set UI text
m_objTitle.Text = TITLE_LABEL;
//Set Properties of search
m_objSearchResults.CacheResults = true;
m_objSearchResults.RefreshCache = true;
m_objSearchResults.DoSearch = true;
m_objSearchResults.Pageable = true;
m_objSearchResults.NoRecordsMessage = NO_RECORDS_MSG;
m_objSearchResults.PageSize = 25;
m_objSearchResults.SearchType = m_sSearchType;
//Add items to the dropdown
if (m_objStatusDropDown.Items.FindByText(AVAIL_USER_TEXT) == null)
{
m_objStatusDropDown.Items.Add(AVAIL_USER_TEXT);
m_objStatusDropDown.Items.FindByText(AVAIL_USER_TEXT).Value = AVAIL_USER_VALUE;
}
if (m_objStatusDropDown.Items.FindByText(ALL_USER_TEXT) == null)
{
m_objStatusDropDown.Items.Add(ALL_USER_TEXT);
m_objStatusDropDown.Items.FindByText(ALL_USER_TEXT).Value = ALL_USER_VALUE;
}
if (m_objStatusDropDown.Items.FindByText(SEARCH_USER_TEXT) == null)
{
m_objStatusDropDown.Items.Add(SEARCH_USER_TEXT);
m_objStatusDropDown.Items.FindByText(SEARCH_USER_TEXT).Value = SEARCH_USER_VALUE;
}
if (this.Page.IsPostBack == false)
{
m_objStatusDropDown.SelectedValue = SEARCH_USER_VALUE;
}
if (IsPostBack)
{
try
{
m_objUserInstructionText.Text = "";
//add the DAO Parameters
string assignmentTypeSelected = Request.QueryString["AssignmentType"];
m_objSearchResults.DAOParams.Add("RequestType", Request.QueryString["RequestType"]);
m_objSearchResults.DAOParams.Add("AssignmentID", Request.QueryString["AssignmentID"]);
m_objSearchResults.DAOParams.Add("AssignmentType", assignmentTypeSelected);
m_objSearchResults.DAOParams["StatusFilter"] = m_objStatusDropDown.SelectedValue.ToUpper();
m_objSearchResults.DAOParams["Name"] = m_objSearchTextBox.Value.Trim();
if (null == SetApplCode(assignmentTypeSelected))
{
throw new ApplicationException("Invalid Assignment Type.");
}
else
{
m_objSearchResults.DAOParams["ApplCode"] = SetApplCode(assignmentTypeSelected).ToUpper();
}
//add searchControl
m_objListPH.Controls.Add(m_objSearchResults);
// Get the values from the ResultsForm
string sRecordsDisplayed = m_objSearchResults.RecordsDisplayed;
string sTableWidth = m_objSearchResults.TableWidth;
bool bPageable = m_objSearchResults.Pageable;
int iCurrentPageIndex = m_objSearchResults.CurrentPageIndex;
int iPageSize = m_objSearchResults.PageSize;
int iRecordCount = m_objSearchResults.RecordCount;
int iEndRecord = m_objSearchResults.EndRecord;
// Create the html if we are paging data
m_objNavigation.Visible = bPageable;
m_objNavigation.DisplayViewAllButton = false;
m_objNavigation.PageSize = iPageSize;
m_objNavigation.Count = iRecordCount;
m_objNavigation.ItemsDisplayText = "Users";
m_objNavigation.CurrentPage = iCurrentPageIndex + 1;
}
catch (ApplicationException ex)
{
m_objInvalidAssignTypeErr.Text = ex.Message;
m_objUserInstructionText.Text = "";
}
}
}