Xamarin Forms button event not firing on Android - xamarin

I have a Xamarin Forms app, in one of my pages I have two buttons, on Android when you tap the button it does not fire the event, it just highlights the button, if you tap a second time then it fires the event, on iOS it runs flawlessly. Below is some Code extracts, sorry if my code has bad practices, I am a noob, so please do correct me, best way to learn:
//Initialize Page
public GameDetailsNew(Game myEvent)
{
InitializeComponent();
MyEvent.Text = myEvent.EventName;
MyTimeHeader.Text = myEvent.TimeOfEvent;
myEventID = myEvent.EventID;
Task.Run(() => { GetAttendingEvent(myEvent.EventID); });
}
//GetAttendingEvent
private void GetAttendingEvent(int eventID)
{
var registerLable = "";
var attendinIsVisible = false;
var notAttendingIsVisible = false;
try
{
HelperFiles.APICaller ac = new HelperFiles.APICaller();
var x = (string)ac.CallCOFMOBILEBool("GetIsAttending?eventID=" + eventID);
if (x == "Attending")
{
registerLable = "You are currently Attending this Event";
attendinIsVisible = false;
notAttendingIsVisible = true;
}
else
{
registerLable = "You are currently NOT Attending this Event";
attendinIsVisible = true;
notAttendingIsVisible = false;
}
Device.BeginInvokeOnMainThread(() =>
{
RegisterLable.Text = registerLable;
AttendingButton.IsVisible = attendinIsVisible;
NotAttendingButton.IsVisible = notAttendingIsVisible;
});
}
catch (Exception ex)
{
MyAlerts("Error", ex.Message, "OK");
}
}
//My To Button Event Handlers
//Sets User as attending event
void AttendingClicked(object sender, System.EventArgs e)
{
try
{
HelperFiles.APICaller ac = new HelperFiles.APICaller();
var x = (string)ac.CallCOFMOBILEBool("GetCreateAttending?eventID=" + myEventID);
if (x == "1")
{
RegisterLable.Text = "You are currently Attending this Event";
AttendingButton.IsVisible = false;
NotAttendingButton.IsVisible = true;
}
else
{
RegisterLable.Text = "You are currently NOT Attending this Event";
AttendingButton.IsVisible = true;
NotAttendingButton.IsVisible = false;
}
GetDeployingEvent(myEventID);
}
catch (Exception ex)
{
MyAlerts("Error", ex.Message, "OK");
}
}
//Sets User as Not attending event
void NotAttendingClicked(object sender, System.EventArgs e)
{
try
{
HelperFiles.APICaller ac = new HelperFiles.APICaller();
var x = (string)ac.CallCOFMOBILEBool("GetCreateNotAttending?eventID=" + myEventID);
if (x != "1")
{
RegisterLable.Text = "You are currently Attending this Event";
AttendingButton.IsVisible = false;
NotAttendingButton.IsVisible = true;
}
else
{
RegisterLable.Text = "You are currently NOT Attending this Event";
AttendingButton.IsVisible = true;
NotAttendingButton.IsVisible = false;
}
GetDeployingEvent(myEventID);
}
catch (Exception ex)
{
MyAlerts("Error", ex.Message, "OK");
}
}

I just wanted to update on this, I managed to resolve the issue. about 8 months ago I started my project in Xamarin Studio, fast forward a few months, Xamarin Studios changed to Visual Studio. No matter what i done i could not get rid of this bug, I then started a brand new app and pasted all my code in to the new app. This has resolved the bug.

Related

Is there any plugin or way to show 'new version of app available' alert when user opens app

