FilePicker class cannot be found in Xamarin project - xamarin

I'm creating a Xamarin forms app which enables user uploads. I have installed the latest version of the Xamarin.Essentials package but the classes and methods which I would expect to be available cannot be found. I can move ahead with the xamarin.plugins.filepicker package but this is not well documented and I would prefer to use the standard library. Any assistance with this would be greatly appreciated! The default is below.
'''
async Task<FileResult> PickAndShow(PickOptions options)
{
try
{
var result = await FilePicker.PickAsync();
if (result != null)
{
Text = $"File Name: {result.FileName}";
if (result.FileName.EndsWith("jpg", StringComparison.OrdinalIgnoreCase) ||
result.FileName.EndsWith("png", StringComparison.OrdinalIgnoreCase))
{
var stream = await result.OpenReadAsync();
Image = ImageSource.FromStream(() => stream);
}
}
}
catch (Exception ex)
{
// The user canceled or something went wrong
}
}
'''

For the Xamarin.Essentials package, update to the latest version on both Xamarin.Form NuGet Package and Android NuGet Package. After that you could fix the errors like below.
Error CS0246 The type or namespace name 'PickOptions' could not be found (are you
missing a using directive or an assembly reference?)
For the usage of Xamarin.Essentials: File Picker, you could check the MS document.
https://learn.microsoft.com/en-us/xamarin/essentials/file-picker?tabs=android
If you wanna the source file, you could download from the link below. https://github.com/xamarin/Essentials/tree/main/Xamarin.Essentials/FilePicker

Related

How to download and open a file with NS 6.0

