Error connection timeout in Xamarin application - xamarin.forms

I am using flurl.http to call an api in xamarin.forms.
async void CallInspectiontype()
{
IList<dynamic> list = await "http://192.168.xxx.xx:8085/api/QMSon/GetInsp".GetJsonListAsync();
var modelList = new List<string>();
foreach (var item in list)
{
modelList.Add(item.Text);
}
InspectionTypePicker.ItemsSource = modelList;
}
it was running earlier but not now ! I don't no why that so ?
Flurl.Http.FlurlHttpException: occurred

I solved it's issue I ran visual Studio as Admin and check the internet Connectivity this worked fine for me !

Related

Xamarin Forms: Android Phone contacts is not listing

I am referring to this blog for listing the phone contacts. It is working fine on the ios part but on android part, the contacts are not listing. There are no exceptions or errors but the UI is blank.
As per the blog I have done the below things on the android platform:
created the model class Contact and interface IContactsService.
Added READ_CONTACTS permission and added ContactsService implementation.
Installed Plugin.CurrentActivity and Acr.UserDialogs packages.
Added Permission.Util class into the Android project.
Added required things on the MainActivity and ContactPage files on the Main project.
Don't know what I am missing on the android part, on ios it is working fine. On android, the contact permission is not asking during runtime. I manually add the permission from the app settings, but no luck. My Xamarin forms version: 4.8.0.1821
I am uploading a sample project here for reference.
Thanks in advance.
Got the answer from my Microsoft QA thread:
Android 10 does not use Android.Support.V4.Content.ContextCompat to request permission, so please use Xamarin.Essentials: Permissions to request runtime permission.
On ContactsViewModel.cs, add CheckAndContactsReadPermission()method in LoadContacts method like following code.
async Task LoadContacts()
{
try
{
await CheckAndContactsReadPermission();
await _contactService.RetrieveContactsAsync();
}
catch (TaskCanceledException)
{
Console.WriteLine("Task was cancelled");
}
}
public async Task<PermissionStatus> CheckAndContactsReadPermission()
{
var status = await Permissions.CheckStatusAsync<Permissions.ContactsRead>();
if (status == PermissionStatus.Granted)
return status;
if (status == PermissionStatus.Denied && DeviceInfo.Platform == DevicePlatform.iOS)
{
// Prompt the user to turn on in settings
// On iOS once permission has been denied it may not be requested again from the application
return status;
}
status = await Permissions.RequestAsync<Permissions.ContactsRead>();
return status;
}
On ContactsService.cs, change the LoadContactsAsync method like the following code.
async Task<IList<Contact>> LoadContactsAsync()
{
IList<Contact> contacts = new List<Contact>();
//var hasPermission = await RequestPermissionAsync();
//if (hasPermission)
//{
var uri = ContactsContract.Contacts.ContentUri;
var ctx = Application.Context;
await Task.Run(() =>
{
var cursor = ctx.ApplicationContext.ContentResolver.Query(uri, new string[]
{
ContactsContract.Contacts.InterfaceConsts.Id,
ContactsContract.Contacts.InterfaceConsts.DisplayName,
ContactsContract.Contacts.InterfaceConsts.PhotoThumbnailUri
}, null, null, $"{ContactsContract.Contacts.InterfaceConsts.DisplayName} ASC");
if (cursor.Count > 0)
{
while (cursor.MoveToNext())
{
var contact = CreateContact(cursor, ctx);
if (!string.IsNullOrWhiteSpace(contact.Name))
{
OnContactLoaded?.Invoke(this, new ContactEventArgs(contact));
contacts.Add(contact);
}
if (stopLoad)
break;
}
}
});
// }
return contacts;
}

MoveNext error using async with Xamarin forms

I have a Xamarin Android forms project using a CodeIgniter back end, with NuSoap.
I visual studio I created a .NET core project for testing, added a connected service to the server. Created a async task to pull the data from the server, this all worked correctly.
var client = new TbqService.ServicePortTypeClient();
var loginTask = Task.Run(() => client.logInAsync("user", "password"));
echoTask.Wait();
Console.WriteLine($"Login result {loginTask.Result}");
I then followed the same sequence for the Xamarin forms application but am getting the following error. I have seen comments about setting the SSL to TLS 1.2 and removing the bin/obj folder and rebuilding. Neither helped.
{System.NullReferenceException: Object reference not set to an instance of an object.
at MyThingApp.Models.DataConnect+<Login>d__13.MoveNext () [0x00023] in
D:\WebSites\TheMyThing_Projects\MyThingApp\MyThingApp\MyThingApp\Models\DataConnect.cs:31 }
Is there a different in the way the two work, should I be handling them differently?
public async Task<bool> Login(string email, string password)
{
try
{
var c = new TbqService.ServicePortTypeClient();
var result = await c.logInAsync(email, password); // line 31 in error
return result.Contains("true");
}
catch (Exception ex)
{
System.Diagnostics.Debug.WriteLine(ex);
}
return false;
}
It seems like result might be returning null. And so it crashes when you are trying to access contents inside result. Add a null check, and that should remove you error.
if (result != null)
return result.Contains("true");

