DisplayActionSheet throws exception only in xamarin ios - ios

DisplayActionSheet throw me in catch block with Exception null only in Ios
private string signType = string.Empty;
signType = await Application.Current.MainPage.DisplayActionSheet(SystemMessages.PhotoSaveFolder, "Cancel",
null, SystemMessages.InstallationPhoto, SystemMessages.SerialNumbers);
there is no issue in android.
Can anybody know what can cause this.
thanks in advance.

Have a look at below sample code
private async void Btn_Clicked(object sender, EventArgs e)
{
string str = string.Empty;
str = await DisplayActionSheet("Title", "Cancel",
null, "Action1", "Action2");
}
}
And use it on any button clicked event
btn.Clicked += Btn_Clicked;
Or you can create any simple method and call it. This works for me.

Try like below it will work for you
Device.BeginInvokeOnMainThread (() =>
{
string str = string.Empty;
str = await DisplayActionSheet("Title", "Cancel",
null, "Action1", "Action2");
});

I fixed this issue. it is because i was trying to open displayactionsheet from page2 which is redirected from page1. and after navigation i removed page 1 from stack.so it causing this problem.
Thank you all for your valuable time and Help.

Related

Xamarin iOS System.FormatException: Input string was not in a correct format

I'm facing a weird issue in iOS 13.3 and 13.4 that having System.FormatException for some users only. The app is develop using Xamarin Forms.
The error happen after calling to backend API to get user profile but before reaching the backend API (verified not reaching because AppInsights trace logs is not showing the call).
I have check the places where the error might be happening but have no clue.
Exception Stack Trace recorded in AppCenter
System.FormatException: Input string was not in a correct format.
System.Text StringBuilder.FormatError ()
System.Text StringBuilder.AppendFormatHelper (System.IFormatProvider provider, System.String format, System.ParamsArray args)
System String.FormatHelper (System.IFormatProvider provider, System.String format, System.ParamsArray args)
System String.Format (System.String format, System.Object[] args)
Mobile.Services ApiService.GetAsync[T] (Wipro.MyBAT.Mobile.Core.Logging.AnalyticsEvent analyticsEvent, System.String endPoint, System.String queryString, System.Boolean requiresAuthentication, System.Threading.CancellationToken cancelToken, System.Boolean withRetry)
Mobile.Services ApiService.GetUserProfile ()
Mobile.Services.Users UserService.GetUserProfileFromServer ()
Get User Profile method
public async Task<Response<Common.Model.User>> GetUserProfile()
{
var result = await GetAsync<Response<Common.Model.User>>(AnalyticsEvent.UserProfilePerformance, Endpoints.PROFILE).ConfigureAwait(false);
return result;
}
Get User Profile method
private async Task<T> GetAsync<T>(AnalyticsEvent analyticsEvent, string endPoint, string queryString = "", bool requiresAuthentication = true, CancellationToken cancelToken = default, bool withRetry = true)
where T : new()
{
Stopwatch stopwatch = new Stopwatch();
var dict = new Dictionary<string, string>
{
{ "Throttler count", _throttler.CurrentCount.ToString() },
{ "Throttler limit", THROTTLER_LIMIT.ToString() },
{ "Retry", (!withRetry).ToString() }
};
await _throttler.WaitAsync();
stopwatch.Start();
string callId = System.Guid.NewGuid().ToString();
string url;
string responseString = string.Empty;
try
{
if (_connectivity.NetworkAccess == Xamarin.Essentials.NetworkAccess.None || _connectivity.NetworkAccess == Xamarin.Essentials.NetworkAccess.Unknown)
{
return default(T);
}
url = $"{_environment.HostUrl}/api/{endPoint}{queryString}";
HttpRequestMessage message = new HttpRequestMessage(HttpMethod.Get, url);
if (requiresAuthentication)
{
var token = await _authService.GetAccessToken();
message.Headers.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("bearer", token);
message.Headers.Add("callid", callId);
}
// Error should be before this line as the call it not reaching API side
HttpResponseMessage response = await _httpClient.SendAsync(message, cancelToken);
Finally found the root cause of the problem. It is actually calling to the API server but is throwing exception before leaving mobile due to the user is having some VPN in the wifi network. Changing to use 4G instead of Wifi solve the problem.
The String.Format issue is due to the exception handling code using string.Format incorrectly. This makes the actual issue cover up by the string.format exception.
2 things learned:
Always check first if using another network solve the problem or not
Handle exception correctly

Place AutoComplete Prediction

I am getting no response. What am i missing?
Can anyone give me an idea on it. Having error.
IPlacesClient placesClient = PlacesApi.CreateClient(CrossCurrentActivity.Current.Activity);
PlacesApi.Initialize(CrossCurrentActivity.Current.Activity, "********API KEY***************");
var token = AutocompleteSessionToken.NewInstance();
var request = FindAutocompletePredictionsRequest.InvokeBuilder()
.SetSessionToken(token)
.SetTypeFilter(TypeFilter.Establishment)
.SetCountry("US")
.SetQuery("Ind")
.Build();
Task<FindAutocompletePredictionsResponse> task = placesClient.FindAutocompletePredictions(request);
You can refer to https://github.com/xamarin/XamarinComponents/blob/master/Android/GooglePlaces/samples/PlacesSample/MainActivity.cs
You were in the right way.
You must add an Action to your task.
task.AddOnSuccessListener(CrossCurrentActivity.Current.Activity, this);
task.AddOnFailureListener(CrossCurrentActivity.Current.Activity, this);
Then, add code to each one of this Actions
public void OnSuccess(Java.Lang.Object result)
{
//Do something
}
public void OnFailure(Java.Lang.Exception e)
{
//Failed
}
Remember to implement IOnSuccessListener, IOnFailureListener and IOnCompleteListener

IsNullOrEmtpy is not responding,app gives me a crash

I want to alert a user if he forgets to enter his code to login in Xamarin android.As title, it is crash everytime.What is my error? This is my code.
void OnUserClick(object sender, EventArgs e)
{
int code = int.Parse(FindViewById(Resource.Id.codeInput).Text);
EditText codeinput = FindViewById<EditText>(Resource.Id.codeInput);
if (string.IsNullOrEmpty(codeinput.Text))
{
AlertDialog.Builder alertDialog = new AlertDialog.Builder(this);
alertDialog.SetTitle("waring");
alertDialog.SetMessage("enter information");
alertDialog.SetNeutralButton("OK", delegate
{
alertDialog.Dispose();
});
alertDialog.Show();
}
Please check the following code.
int code = int.Parse(FindViewById(Resource.Id.codeInput).Text);
Since we have use the following code
EditText codeInput = FindViewById<EditText>(Resource.Id.codeInput);
If we not enter the input which can't convert to int, then the app will crash.
So you could delete the code or comment out this line of code.

compilation Error in Task.ContinueWith when passing TaskScheduler.FromCurrentSynchronizationContext as second parameter

private void CountWithTask_Click(object sender, RoutedEventArgs e)
{
lblOutput.Content = "file is in processing...";
var taskInt = CountWords();
taskInt.ContinueWith(x =>
{
MessageBox.Show("process has been done.");
lblOutput.Content = $"count of words in file are :- {x.Result}";
},TaskScheduler.FromCurrentSynchronizationContext);
}
}
in the code snippet where I have return "x.Result",I am getting the compilation error at that point. and the error is image 1
"Task does not contain a definition for 'result' and no extension method 'Result' accepting a first argument of type 'Task' could be found (are you missing a using directive or an assembly refernce?)"
if I remove that line then it is giving error at TaskScheduler, and the error is
"Argument 2: cannot convert from 'method-group' to Cacellationtoken."
enter image description here
code for the CountWords method:
public async Task<int> CountWords()
{
Debug.WriteLine(string.Format($"Thread ID: {Thread.CurrentThread.ManagedThreadId.ToString()}"));
await Task.Delay(2000);
int count;
StreamReader reader = new StreamReader(FileName);
var str = await reader.ReadToEndAsync();
count = str.Length;
reader.Close();
return count;
}
I got the issue the issue was very small my mistake and my negligence towards the intelligence. :)
I am using only "TaskScheduler.FromCurrentSynchronizationContext", which is wrong becuase "FromCurrentSynchronizationContext" is a method and it should be like this "TaskScheduler.FromCurrentSynchronizationContext()".
Proper code would be this :
private void CountWithTask_Click(object sender, RoutedEventArgs e)
{
lblOutput.Content = "file is in processing...";
var taskInt = CountWords();
taskInt.ContinueWith(x =>
{
MessageBox.Show("process has been done.");
lblOutput.Content = $"count of words in file are :- {x.Result}";
},TaskScheduler.FromCurrentSynchronizationContext());
}
}
Thanks for the response #scott.
Thanks Stackoverflow. :)

Click handler not working, possible unintended reference comparison

this doesnt work ,i have an item "Area" in my listBox1,but code is not producing MessageBox in wp7 runtime,
private void button1_Click(object sender, RoutedEventArgs e)
{
if( listBox1.SelectedItem=="Area")
{
MessageBox.Show("hi");
}
}
try:
listBox1.SelectedItem as string == "Area"
You are missing the cast.

Resources