I have Xamarin.Android app, I want to show alert to user (when user opens app) that please download latest version. Like other apps. How can I do that?
I have tried few ways but didn't get succeed. I have tried this. This is quite different from Android. I need it for Xamarin.
I already asked this question but existing functionality broke down due to having some changes in play store policies, consequently I am not getting specific string "itemprop=\"softwareVersion\">" from play store so I asked new question. Thank you
Working answer. I have used plugin for that Plugin.LatestVersion for Xam.Android to get latest version of app from Google play store. below line of code was returning latest app version.
var appStoreVersionString = await CrossLatestVersion.Current.GetLatestVersionNumber();
Then this is the further implementation
private void CompareVersion()
{
double currentVersion = 0d;
double appStoreversion = 0d;
bool IsUpdateRequired = false;
if (Context.PackageName != null)
{
PackageInfo info = Context.PackageManager.GetPackageInfo(Context.PackageName, PackageInfoFlags.Activities);
string currentVersionStrig = info.VersionName;
currentVersion = Convert.ToDouble(currentVersionStrig);
}
try
{
if (IsUpdateRequired == false)
{
string appStoreVersionString = string.Empty;
if (CheckNetConnection.IsNetConnected())
{
Task.Run(async () => { appStoreVersionString = await CrossLatestVersion.Current.GetLatestVersionNumber();}).Wait();
if (!string.IsNullOrEmpty(appStoreVersionString))
{
appStoreversion = Convert.ToDouble(appStoreVersionString);
if ((appStoreversion.ToString() != currentVersion.ToString() && (appStoreversion > currentVersion)))
{
IsUpdateRequired = true;
}
}
}
}
if (IsUpdateRequired)
{
Activity.RunOnUiThread(() =>
{
AlertDialog dialog = null;
var Alertdialog = new Android.App.AlertDialog.Builder(Context);
Alertdialog.SetTitle("Update Available");
Alertdialog.SetMessage($"A new version of [" + appStoreversion + "] is available. Please update to version [" + appStoreversion + "] now.");
Alertdialog.SetNegativeButton("Cancel", (sender, e) =>
{
if (dialog == null)
{
dialog = Alertdialog.Create();
}
dialog.Dismiss();
});
Alertdialog.SetPositiveButton("Update", (sender, e) =>
{
string appPackage = string.Empty;
try
{
appPackage = Application.Context.PackageName;
Utilities.Logout(Activity);
var ints = new Intent(Intent.ActionView, Android.Net.Uri.Parse("market://details?id=" + appPackage));
ints.SetFlags(ActivityFlags.ClearTop);
ints.SetFlags(ActivityFlags.NoAnimation);
ints.SetFlags(ActivityFlags.NewTask);
Application.Context.StartActivity(ints);
}
catch (ActivityNotFoundException)
{
var apppack = Application.Context.PackageName;
Utilities.Logout(Activity);
var ints = new Intent(Intent.ActionView, Android.Net.Uri.Parse("market://details?id=" + appPackage));
ints.SetFlags(ActivityFlags.ClearTop);
ints.SetFlags(ActivityFlags.NoAnimation);
ints.SetFlags(ActivityFlags.NewTask);
Application.Context.StartActivity(ints);
}
//this kills the app?
Android.OS.Process.KillProcess(Android.OS.Process.MyPid());
System.Environment.Exit(1);
});
if (dialog == null)
dialog = Alertdialog.Create();
dialog.Show();
});
}
}
catch (Exception ex)
{
var objLog = new LogService();
objLog.MobileLog(ex, SISConst.UserName);
}
}

get outlook single occurrence of recurring calendar event from double click on calendar

