Xamarin form : How to select multiple files form filepicker - xamarin.forms

i have developed to pick file form mobile, but need to pickup multpple file here is my code
try
{
FileData fileData = await CrossFilePicker.Current.PickFile();
if (fileData == null)
return; // user canceled file picking
string fileName = fileData.FileName;
string contents = System.Text.Encoding.UTF8.GetString(fileData.DataArray);
System.Console.WriteLine("File name chosen: " + fileName);
System.Console.WriteLine("File data: " + contents);
}
catch (Exception ex)
{
System.Console.WriteLine("Exception choosing file: " + ex.ToString());
}
need to know how i can select multiple files

You can use Xamarin Essentials FilePicker to select multiple files.It is stable now and support Android,iOS and UWP.
https://learn.microsoft.com/en-us/xamarin/essentials/file-picker?tabs=android

Related

Cannot open passkit file created in the server using dotnet-passbook v3.0.2

I have recently come across an issue that I cannot open my Pkpass which is created using dotnet-passbook version 3.2.0.
The Pkpass created locally can be opened fine and the issue is with the Pkpass created in the server.
I have even tried to upload the Pkpass from the server to the validator but the validator just returns “Failed to process the Pkpass file.”
Below is my code snapshot for building the Pkpass:
public static FileContentResult GetPass(Shopper account)
{
try {
if (account == null)
{
return null;
}
PassGenerator generator = new PassGenerator();
PassGeneratorRequest request = new PassGeneratorRequest();
// "webServiceURL" : "https://example.com/passes/",
// "authenticationToken" : "vxwxd7J8AlNNFPS8k0a0FfUFtq0ewzFdc",
// Product info
request.PassTypeIdentifier = "PassTypeIdentifier";
request.TeamIdentifier = "TeamIdentifier";
request.SerialNumber = "SerialNumber";
request.Description = "Description";
request.OrganizationName = "OrganizationName";
request.LogoText = "LogoText";
// Add the installed certificate and it's thumbprint
WebClient webClient = new WebClient();
try
{
X509KeyStorageFlags flags = X509KeyStorageFlags.MachineKeySet | X509KeyStorageFlags.Exportable;
request.PassbookCertificate = new X509Certificate2(webClient.DownloadData(CertificatesBucket + "/Certificates.p12"), S3_AppleCertificatePassword, flags);
}
catch (Exception e)
{
throw new Exception("Error occurs when geting certificate: " + e.Message);
}
// Add Apple's WWDRCA certificates
try
{
request.AppleWWDRCACertificate = new X509Certificate2(webClient.DownloadData(CertificatesBucket + "/AppleWWDRCAG2.cer"));
}
catch (Exception e)
{
throw new Exception("Error occurs when geting AppleWWDRCCA: " + e.Message);
}
// override icon and icon retina
try
{
request.Images.Add(PassbookImage.Logo, webClient.DownloadData(AppleImageBucket + "/logo.png"));
request.Images.Add(PassbookImage.Icon, webClient.DownloadData(AppleImageBucket + "/icon.png"));
request.Images.Add(PassbookImage.Icon2X, webClient.DownloadData(AppleImageBucket + "/icon%402x.png"));
request.Images.Add(PassbookImage.Strip, webClient.DownloadData(AppleImageBucket + "/strip.png"));
request.Images.Add(PassbookImage.Strip2X, webClient.DownloadData(AppleImageBucket + "/strip%402x.png"));
}
catch (Exception e)
{
throw new Exception("Error occurs when geting images: " + e.Message);
}
// Add barcode
request.AddBarcode(BarcodeType.PKBarcodeFormatCode128, account.Id, "ISO-8859-1");
// Link the pass to an existing app using the app's Apple ID.
request.AssociatedStoreIdentifiers.Add(121212);
request.Style = PassStyle.StoreCard;
// Add fields
request.AddHeaderField(new StandardField("StandardField", "TEXT", account.Id));
request.AddSecondaryField(new StandardField("StandardField", "TEXT", account.Name));
request.AddSecondaryField(new StandardField("StandardField", "TEXT", "TEXT"));
request.TransitType = TransitType.PKTransitTypeAir;
byte[] generatedPass = generator.Generate(request);
//throw new Exception("apple generatedPass: " + JsonTransHelper.SerializeObject(generatedPass));
return new FileContentResult(generatedPass, "application/vnd.apple.pkpass");
}
catch (Exception ex)
{
throw new Exception("Error occurs when creating apple pass: " + ex.Message);
}
}
}
}
Any help greatly appreciated!
It is caused by AWS API Gateway. If you running this on a Lambda function try to invoke it directly.
Offset to Central Directory cannot be held in an Int64 .net core

Unable to attach file to Email in Android 10

