Is there a way to read an embedded JSON file in a PCL project with PCLStorage module? I looked everywhere but couldn't find a sample related to this matter.
EDIT: PCLStorage link: https://github.com/dsplaisted/pclstorage
you need something like this:
public static async Task<string> ReadFileContent(string fileName, IFolder rootFolder)
{
ExistenceCheckResult exist = await rootFolder.CheckExistsAsync(fileName);
string text = null;
if (exist == ExistenceCheckResult.FileExists)
{
IFile file = await rootFolder.GetFileAsync(fileName);
text = await file.ReadAllTextAsync();
}
return text;
}
to use:
IFolder rootFolder = FileSystem.Current.LocalStorage;
IFolder myCoolFolder = await rootFolder.CreateFolderAsync("MyCoolForler", CreationCollisionOption.OpenIfExists);
string fileContent = await this.ReadFileContent("MyCoolFile.txt", myCoolFolder);
You should be able to read embedded resources like this:
var assembly = typeof(LoadResourceText).GetTypeInfo().Assembly;
Stream stream = assembly.GetManifestResourceStream("WorkingWithFiles.PCLTextResource.txt");
string text = "";
using (var reader = new System.IO.StreamReader (stream)) {
text = reader.ReadToEnd ();
}
Xamarin has a great guide on how to work with them here.
https://developer.xamarin.com/guides/cross-platform/xamarin-forms/working-with/files/
Related
I have two questions:
1.When i use postman to upload an image, for example when i browse 15.jpg, it generates something like nDt3Vxjca/15.jpg in value column link
what is nDt3Vxjca.
public async Task<IActionResult> Upload([FromForm] IFormFileViewModel request)
{
var requestContent = new MultipartFormDataContent();
if (request.image!= null)
{
byte[] data;
using (var br = new BinaryReader(request.image.OpenReadStream()))
{
data = br.ReadBytes((int)request.image.OpenReadStream().Length);
}
ByteArrayContent bytes = new ByteArrayContent(data);
requestContent.Add(bytes, "image", request.image.FileName);
};
var client = _httpClientFactory.CreateClient();
string clientID = "abcdefg";
client.DefaultRequestHeaders.Add("Authorization", "Client-ID " + clientID);
var response = await client.PostAsync("https://api.imgur.com/3/upload", requestContent);
return Ok();
}
I copy a some lines of code to convert IformFile to binary. It still manages to upload the image but it doesn't point to my account, it returns something like this:
{"status":200,"success":true,"data":{"id":"I5oGuBd","deletehash":"qVwP3BONUUU9dr7","account_id":null,"account_url":null,"ad_type":null
account_id and account_url is null, Did i make mistake somewhere?
I am trying to read the text from a QRcode image on my mobile app. I am using Xamarin.Forms with ZXing NuGet package.
I have been able to get the file using Xamarin.Essentials FilePicker. But I don't know how to actually read the barcode. I have looked at some stackoverflow solutions and they all seem to be Xamarin.Android based (using BinaryBitmap objects). I need a solution that can work for iOS and UWP as well. Here is what I have so far:
string file = "";
var filePickerOptions = new PickOptions
{
PickerTitle = "Select Barcode Image",
FileTypes = FilePickerFileType.Images
};
var result = await FilePicker.PickAsync(filePickerOptions);
if (result != null)
{
file = result.FullPath;
var res = Decode(file, BarcodeFormat.QR_CODE);
Console.WriteLine(res.Text);
}
public Result Decode(string file, BarcodeFormat? format = null, KeyValuePair<DecodeHintType, object>[] aditionalHints = null)
{
var r = GetReader(format, aditionalHints);
/* I need some function here that will allow me to get the BinaryBitmap from the image file path or something along those lines.*/
var image = GetBinaryBitmap(file);
var result = r.decode(image);
return result;
}
MultiFormatReader GetReader(BarcodeFormat? format, KeyValuePair<DecodeHintType, object>[] aditionalHints)
{
var reader = new MultiFormatReader();
var hints = new Dictionary<DecodeHintType, object>();
if (format.HasValue)
{
hints.Add(DecodeHintType.POSSIBLE_FORMATS, new List<BarcodeFormat>() { format.Value });
}
if (aditionalHints != null)
{
foreach (var ah in aditionalHints)
{
hints.Add(ah.Key, ah.Value);
}
}
reader.Hints = hints;
return reader;
}
https://github.com/Redth/ZXing.Net.Mobile/issues/981. This thread solved it for me. Credit to #jason for this response.
I'm trying to resize imagine with System.Drawing but im taking that file as IFormFile and when i use the System.Drawing its just keep warning me to about that : cannot implicitly convert type 'System.Drawing.Bitmap' to 'Microsoft.AspNetCore.Http.IFormFile' . I need to resize those photos and save them as IFormFile but i dont know how to do that.
public Task<IFormFile> ResizeImagine300x300(IFormFile file)
{
Image image = Image.FromStream(file.OpenReadStream(), true, true);
var newImage = new Bitmap(1024, 768);
using (var g = Graphics.FromImage(newImage))
{
g.DrawImage(image, 0, 0, 1024, 768);
};
return newImage;//the point where i get the error
}
Is it possible to do it in my way?
If its not possible, then which way i should follow?
Thanks for any suggestion
Edit: I wanna return as a IFormFile because i have a method which is uploading those files to my database. here is my method :
public async Task<FileRepo> FileUploadToDatabase(List<IFormFile> files)
{
foreach (var file in files)
{
var fileName = Path.GetFileNameWithoutExtension(file.FileName);
var fileExtension = Path.GetExtension(file.FileName);
_fileRepo = new FileRepo
{
FileName = fileName,
FileExtension = fileExtension,
FileType = file.ContentType,
CreatedDate= DateTime.Now
};
using (var dataStream = new MemoryStream())
{
await file.CopyToAsync(dataStream);
_fileRepo.FileData = dataStream.ToArray();
}
}
return _fileRepo;
}
After that I'm uploading that _fileRepo variable to my database like that :
var File = _fileUploader.FileUploadToDatabase(files);
var FileResult = File.Result;
FileResult.ProductID = ProductID;
_unitOfWorkFR.RepositoryFileRepo.Create(FileResult);
I am trying to convert vsd/vsdx to png file, it was working fine until today. here is my code. please help. code stuck on convertApi.ConvertAsync line, it doesn't throw any error. but it just doesn't return anything.
public async void PrintVisioToTIFF(string VisioFilePath, string Filepath, string Extension)
{
var convertApi = new ConvertApi("XXXXXXXXXXXXXXX");
if (Extension == ".vsd")
{
var convert = await convertApi.ConvertAsync("vsd", "jpg",
new ConvertApiFileParam("File", VisioFilePath));
await convert.SaveFilesAsync(Filepath);
}
else if (Extension == ".vsdx")
{
var convert = await convertApi.ConvertAsync("vsdx", "png",
new ConvertApiFileParam("File", VisioFilePath));
await convert.SaveFilesAsync(Filepath);
}
}
I got the camera function to work and it displays the image on the page like i asked it too. But is there a way to permanently save the image on your phone or somewhere else and then call it?
Thank you so much
Here's some code that works for me.
IFileAccess is my wrapper around System.IO.File functions such as file open, write, check if exsists. If you're making your own file service look up Xamarin.Forms.Labs.Resolver and how to use it; if you're using shared Forms project type you can access System.IO.File directly from the Forms project. Assuming that's clear, the following
var fileAccess = Resolver.Resolve<IFileAccess> ();
mediaPicker.SelectPhotoAsync (new CameraMediaStorageOptions{ MaxPixelDimension = 1024 })
.ContinueWith(t=>{
if (!t.IsFaulted && !t.IsCanceled) {
var mediaFile = t.Result;
var fileAccess = Resolver.Resolve<IFileAccess> ();
string imageName = "IMG_" + DateTime.Now.ToString ("yy-MM-dd_HH-mm-ss") + ".jpg";
// save the media stream to a file
fileAccess.WriteStream (imageName, mediaFile.Source);
// use the stored file for ImageSource
ImageSource imgSource = ImageSource.FromFile (fileAccess.FullPath (imageName));
imgInXAML.Source = imgSource;
}
});
Further detail on IFileAccess.
In your Forms project create an interface like this:
public interface IFileAccess
{
bool Exists (string filename);
string FullPath(string filename);
void WriteStream (string filename, Stream streamIn);
}
In your iOS or Android or Shared project add a class FileAccess that implements IFileAccess:
public class FileAccess : IFileAccess
{
public bool Exists (string filename)
{
var filePath = GetFilePath (filename);
if (File.Exists (filePath)) {
FileInfo finf = new FileInfo (filePath);
return finf.Length > 0;
} else
return false;
}
public string FullPath (string filename)
{
var filePath = GetFilePath (filename);
return filePath;
}
static string GetFilePath (string filename)
{
var documentsPath = Environment.GetFolderPath (Environment.SpecialFolder.Personal);
var filePath = Path.Combine (documentsPath, filename);
return filePath;
}
public void WriteStream (string filename, Stream streamIn)
{
var filePath = GetFilePath (filename);
using (var fs = File.Create (filePath)) {
streamIn.CopyTo (fs);
}
}
}
If you're already using Xamarin.Forms.Labs.Resolver then add only the line to register the service, otherwise in your iOS or Android project find a call to Forms.Init() and right before it add
var resolverContainer = new SimpleContainer ();
resolverContainer.Register<IFileAccess> (t => new FileAccess ()); // maybe just this line
Resolver.SetResolver (resolverContainer.GetResolver ());