I am creating an outlook plugin that opens a SharePoint Calendar event for editing. The SharePoint Calendar is added to outlook as an overlay.
When clicking on the series event and editing a series everything works fine. But when I select just this one (occurrence). I am unable to get any of the properties for the AppointmentItem object.
I have tried both the ReadComplete and the Open events and still get an exception:
Exception from HRESULT: 0x80040108" and I am unable to access the
Parent. It appears all of the properties are null except Class = 26
and MessageClass = "IPM.Appointment"
private void Application_ItemLoad(object item)
{
_item = item;
try
{
if (!(item is AppointmentItem) || !_exp.CurrentFolder.Name.Contains("Test - Conference Room ")) return;
_warnUser = true;
_apptItem = (AppointmentItem) item;
_apptItem.ReadComplete += test;
_apptItem.Open += McAI_Open;
}
catch (Exception ex)
{
var expMessage = ex.Message;
MessageBox.Show(expMessage);
}
}
private static void ThisAddIn_Shutdown(object sender, EventArgs e)
{
// Note: Outlook no longer raises this event. If you have code that
// must run when Outlook shuts down, see https://go.microsoft.com/fwlink/?LinkId=506785
}
private void McAI_Open(ref bool cancel)
{
_warnUser = false;
var conferenceRoom = _exp.CurrentFolder.Name;
conferenceRoom = conferenceRoom.Replace("Test - ", "");
if (!(_item is AppointmentItem)){return;}
try
{
var g = _apptItem.IsRecurring;
if (_apptItem != null && _exp.CurrentFolder.Name.Contains("Test") && _apptItem.Location != null)
{
var location = _apptItem.Location;
var result = location.Substring(location.LastIndexOf(':') + 1);
cancel = true;
var sharePointItemId = int.Parse(result);
var frm = new FrmCalendarSelection(
"<SharePointURL>" + conferenceRoom,
sharePointItemId);
frm.Show();
frm.Closed += Frm_Closed;
}
else if (_apptItem != null && _exp.CurrentFolder.Name.Contains("Test") && _apptItem.Location == null)
{
cancel = true;
var frm = new FrmCalendarSelection(
"<SharePointURL>" + conferenceRoom);
frm.Show();
frm.Closed += Frm_Closed;
}
}
catch (Exception e)
{
throw e;
}
}

How to get current location coordinates in the Map feature in Xamarin Application?