I am trying to attach pdf to Gmail using file provider. It is working on Android 6.0 but says 'Couldn't attach file'
fun startFileShareIntent(filePath: String, context: Context?) {
try {
val file = File(filePath)
val uri = FileProvider.getUriForFile(context!!, "com.trust.inspakt.android.provider", file)
val intent = ShareCompat.IntentBuilder.from(context as Activity)
.setType("application/pdf")
.setStream(uri)
.setChooserTitle("Choose bar")
.createChooserIntent()
.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION)
context.startActivity(intent)
} catch (e: Exception) {
e.printStackTrace()
}
}
I assume from your question that it is working on Android 7.0 and up?
In Android 6.0 there is no need for a file provider. Here is the Java code that I am using to attach a csv file to gmail. This works for me from Android 6.0 up to Android 11.
/* This is the filename or file URI, depending on what Android version you have
and how you got the filename */
String fileInfo;
final Intent emailIntent = new Intent(Intent.ACTION_SEND);
emailIntent.setType("message/rfc822");
emailIntent.putExtra(Intent.EXTRA_EMAIL,"example#gmail.com");
emailIntent.putExtra(Intent.EXTRA_SUBJECT,"subject");
emailIntent.putExtra(Intent.EXTRA_TEXT,emailBody);
//add file to email according to build type
if (Build.VERSION.SDK_INT>=Q){
Uri path = Uri.parse(fileInfo);
emailIntent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
emailIntent.putExtra(Intent.EXTRA_STREAM, path);
}
else if (Build.VERSION.SDK_INT>M) {
File test_result = new File(fileInfo);
String authority = context.getApplicationContext().getPackageName() + ".provider";
Uri path = FileProvider.getUriForFile(context.getApplicationContext(),authority,test_result);
emailIntent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
emailIntent.putExtra(Intent.EXTRA_STREAM, path);
}
else {
File test_result = new File(fileInfo);
Uri path = Uri.fromFile(test_result);
emailIntent.putExtra(Intent.EXTRA_STREAM, path);
}
//send email
context.startActivity(emailIntent);

Xamarin forms how to Get existing local database

How do you Get an existing database from a device or emulator ?
device not rooted
I'm using Microsoft.WindowsAzure.MobileServices
public bool InitialiseDb()
{
try
{
Store = new MobileServiceSQLiteStore(offlineDbPath);
Store.DefineTable<Products>();
_client.SyncContext.InitializeAsync(Store);
this.productTable = _client.GetSyncTable<Products>();
return true;
}
catch (Exception ex)
{
Debug.WriteLine(ex.Message);
return false;
}
}
You can copy the existing database into a folder you can access
Create path to database :
string filepath = "data/data/[package-name]/files/[name-of-db]";
You can get your package name from your android project options
then use the following code to extract it:
string filepath = "data/data/com.foo.foo/files/localstorage.db";
var bytes = System.IO.File.ReadAllBytes(filepath);
var fileCopyName = string.Format("/sdcard/Database_{0:dd-MM-yyyy_HH-mm-ss-tt}.db", System.DateTime.Now);
System.IO.File.WriteAllBytes(fileCopyName, bytes);

Crystal report display no data although the DataSet is set using push method

I'm new to crystal report. I'm facing an issue that my report show no data although the dataset showed it did have data during debugging. I noticed that everything went wrong after the line " m_rptViewReport.SetDataSource(ds); ", it show "HasRecords = Function evaluation disabled because a previous function evaluation timed out. You must continue execution to reenable function evaluation crystal reports"
Basically, I'm trying to export the data to xls file using push method. I'm using VS2015 and my crystal report assembly version is 13.0.3500.0
Pls take a look at my code
public bool ExportToFile(DataSet ds,string fileType)
{
try
{
object obj = null;
char[] split ={ '.' };
CrystalDecisions.CrystalReports.Engine.ReportDocument m_rptViewReport = null;
if (File.Exists(Request.PhysicalApplicationPath + "\\" + this.ReportFile))
{
try {
m_rptViewReport = new CrystalDecisions.CrystalReports.Engine.ReportDocument();
m_rptViewReport.Load(Request.PhysicalApplicationPath + "\\" + this.ReportFile);
ds.WriteXml("D:\\testfile.XML", XmlWriteMode.WriteSchema); //the output XML file does have data
m_rptViewReport.SetDataSource(ds);//something went wrong after this line
}
catch (Exception ex) //nothing happened here
{
throw ex;
}
}
else
this.SetTextTitle(Resources.GetLanguage("msgNoFile") + " " + this.ReportFile);
if (m_rptViewReport.HasRecords){ //I added this line later and founded that the value is not TRUE
if (m_rptViewReport != null)
{
SetReportParameterValue(m_rptViewReport);
Response.ContentType = "application/vnd.ms-excel";
try {
m_rptViewReport.ExportToHttpResponse(CrystalDecisions.Shared.ExportFormatType.Excel, Response, true, this.ReportCode);
}
catch (System.Threading.ThreadAbortException ex1)
{
//throw ex1;
}
}
}
return true;
}
catch(Exception ex)
{
return false;
}
}
any help would be appreciated.
<CR:CrystalReportViewer ID="CrystalReportViewer1" runat="server" AutoDataBind="True" GroupTreeImagesFolderUrl="" Height="1202px" ToolbarImagesFolderUrl="" ToolPanelWidth="200px" Width="1104px" />
Can you please try removing the datasource of the report from the UI, donot specify the report datasource in the crystal report viewer.
Use the above sample code and remove the Reportdatasource etc, and try now.