I'have migrate to NativeScript 6.0 and need some help on how to download and open a file with Android support lib (AndroidX) in the Downloads folder.
Actually, in NS 5.x, i have used FileProvider from Android support lib (android.support.v4.content.FileProvider) and works great. After the migration, using (androidx.core.content.FileProvider), i have errors opening the App.
But in Android docs, i can't find any method or information to migrate the code for Native download and Open (Downloads Folder).
Previous Method:
private openFile(fileName: string, mimeType: string, extension: string) {
try {
if (isAndroid) {
const intent = new android.content.Intent(android.content.Intent.ACTION_VIEW);
const context = applicationModule.android.context;
console.log("android.ctx=", context);
const nativeFile = new java.io.File(fileName);
console.log("nativeFile=", nativeFile);
const uri = android.support.v4.content.FileProvider.getUriForFile(context, "com.otisw.gescon.app.provider", nativeFile);
intent.setDataAndType(uri, mimeType);
intent.addFlags(android.content.Intent.FLAG_GRANT_READ_URI_PERMISSION);
const choosedIntent = android.content.Intent.createChooser(intent, "Open file...");
console.log("choosedIntent=>", choosedIntent);
context.startActivity(choosedIntent);
} else {
// const documents = fs.knownFolders.currentApp();
// const file = this.documents.getFile(fileName);
const open = utils.ios.openFile(fileName);
}
} catch (e) {
console.log(e);
}
}
Tried:
private openFile(fileName: string, mimeType: string, extension: string) {
try {
if (isAndroid) {
const intent = androidx.core.content.IntentCompat.makeMainSelectorActivity(
"android.content.Intent.ACTION_VIEW",
"??"
);
File reference.d.ts:
/// <reference path="./node_modules/tns-core-modules/tns-core-modules.d.ts" />
/// <reference path="./node_modules/tns-platform-declarations/ios.d.ts" />
/// <reference path="./node_modules/tns-platform-declarations/android/androidx-26.d.ts" />
Does anyone tries to upgrade the code for Download and Open from NativeScript to new AndroidX or knows a workaround to do this ?
Thanks!
You will have to use androidx.core.content.FileProvider on AndoridX and android.support.v4.content.FileProvider in lower versions.
With the release of Android 9.0 (API level 28) there is a new version
of the support library called AndroidX which is part of Jetpack. The
AndroidX library contains the existing support library and also
includes the latest Jetpack components.
You can continue to use the support library. Historical artifacts
(those versioned 27 and earlier, and packaged as android.support.*)
will remain available on Google Maven. However, all new library
development will occur in the AndroidX library.
We recommend using the AndroidX libraries in all new projects. You
should also consider migrating existing projects to AndroidX as well.

Unable to load DLL 'e_sqlite3': The specified module could not be found

I have a Xamarin Forms solution. I added sqlite-net-pcl as reference to all projects. It works fine on Android but crashes on Windows 8.1 and Windows Phone 8.1. I have an IOS project but I don't have OSX at the moment to try it.
I use this in the Windows projects to access the database:
using System.IO;
using SQLite;
using Xamarin.Forms;
using HelloXamarin.Windows;
using Windows.Storage;
[assembly: Dependency(typeof(SQLiteDb))]
namespace HelloXamarin.Windows
{
public class SQLiteDb : ISQLiteDb
{
public SQLiteAsyncConnection GetConnection(string databaseName)
{
var documentsPath = ApplicationData.Current.LocalFolder.Path;
var path = Path.Combine(documentsPath, databaseName);
return new SQLiteAsyncConnection(path);
}
}
}
Here are my references:
I get this exception when trying to access the database:
The type initializer for 'SQLite.SQLiteConnection' threw an exception.
Unable to load DLL 'e_sqlite3': The specified module could not be found. (Exception from HRESULT: 0x8007007E)
at SQLitePCL.SQLite3Provider_e_sqlite3.NativeMethods.sqlite3_win32_set_directory(UInt32 directoryType, String directoryPath)
at SQLitePCL.SQLite3Provider_e_sqlite3..ctor()
at SQLitePCL.Batteries_V2.Init() at SQLite.SQLiteConnection..cctor()
I have no idea how to solve this, please help me!
The whole solution is available on GitHub:
https://github.com/apspot/HelloXamarin
For me, it worked by adding the e_sqlite3 bundle to the executable project
By this time the issue is still open. So before they come with some solid fix, you can use this work around, to solve the issue for now.
Add one helper class
using System;
using System.Diagnostics;
using System.IO;
namespace SQLitePCL
{
public class NativeLibraryHack
{
public static bool Hacked { get; private set; }
public static bool DoHack()
{
if (Hacked) return true;
try
{
const string runtimeFolderName = "/runtimes";
var destinationPath = typeof(SQLitePCL.raw).Assembly.Location
.Replace("\\", "/");
var destinationLength = destinationPath.LastIndexOf("/", StringComparison.OrdinalIgnoreCase);
var destinationDirectory = destinationPath.Substring(0, destinationLength) + runtimeFolderName;
var sourcePath = new Uri(typeof(SQLitePCL.raw).Assembly.CodeBase)
.AbsolutePath;
var sourceLength = sourcePath.LastIndexOf("/", StringComparison.OrdinalIgnoreCase);
var sourceDirectory = sourcePath.Substring(0, sourceLength) + runtimeFolderName;
if (Directory.Exists(sourceDirectory))
CopyFilesRecursively(new DirectoryInfo(sourceDirectory), new DirectoryInfo(destinationDirectory));
}
catch (Exception ex)
{
//Ignore Exception
Debug.WriteLine(ex.Message);
return false;
}
return (Hacked = true);
}
private static void CopyFilesRecursively(
DirectoryInfo source,
DirectoryInfo target
)
{
foreach (var dir in source.GetDirectories())
CopyFilesRecursively(dir, target.CreateSubdirectory(dir.Name));
foreach (var file in source.GetFiles())
{
try
{
var destinationFile = Path.Combine(target.FullName, file.Name);
if (!File.Exists(destinationFile))
file.CopyTo(destinationFile);
}
catch (Exception ex)
{
//Ignore Exception
Debug.WriteLine(ex.Message);
}
}
}
}
}
And add the hack before your db migration script, I am using web api 2
so i did on RouteConfig.RegisterRoutes
NativeLibraryHack.DoHack();
using (KSDBContext db = new KSDBContext())
{
db.Database.Migrate();
}
You need to add the SQLite Extensions.
Go to Tools > Extensions and Updates
Go to Online, then search for SQLite.
Download SQLite for Windows Runtime
In your Windows Project, Add Reference and ensure you add the extension.
Also remove Microsoft.VCLibs from your references.
Try referencing Visual C++ 2015 Runtime for Universal Windows Platform Apps. That sorted it out for me.
Go to References
Add Reference
Extensions.
Check"Visual C++ 2015 Runtime for Universal Windows Platform Apps"
OK

Xamarin Forms HttpClient GetAsync Fails in iOS Only

I have a very simple REST query to our WebAPI back end (used by a number of applications) and it works fine under Android and Windows but in iOS it fails with an "Object reference not set to an instance of an object" error. In the code below, both moHttpClient and loUri are instantiated. I've tried wrapping the call to GetEmployeeRecord in Device.BeginInvokeOnMainThread but that doesn't help either. I have upgraded to the latest stable version of Xamarin in Visual Studio and on my Mac. Why is it working in the other OSs but not iOS?
private async void btnTest_Clicked(object sender, EventArgs e)
{
await GetEmployeeRecord();
}
private async Task GetEmployeeRecord()
{
try
{
var loUri = new Uri("https://my.website.com/mobile.webapp/api/employees?key=6c6f2c06-a444-4e54-bd77-b5f594c29910");
var loResponse = await moHttpClient.GetAsync(loUri);
if (loResponse.IsSuccessStatusCode)
{
var lcJson = await loResponse.Content.ReadAsStringAsync();
await DisplayAlert("Employee", lcJson, "OK");
}
}
catch (Exception ex)
{
Device.BeginInvokeOnMainThread(() =>
{
DisplayAlert("Get Employee Record", ex.Message, "OK");
});
}
}
Using a breakpoint at the GetAsync line, both moHttpClient and loUri are instantiated. However, mousing over GetAsync gives a message that GetAsync is an unknown member. How can that be?
I just checked and it seems this Unknown member occurs with Android too. But with Android it actually executes.
In order to get the http query to work for iOS I had to install the NuGet package Microsoft.Net.Http in the PCL project, which is where the code is running.

Open Uri to read JSON file in background task UWP

I have a use case where I have to read a config.json file from an AppService and based on the configuration in json file I have to generate an ID.
I am using following piece of code to generate the Uri so that I can open the file using StorageFile.GetFileFromApplicationUriAsync(fileUri).
Uri fileUri = null;
try
{
Debug.WriteLine("Creating new uri");
fileUri = new Uri(fileName);
if (fileUri == null)
{
Debug.WriteLine("Uri creation failed");
} else
{
Debug.WriteLine("New Uri created");
}
} catch (Exception ex)
{
Debug.WriteLine("Uri creation failed" + ex.Message);
}
Now when I am trying to debug this code my debugger is disappearing after line with new Uri(fileName)
If I just let the code run with no breakpoints I am not seeing any message after Creating new uri. Not even an exception.
Value of fileName is "ms-appx:///config/config.json"
Can anyone please explain what is wrong here? Also is it possible to open and read a file from an AppService?
--
Thanks
Tarun
The uri use appx only can read the resource is content in msbuild.
You can right click the file and select the property and you should select the file's build action as content.
http://jycloud.9uads.com/web/GetObject.aspx?filekey=449e34647d61faca2ce846b773a4da8e
http://jycloud.9uads.com/web/GetObject.aspx?filekey=5423b79037eee8dc66431d0478d79871
http://jycloud.9uads.com/web/GetObject.aspx?filekey=6189eb9547c6f2fa79333df67ab33cef
You can see the last image is use complie and you can change it to content.
Sorry, my visual studio's language is local language.But the visual studio's have the same layout.

Error while using 'google-api-dotnet-client' to access FusionTables

I am trying to work with FusionTables API. But I am getting this error:
Method 'get_Error' in type 'Google.Apis.Fusiontables.v1.Data.Table'
from assembly 'Google.Apis.Fusiontables.v1, Version=1.2.4737.25287,
Culture=neutral, PublicKeyToken=null' does not have an implementation.
Can some one please help me with this error? Here is my code:
// Create the service.
if (fTableService == null)
{
// Register the authenticator.
var auth = CreateAuthenticator();
fTableService = new FusiontablesService(auth);
if (fTableService != null)
{
name = fTableService.Table.List().Fetch().Items[0].Name;
}
}
Thanks
It looks like you mix between assemblies versions (of the generated API and of the google client library itself).
Try to download the latest version of FusionTables API from http://code.google.com/p/google-api-dotnet-client/wiki/APIs#Fusion_Tables_API.
The bundle contains all the dlls you need to reference.
Good luck

Resources