I am working on location coordinates marking feature in the App.
I am using following dll's and google map.
Xamarin.Forms.Maps
Xam.Plugin.Geolocator
Xam.Plugin.ExternalMaps
In my iphone simulator, If the Location is NONE.It pulls default location some where in Rome, Italy
Following is the code written to pull the Map ..
public async Task<Xamarin.Forms.Maps.Position> GetPosition()
{
IsBusy = true;
Xamarin.Forms.Maps.Position p;
try
{
if (!locator.IsGeolocationAvailable)
{
p = new Xamarin.Forms.Maps.Position();
}
if (!locator.IsGeolocationEnabled)
{
p = new Xamarin.Forms.Maps.Position();
}
var position = await locator.GetPositionAsync(timeoutMilliseconds: 10000);
p = new Xamarin.Forms.Maps.Position(position.Latitude,position.Longitude);
}
catch (Exception ex)
{
Debug.WriteLine(ex.Message);
p = new Xamarin.Forms.Maps.Position();
}
IsBusy = false;
return p;
}
public async Task<object> GetCityName(double latitude, double longitude) {
HttpClient client;
client = new HttpClient();
client.MaxResponseContentBufferSize = 256000;
try
{
var response = await client.GetAsync("https://maps.googleapis.com/maps/api/geocode/json?latlng=" + latitude + "," + longitude);
if (response.IsSuccessStatusCode)
{
var result = await response.Content.ReadAsStringAsync();
var json = Newtonsoft.Json.Linq.JObject.Parse(result);
var reValue = "" + json["results"][0]["formatted_address"];
var strArr = reValue.Split(',');
if (strArr.Length > 2)
return strArr[strArr.Length - 2] + ", " +strArr[strArr.Length - 1];
else
return "";
}
else {
Debug.WriteLine(#"Failed.");
return "Failed";
}
}
catch (Exception ex)
{
Debug.WriteLine(#"ERROR {0}", ex.Message);
return ex.Message;
}
}
Image :
elaborate your problem please, and change your conditions as follows:
if (CrossGeolocator.Current.IsGeolocationAvailable)
{
if (CrossGeolocator.Current.IsGeolocationEnabled)
{
var position = await locator.GetPositionAsync(timeoutMilliseconds: 10000);
p = new Xamarin.Forms.Maps.Position(position.Latitude,position.Longitude);
}
else
{
throw new Exception("Geolocation is turned off");
// Geolocation is turned off for the device.
}
}
else
{
throw new Exception("Geolocation is turned off");
// Geolocation not available for device
}
Here now Handle the catches from GetPosition() Method to make sure you don't get the default location.

Data grid view in win form does not re size with its content

I am trying to re size the data grid view in windows form. There are two data grid view on my form and both are fed from the database. Is there any was I can resize the data grid view on the left so that it grows with the content length and width and the data grid view shrinks with the content.
Given below is my code
private void show_Click(object sender, EventArgs e)
{
int rowIndex = Convert.ToInt32(productGridView.SelectedRows[0].Cells[2].Value);
//IEnumerable<Supplier> supplierQuery = from supplier in newNorthWindContext.Suppliers
// where supplier.SupplierID == rowIndex
// select new {} supplier;
IEnumerable<Supplier> supplierQuery = newNorthWindContext.Suppliers.Where(supliers => supliers.SupplierID == rowIndex);
supplierDataGridView.DataSource = ((ObjectQuery)supplierQuery).Execute(MergeOption.AppendOnly);
supplierDataGridView.Columns["SupplierID"].Visible = false;
supplierDataGridView.Columns["ContactTitle"].Visible = false;
supplierDataGridView.Columns["Address"].Visible = false;
supplierDataGridView.Columns["City"].Visible = false;
supplierDataGridView.Columns["Region"].Visible = false;
supplierDataGridView.Columns["PostalCode"].Visible = false;
supplierDataGridView.Columns["ContactTitle"].Visible = false;
supplierDataGridView.Columns["Address"].Visible = false;
//supplierDataGridView.AutoResizeColumns();
supplierDataGridView.AutoSizeColumnsMode =
DataGridViewAutoSizeColumnsMode.AllCells;
}
private void categoryDropDown_SelectedIndexChanged(object sender, EventArgs e)
{
Category category = (Category)this.categoryDropDown.SelectedItem;
try
{
productGridView.DataSource = category.Products;
productGridView.Columns["SupplierID"].Visible = false;
productGridView.Columns["CategoryID"].Visible = false;
productGridView.Columns["Category"].Visible = false;
productGridView.Columns["Order_Details"].Visible = false;
productGridView.Columns["Supplier"].Visible = false;
productGridView.AllowUserToDeleteRows = true;
productGridView.AutoResizeColumns();
productGridView.SelectionMode = DataGridViewSelectionMode.FullRowSelect;
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
private void ProductDetail_Load(object sender, EventArgs e)
{
newNorthWindContext = new NorthwindEntities();
productGridView.AutoSizeColumnsMode =
DataGridViewAutoSizeColumnsMode.AllCells;
IEnumerable<Category> categoryQuery = from category in newNorthWindContext.Categories.Include("Products")
orderby category.CategoryName
select category;
try
{
this.categoryDropDown.DataSource = ((ObjectQuery)categoryQuery).Execute(MergeOption.AppendOnly);
this.categoryDropDown.DisplayMember = "categoryName";
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
This solves the issue.
supplierDataGridView.Width = supplierDataGridView.Columns.GetColumnsWidth(DataGridViewElementStates.Visible)+4;
at the end of show_Click you should have something like
supplierDataGridView.Width = supplierDataGridView.Columns.Sum(x => x.Width) + supplierDataGridView.RowHeadersWidth + 2;
supplierDataGridView.Height = supplierDataGridView.GetRowDisplayRectangle(supplierDataGridView.NewRowIndex, true).Bottom + supplierDataGridView.GetRowDisplayRectangle(supplierDataGridView.NewRowIndex, false).Height;
I hope this helps!

How to call MessageBox within photochooser task

I have a code where I am calling photochooser in WP7 and I want to show a messagebox to user when the pic is more than 2Mb. When I try to do this, since the photochooser task is running in background, we start getting unhandled exceptions.
void photoChooserTask_Completed(object sender, PhotoResult e)
{
if (e.ChosenPhoto != null)
{
ProgressBar.Visibility = Visibility.Visible;
image = _UploadImgeViewModel.ReadToEnd(e.ChosenPhoto);
if (image.Length < 16384)
{
BitmapImage bi = new BitmapImage();
bi.SetSource(e.ChosenPhoto);
UserSession.ProfileImage = bi;
Session.PreviousImage = bi;
UserSession.isImageChanged = true;
UserSession.image = image;
UserSession.Uploadimage = image;
NavigationService.Navigated += new NavigatedEventHandler(navigateCompleted);
}
else
{
ProgressBar.Visibility = Visibility.Collapsed;
UserSession.isImageChanged = false;
UserSession.ProfileImage = null;
Dispatcher.BeginInvoke(() => MessageBox.Show("The message"));
}
}
}
#endregion
This only shows the background job as resuming... and the msg box in foreground. and after a few seconds, the app crashes.
Can you please help me with this?
Cool. I got some idea to resolve this. Might not be a fix, but this way we can avoid this issue. Just add a button and do the validating process in the button click event. Since we can't display the message box when the navigation is in progress.
Below is the code:
void photoChooserTask_Completed(object sender, PhotoResult e)
{
if (e.ChosenPhoto != null)
{
ProcessSelectedImage(e.ChosenPhoto);
}
}
private void ProcessSelectedImage(Stream stream)
{
if (stream != null)
{
bi.SetSource(stream);
UserSession.ProfileImage = bi;
UserSession.PreviousImage = bi;
image = ConvertToImage.ReadToEnd(stream);
UserSession.image = image;
UserSession.Uploadimage = image;
}
}
private void UploadImage_Click(object sender, RoutedEventArgs e)
{
if (image.Length < 16384)
{
UserSession.isImageChanged = true;
UserSession.image = image;
UserSession.Uploadimage = image;
NavigationService.Navigate(new Uri("/Views/EditMyProfile.xaml", UriKind.Relative));
}
else
{
UserSession.isImageChanged = false;
UserSession.ProfileImage = null;
UserSession.IsChangingProfilePicture = true;
MessageBox.Show(MessageContent.ImageUploadLengh);
}
}
Thanks
Kamal
You have 10 seconds to return to the foreground completely or your app will be killed. If you have a messagebox that can display here, you will fail certification (because user could not click anything for 10 seconds) -- you need to wait for the page to load.
A workaround for this if you need to show a MessageBox is to set a bool, and check it in the Page's Loaded event.
void photoChooserTask_Completed(object sender, PhotoResult e) { if (e.ChosenPhoto != null) { ProgressBar.Visibility = Visibility.Visible;
image = _UploadImgeViewModel.ReadToEnd(e.ChosenPhoto);
if (image.Length < 16384)
{
BitmapImage bi = new BitmapImage();
bi.SetSource(e.ChosenPhoto);
UserSession.ProfileImage = bi;
Session.PreviousImage = bi;
UserSession.isImageChanged = true;
UserSession.image = image;
UserSession.Uploadimage = image;
NavigationService.Navigated += new NavigatedEventHandler(navigateCompleted);
}
else
{
ProgressBar.Visibility = Visibility.Collapsed;
UserSession.isImageChanged = false;
UserSession.ProfileImage = null;
//set flag
UserSession.ImageTooBig = true;
}
}
}
#endregion
MyPage()
{
//make sure you attach Loaded Event if not already
Loaded += (s,e) =>
{
if (UserSession.ImageTooBig)
{
UserSession.ImageTooBig = false;
MessageBox.Show("Sorry, the image exceeds 2 MB");
}
};
}

Resources