Cannot upload files from android to asp.net server using Cordova FileTransfer plugin

I have a simple mobile app created using cordova file transfer plugin. Below is the upload code
function uploadPhoto(fileURI) {
var options = new FileUploadOptions();
options.fileKey = fileURI.substr(fileURI.lastIndexOf('/') + 1);
options.fileName = fileURI.substr(fileURI.lastIndexOf('/') + 1);
if (cordova.platformId == "android") {
options.fileName += ".jpg"
}
options.mimeType = "image/jpeg";
//options.contentType = 'multipart/form-data';
options.params = {}; // if we need to send parameters to the server request
options.headers = {
Connection: "Close"
};
//options.httpMethod = 'POST';
//options.chunkedMode = false;
var ft = new FileTransfer();
rst.innerHTML = "Upload in progress...";
ft.upload(
fileURI,
encodeURI("http://localhost:55013/virtualroomservice.asmx/SaveImage"),
onFileUploadSuccess,
onFileTransferFail,
options, true);
function onFileUploadSuccess (result) {
// rst.innerHTML = "Upload successful";
console.log("FileTransfer.upload");
console.log("Code = " + result.responseCode);
console.log("Response = " + result.response);
console.log("Sent = " + result.bytesSent);
console.log("Link to uploaded file: https://www.kinrep.com/foster/ws/contentlibrary" + result.response);
var response = result.response;
var destination = "https://www.kinrep.com/foster/WS/ContentLibrary" + response.substr(response.lastIndexOf('=') + 1);
if(this.id == 'uploadcheque') {
document.getElementById("hdnchequeimgpath").value = destination;
} else if(this.id == 'uploaddoorlock') {
document.getElementById("hdndoorlockedimgpath").value = destination;
} else {
document.getElementById("hdnothersimgpath").value = destination;
}
rst.innerHTML = "File uploaded to: " +
destination +
"</br><button class=\"button\" onclick=\"window.open('" + destination + "', '_blank', 'location=yes')\">Open Location</button>";
//document.getElementById("downloadedImage").style.display="none";
}
function onFileTransferFail (error) {
rst.innerHTML = "File Transfer failed: " + error.code;
console.log("FileTransfer Error:");
console.log("Code: " + error.code);
console.log("Source: " + error.source);
console.log("Target: " + error.target);
}
}
Below is the server code
[WebMethod]
[ScriptMethod]
public string SaveImage()
{
try
{
HttpPostedFile file = HttpContext.Current.Request.Files[0];
if (file == null)
return "0";
string targetFilePath = Server.MapPath(#"WS\ContentLibrary") + file.FileName;
file.SaveAs(targetFilePath);
}
catch (Exception ex)
{
string s = ex.Message;
return s;
}
return "1";
}
When the call gets invoked it is getting inside SaveImage webmethod but HttpContext.Current.Request.Files.Count is 0. The same call when I point to filedropper.com as given in example code it worked fine (i could see the uploaded image on filedrop.com) but not working when pointing to my windows web service. I have seen various other posts but could not just figure out whats going wrong. In the client console it writes no of bytes sent which means there is no issue from client side where as server side there seems to be an issue. Can anyone suggest where the issue is?
Below is the debug output
UPDATE-06112016-5:35PMIS
Still clueless also posted in http://www.telerik.com/forums/file-upload-not-working-93d711a97c9b
UPDATE-06112016-9-54PMIS
After a nightmare not been able to figure out how to fix the issue I decided to go with hosting a php on iis as alternative. Cordova File Transfer plugin seems to work fine with php server page as here
Apparently, IIS 7.5 in fast CGI mode has a bug regarding chunked multipart form data: https://bugs.php.net/bug.php?id=60826
The FileTransfer plugin for Cordova defaults the chunked mode to true:
chunkedMode: Whether to upload the data in chunked streaming mode. Defaults to true. (Boolean)
In my case this was exactly the problem and setting options.chunkedMode to true fixed it right away.
Note that you won't be able to use the onprogress property anymore.
onprogress: Called with a ProgressEvent whenever a new chunk of data is transferred. (Function)

Resources