Xamarin.Forms Azure DocumentDb Exception

I am using latest version of Microsoft.Azure.DocumentDB.Core (1.3.1.0) but keep getting an exception when trying to connect:
Example:
I create a Client Connection:
if (Client == null)
{
Client = new DocumentClient(new Uri(AppConstants.SUBSCRIPTION_URL),
AppConstants.PRIMARY_KEY);
}
And I try to query some data:
public async Task<List<Config>> GetAll()
{
var configs = new List<Config>();
var queryOptions = new FeedOptions { MaxItemCount = -1 };
var settings = Client.CreateDocumentQuery<Config>(UriFactory.CreateDocumentCollectionUri(AppConstants.COSMOS_DATABASE, COLLECTION_ID), queryOptions).AsDocumentQuery();
if (settings != null)
{
while(settings.HasMoreResults)
{
configs.AddRange(await settings.ExecuteNextAsync<Config>());
}
}
return configs;
}
And I get this error, even tough Settings is not null:
System.NullReferenceException: Object reference not set to an instance
of an object.
At first I thought its todo with the Client not being open so I tried adding:
await Client.OpenAsync();
But this has the same issue. Now running this same code in Asp.Net using the Web Client Nuget, The code runs perfectly.
Any ideas if recent changes to Xamarin or DocumentDB could be the cause or am I missing something else please?
Thanks,

Assembly.UnsafeLoadFrom causes web app crash

I am trying to load a DLL from internet, more specifically it is Azure storage (Blob), so I used "Assembly.UnsafeLoadFrom" like this:
Assembly.UnsafeLoadFrom(#"https://accountname.blob.core.windows.net/test/calculator.dll");
But becuaset this specific call, my web app (published) returns:
"The specified CGI application encountered an error and the server
terminated the process."
The weird part is if I am using my local build, it is fine. there is no crash and the return result is correct.
I am using Visual Studio 2015 and .net 5.
Please let me know how to resolve this issue or how to debug it.
Thanks
For a simple way, you could achieve your purpose by the following code:
calculator.dll
public class Calculator
{
public string HelloWorld(string userName)
{
return string.Format("Hello world, {0}!", userName);
}
}
HomeController.cs
public async Task<ActionResult> Index()
{
string url = "https://brucechen.blob.core.windows.net/dll/calculator.dll";
HttpClient client = new HttpClient();
var bytes = await client.GetByteArrayAsync(url);
//load assembly from bytes
Assembly assembly = Assembly.Load(bytes);
var calc = assembly.CreateInstance("calculator.Calculator");
//invoke the method and get result
var result = calc.GetType().InvokeMember("HelloWorld", BindingFlags.InvokeMethod, null, calc, new[] { "Bruce" });
ViewData["result"] = result;
return View();
}
Result

Using speech synthesizer in ASP.NET web application gets stuck

In an MVC web application I use the SpeechSynthesizer class to speak some text to a .wav file during a function called by a controller action handler that returns a view. The code executes, writes the file, and the action handle returns, but the development server usually, but not always, never comes back with the return page. This is the text-to-speech code:
string threadMessage = null;
bool returnValue = true;
var t = new System.Threading.Thread(() =>
{
try
{
SpeechEngine.SetOutputToWaveFile(wavFilePath);
SpeechEngine.Speak(text);
SpeechEngine.SetOutputToNull();
}
catch (Exception exception)
{
threadMessage = "Error doing text to speech to file: " + exception.Message;
returnValue = false;
}
});
t.Start();
t.Join();
if (!returnValue)
{
message = threadMessage;
return returnValue;
}
I saw a couple of posts for a similar problem in a service that advised doing the operation in a thread, hence the above thread.
Actually, using the SpeechSynthesizer for other things can hang as well. I had a page that just enumerated the voices, but it would get stuck as well. Since there is no user code in any of the threads if I pause the debugger, I have no clue how to debug it.
I've tried Dispose'ing the SpeechSynthesizer object afterwards, calling SetOutputToDefaultVoice, to no avail. I've tried it on both Windows 8.1 and Windows 8, running with the development server under the debugger, or running IIS Express separately.
Any ideas? Is there other information I could give that would be helpful?
Thanks.
-John
Try
Public void Speak(string wavFilePath, string text)
{
using (var synthesizer = new SpeechSynthesizer())
{
synthesizer.SetOutputToWaveFile(wavFilePath);
synthesizer.Speak(text);
return outputFile;
}
}
Task.Run(() => Speak("path", "text")).Result;
It worked for me in IIS Express

Resources