Xamarin.Forms Directory Picker - xamarin.forms

I would like to save a file in a user selected folder, thats why I would like to provide a directory list to user and user will be able to choose the directory where he wants to export the data. Unfortuntely I could not find any example for directory/folder picker, I just found a file picker which is not useful for me..
https://github.com/jfversluis/FilePicker-Plugin-for-Xamarin-and-Windows
Is there any component for picking a folder for Xamarin.Forms? Actually I am just doing for Android but we use Xamarin.forms

There is none I can think of.
With netstandard everything is way more simple as you can use the classic c# File api to get the folders.
You just have to know the mappings between special folders and android folders (per example):
System.Environment.SpecialFolder Path
ApplicationData INTERNAL_STORAGE/.config
Desktop INTERNAL_STORAGE/Desktop
LocalApplicationData INTERNAL_STORAGE/.local/share
MyDocuments INTERNAL_STORAGE
MyMusic INTERNAL_STORAGE/Music
MyPictures INTERNAL_STORAGE/Pictures
MyVideos INTERNAL_STORAGE/Videos
Personal INTERNAL_STORAGE
source: https://learn.microsoft.com/en-US/xamarin/android/platform/files/
same for ios:
https://learn.microsoft.com/en-US/xamarin/ios/app-fundamentals/file-system
But it's really easy to implement, just enumerate all folders and display them in a ListView.
EDIT: more details on implementation.
In fact you want to code a "directory explorer", it's easy, here is the concept.
You have a ListView in your Page
You have a Cancel button and a Select button in your Page
You have a CurrentPath in your ViewModel
You bind CurrentPath to the Title of your Page
You have an List<DirectoryViewModel> Directories in your ViewModel
Each time a user click on a item from the list:
You add the directory name in your current path
You get all the directories from the new path, and update your Directories property (don't forget RaisePropertyChange(nameof(Directories)))
The ListView will be updated accordingly
Each time you back:
You remove last part of your current path
same as before
If you arrive to root path "/", you do nothing when clicking on back.
Oh and you could use this Grid component to instead of the ListView, will be nicer ;)
https://github.com/roubachof/Sharpnado.Presentation.Forms#grid-Layout

You can edit this to make it work..
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Android.App;
using Android.Content;
using Android.OS;
using Android.Runtime;
using Android.Views;
using Android.Widget;
using Java.IO;
using Java.Util;
namespace Android.Basic.IO
{
public class DirectoryPicker : ListActivity
{
public const String START_DIR = "startDir";
public const String ONLY_DIRS = "onlyDirs";
public const String SHOW_HIDDEN = "showHidden";
public const String CHOSEN_DIRECTORY = "chosenDir";
public const int PICK_DIRECTORY = 43522;
private File dir;
private Boolean showHidden = false;
private bool onlyDirs = true;
public override void OnCreate(Bundle savedInstanceState, PersistableBundle persistentState)
{
base.OnCreate(savedInstanceState, persistentState);
Bundle extras = Intent.Extras;
dir = OS.Environment.ExternalStorageDirectory;
if (extras != null)
{
String preferredStartDir = extras.GetString(START_DIR);
showHidden = extras.GetBoolean(SHOW_HIDDEN, false);
onlyDirs = extras.GetBoolean(ONLY_DIRS, true);
if (preferredStartDir != null)
{
File startDir = new File(preferredStartDir);
if (startDir.IsDirectory)
{
dir = startDir;
}
}
}
SetContentView(Resource.Layout.folder_chooser_activity);
var title = dir.AbsolutePath.ToString();
Title = (title);
Button btnChoose = (Button)FindViewById(Resource.Id.btnChoose);
String name = dir.Name;
if (name.Length == 0)
name = "/";
btnChoose.Text = ("Choose " + "'" + name + "'");
btnChoose.Click += delegate
{
returnDir(dir.AbsolutePath);
};
ListView lv = this.ListView;
lv.TextFilterEnabled = (true);
if (!dir.CanRead())
{
Context context = ApplicationContext;
String msg = "Could not read folder contents.";
Toast.MakeText(context, msg, ToastLength.Long).Show();
return;
}
var files = filter(dir.ListFiles(), onlyDirs, showHidden);
String[] names = Names(files);
ListAdapter = (new ArrayAdapter<String>(this, Resource.Layout.folder_chooser_item, names));
lv.ItemClick += (ff, gg) =>
{
var position = gg.Position;
if (!files[gg.Position].IsDirectory)
return;
String path = files[position].AbsolutePath;
var intent = new Intent(this, typeof(DirectoryPicker));
intent.PutExtra(DirectoryPicker.START_DIR, path);
intent.PutExtra(DirectoryPicker.SHOW_HIDDEN, showHidden);
intent.PutExtra(DirectoryPicker.ONLY_DIRS, onlyDirs);
StartActivityForResult(intent, PICK_DIRECTORY);
};
}
protected void OnActivityResult(int requestCode, int resultCode, Intent data)
{
if (requestCode == PICK_DIRECTORY && resultCode == (int)Result.Ok)
{
Bundle extras = data.Extras;
String path = (String)extras.Get(DirectoryPicker.CHOSEN_DIRECTORY);
returnDir(path);
}
}
private void returnDir(String path)
{
Intent result = new Intent();
result.PutExtra(CHOSEN_DIRECTORY, path);
SetResult(Result.Ok, result);
Finish();
}
public List<File> filter(File[] file_list, bool onlyDirs, bool showHidden)
{
var files = new List<File>();
foreach (var file in file_list)
{
if (onlyDirs && !file.IsDirectory)
continue;
if (!showHidden && file.IsHidden)
continue;
files.Add(file);
}
Collections.Sort(files);
return files;
}
public String[] Names(List<File> files)
{
String[] names = new String[files.Count];
int i = 0;
foreach (var file in files)
{
names[i] = file.Name;
i++;
}
return names;
}
}
}
Start activity as result then catch in OnActivityResult
if (requestCode == DirectoryPicker.PICK_DIRECTORY && resultCode == Result.Ok)
{
Bundle extras = data.Extras;
String path = (String)extras.Get(DirectoryPicker.CHOSEN_DIRECTORY);
// do stuff with path
}

Related

DependencyService.Get<ILogManager>().GetLog() System.NullReferenceException: 'Object reference not set to an instance of an object'

I am trying to execute Xamarin App.
I can build and deploy solutions on both Android and iOS devices. But when I am Debugging/running iOS App I am receiving an error
**System.NullReferenceException:** 'Object reference not set to an instance of an object'
on
private static ILogger logger = DependencyService.Get<ILogManager>().GetLog(); line
I have installed the latest version of the Nlog NuGet Package.
My ILogManager file is
namespace VolMobile.AppData.Interfaces
{
public interface ILogManager
{
ILogger GetLog([System.Runtime.CompilerServices.CallerFilePath]string callerFilePath = "");
void Reload();
void DeleteLog();
}
}
How can I resolve this issue?
update
My NLogManager iOS file
using System;
using System.Collections.Generic;
using Xamarin.Forms;
using System.IO;
using NLog;
using NLog.Config;
using NLog.Targets;
using VolMobile.AppData.Interfaces;
using VolMobile.iOS.Logging;
[assembly: Dependency(typeof(NLogManager))]
namespace VolMobile.iOS.Logging
{
public class NLogManager : ILogManager
{
string logFile;
LoggingConfiguration config;
public NLogManager()
{
Reload();
}
public void Reload()
{
config = new LoggingConfiguration();
var consoleTarget = new ConsoleTarget();
config.AddTarget("console", consoleTarget);
var consoleRule = new LoggingRule("*", LogLevel.Trace, consoleTarget);
config.LoggingRules.Add(consoleRule);
//File logging level
LogLevel llSetting = LogLevel.Off;
IEnumerable<LogLevel> sysLevels = LogLevel.AllLevels;
//default to trace at startup
string currentLogLevel = "Trace";
//load the app state if available
if (App.AppState != null)
currentLogLevel = App.AppState.AppSettings.LogLevel;// AppData.AppData.LogLevel;
foreach (LogLevel ll in sysLevels)
{
if (currentLogLevel == ll.Name)
{
llSetting = ll;
}
}
var fileTarget = new FileTarget();
string folder = System.Environment.GetFolderPath(System.Environment.SpecialFolder.MyDocuments); //android.os.environment is the other option
fileTarget.FileName = Path.Combine(folder, "Log.txt");
fileTarget.Layout = "${longdate}|${level:uppercase=true}|${callsite}|${appdomain}|${logger}|${threadid}|${message}|{exception:format=tostring}";
config.AddTarget("file", fileTarget);
logFile = Path.Combine(folder, "Log.txt");
var fileRule = new LoggingRule("*", llSetting, fileTarget);//LogLevel.Warn
config.LoggingRules.Add(fileRule);
LogManager.Configuration = config;
}
public void DeleteLog()
{
File.Delete(logFile);
}
// Services.Logging.ILogger
//AppData.Interfaces.ILogger
//public NLogLogger GetLog([System.Runtime.CompilerServices.CallerFilePath] string callerFilePath = "")
//{
// string fileName = callerFilePath;
// if (fileName.Contains("/"))
// {
// fileName = fileName.Substring(fileName.LastIndexOf("/", StringComparison.CurrentCultureIgnoreCase) + 1);
// }
// var logger = LogManager.GetLogger(fileName);
// return new NLogLogger(logger, logFile);
//}
public AppData.Interfaces.ILogger GetLog([System.Runtime.CompilerServices.CallerFilePath] string callerFilePath = "")
{
string fileName = callerFilePath;
if (fileName.Contains("/"))
{
fileName = fileName.Substring(fileName.LastIndexOf("/", StringComparison.CurrentCultureIgnoreCase) + 1);
}
var logger = LogManager.GetLogger(fileName);
return new NLogLogger(logger, logFile);
}
}
}
The app is working perfectly fine on iOS, Andriod simulators, and Android Device only not on iOS devices.

BackgroundTaskRegistration trigger property is null

Hi want to receive push notifications on background task for that i have created Portable library here is my Background task class
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Xml.Linq;
using Windows.ApplicationModel.Background;
using Windows.Data.Xml.Dom;
using Windows.Networking.PushNotifications;
using Windows.Storage;
using Windows.UI.Notifications;
namespace BackgroundTask
{
public sealed class NotificationTask : IBackgroundTask
{
public void Run(IBackgroundTaskInstance taskInstance)
{
// Get the background task details
ApplicationDataContainer settings = ApplicationData.Current.LocalSettings;
string taskName = taskInstance.Task.Name;
Debug.WriteLine("Background " + taskName + " starting...");
// Store the content received from the notification so it can be retrieved from the UI.
ToastNotification notification = (ToastNotification )taskInstance.TriggerDetails;
settings.Values[taskName] = notification.Content;
NotificationTask.AddTostNotification(notification.Content);
Debug.WriteLine("Background " + taskName + " completed!");
}
private static void AddTostNotification(String xmlDocument)
{
List<string> messageSection = NotificationTask.GetMessageAndLandingPage(xmlDocument, "toast");
if (messageSection == null) { return; }
ToastTemplateType toastTemplate = ToastTemplateType.ToastText01;
XmlDocument toastXml = ToastNotificationManager.GetTemplateContent(toastTemplate);
XmlNodeList toastTextElements = toastXml.GetElementsByTagName("text");
toastTextElements[0].AppendChild(toastXml.CreateTextNode(messageSection[0]));
// toastTextElements[1].AppendChild(toastXml.CreateTextNode(message));
IXmlNode toastNode = toastXml.SelectSingleNode("/toast");
((XmlElement)toastNode).SetAttribute("launch", messageSection[1]);
XmlElement audio = toastXml.CreateElement("audio");
audio.SetAttribute("src", "ms-appx:///Assets/Play-Guitar.wav");
//audio.SetAttribute("loop", "true");
toastNode.AppendChild(audio);
//launch tost immediatly
ToastNotification toast = new ToastNotification(toastXml);
ToastNotificationManager.CreateToastNotifier().Show(toast);
}
Here i am registering Task
internal async void InitChannel()
{
// Applications must have lock screen privileges in order to receive raw notifications
BackgroundAccessStatus backgroundStatus = await BackgroundExecutionManager.RequestAccessAsync();
// Make sure the user allowed privileges
if (backgroundStatus != BackgroundAccessStatus.Denied && backgroundStatus != BackgroundAccessStatus.Unspecified)
{
Windows.Storage.ApplicationDataContainer roamingSettings = Windows.Storage.ApplicationData.Current.LocalSettings;
try
{
var channel = await PushNotificationChannelManager.CreatePushNotificationChannelForApplicationAsync();
if (channel != null)
{
roamingSettings.Values["ExistingPushChannel"] = channel.Uri;
dispatcher = Windows.UI.Core.CoreWindow.GetForCurrentThread().Dispatcher;
channel.PushNotificationReceived += OnPushNotificationReceived;
UnregisterBackgroundTask();
RegisterBackgroundTask();
}
else
{
roamingSettings.Values["ExistingPushChannel"] = "Failed to create channel";
}
}
catch
{
roamingSettings.Values["ExistingPushChannel"] = "Failed to create channel";
}
}
}
private void RegisterBackgroundTask()
{
BackgroundTaskBuilder taskBuilder = new BackgroundTaskBuilder();
PushNotificationTrigger trigger = new PushNotificationTrigger();
taskBuilder.SetTrigger(trigger);
// Background tasks must live in separate DLL, and be included in the package manifest
// Also, make sure that your main application project includes a reference to this DLL
taskBuilder.TaskEntryPoint = "BackgroundTask.NotificationTask";
taskBuilder.Name = "PlaypushNotification";
try
{
BackgroundTaskRegistration task = taskBuilder.Register();
task.Completed += BackgroundTaskCompleted;
}
catch
{
UnregisterBackgroundTask();
}
}
private bool UnregisterBackgroundTask()
{
foreach (var iter in BackgroundTaskRegistration.AllTasks)
{
IBackgroundTaskRegistration task = iter.Value;
if (task.Name == "PlaypushNotification")
{
task.Unregister(true);
return true;
}
}
return false;
}
In my Manifest file
<Extensions>
<Extension Category="windows.backgroundTasks" EntryPoint="BackgroundTask.NotificationTask">
<BackgroundTasks>
<Task Type="pushNotification" />
</BackgroundTasks>
</Extension>
</Extensions>
PushNotification Trigger is not firing, when i debug i found that trigger property of BackgroundTaskRegistration is null. what is the issue? What wrong is going here?

ASP.NET Bundling and Minification removing license comments? [duplicate]

I have found this link:
http://giddyrobot.com/preserving-important-comments-in-mvc-4-bundles/
It shows how to do this same thing for JavaScript and I have used it to make an attempt for StyleBundles, but I'm unsure if it's doing things correctly on the backend.
Is the source code available? If not does anyone know if this seems right? All I want to keep is comments that start with /*! so that licenses for open source projects like normalize get included properly in production.
Here is what I have so far:
public static void RegisterBundles(BundleCollection bundles)
{
// Allows us to keep /*! comments for licensing purposes
var cssBundleSettings = new CssSettings
{
CommentMode = CssComment.Important
};
}
public class ConfigurableStyleBundle : Bundle
{
public ConfigurableStyleBundle(string virtualPath, CssSettings cssSettings) :
this(virtualPath, cssSettings, null) { }
public ConfigurableStyleBundle(string virtualPath, CssSettings cssSettings, string cdnPath) :
base(virtualPath, cdnPath, new[] { new ConfigurableCSSTransform(cssSettings) })
{
// commented out from js concatenation token not sure if this one should have one
//base.ConcatenationToken = ";";
}
}
[ExcludeFromCodeCoverage]
public class ConfigurableCSSTransform : IBundleTransform
{
private readonly CssSettings _cssSettings;
public ConfigurableCSSTransform(CssSettings cssSettings)
{
_cssSettings = cssSettings;
}
public void Process(BundleContext context, BundleResponse response)
{
if (context == null)
{
throw new ArgumentNullException("context");
}
if (response == null)
{
throw new ArgumentNullException("response");
}
if (!context.EnableInstrumentation)
{
var minifier = new Minifier();
var content = minifier.MinifyStyleSheet(response.Content, _cssSettings);
if (minifier.ErrorList.Count > 0)
{
GenerateErrorResponse(response, minifier.ErrorList);
}
else
{
response.Content = content;
}
}
response.ContentType = "text/css";
}
internal static void GenerateErrorResponse(BundleResponse bundle, IEnumerable<object> errors)
{
var content = new StringBuilder();
content.Append("/* ");
content.Append("CSS MinifyError").Append("\r\n");
foreach (object current in errors)
{
content.Append(current.ToString()).Append("\r\n");
}
content.Append(" */\r\n");
content.Append(bundle.Content);
bundle.Content = content.ToString();
}
}
All of this is wrapped in public class BundleConfig and gets called from Global.asax.
I'm just wondering if CssComment.Important could have negative effects and remove too much and if this seems to be doing what I want it to? When I have tested it everything seems to look correct styling wise, but it doesn't hurt to get some eyes seeing as this is probably useful for a lot of other ASP.NET devs who use open source libraries.
I don't think you've done anything incorrectly. Though I would approach it using the IBundleBuilder interface, as this will also keep regular comments out of production from prying eyes who switch user agent, like specified in How to prevent User-Agent: Eureka/1 to return source code. I show some steps on how to test against this in this related blog post.
public class ConfigurableStyleBuilder : IBundleBuilder
{
public virtual string BuildBundleContent(Bundle bundle, BundleContext context, IEnumerable<BundleFile> files)
{
var content = new StringBuilder();
foreach (var file in files)
{
FileInfo f = new FileInfo(HttpContext.Current.Server.MapPath(file.VirtualFile.VirtualPath));
CssSettings settings = new CssSettings();
settings.CommentMode = Microsoft.Ajax.Utilities.CssComment.Important;
var minifier = new Microsoft.Ajax.Utilities.Minifier();
string readFile = Read(f);
string res = minifier.MinifyStyleSheet(readFile, settings);
if (minifier.ErrorList.Count > 0)
{
res = PrependErrors(readFile, minifier.ErrorList);
content.Insert(0, res);
}
else
{
content.Append(res);
}
}
return content.ToString();
}
private string PrependErrors(string file, ICollection<ContextError> errors )
{
var content = new StringBuilder();
content.Append("/* ");
content.Append("CSS MinifyError").Append("\r\n");
foreach (object current in errors)
{
content.Append(current.ToString()).Append("\r\n");
}
content.Append("Minify Error */\r\n");
content.Append(file);
return content.ToString();
}
private string Read(FileInfo file)
{
using (var r = file.OpenText())
{
return r.ReadToEnd();
}
}
}
public class BundleConfig
{
public static void RegisterBundles(BundleCollection bundles)
{
var cssBundle = new ConfigurableStyleBundle("~/Content/css");
cssBundle.Include("~/Content/stylesheet1.css");
cssBundle.Include("~/Content/stylesheet2.css");
bundles.Add(cssBundle);
//etc
}
}
I made a NuGet package for this (including a version for scripts) - https://www.nuget.org/packages/LicensedBundler/

Issue with Custom Pipeline component

The Custom Pipeline component developed reads the incoming stream to a folder and pass only some meta data through the MessageBox.I am using the one already availaible in Code Project
using System;
using System.Collections.Generic;
using System.Text;
using Microsoft.BizTalk.Message.Interop;
using Microsoft.BizTalk.Component.Interop;
using System.IO;
namespace SendLargeFilesDecoder
{
[ComponentCategory(CategoryTypes.CATID_PipelineComponent)]
[ComponentCategory(CategoryTypes.CATID_Decoder)]
[System.Runtime.InteropServices.Guid("53fd04d5-8337-42c2-99eb-32ac96d1105a")]
public class SendLargeFileDecoder : IBaseComponent,
IComponentUI,
IComponent,
IPersistPropertyBag
{
#region IBaseComponent
private const string _description = "Pipeline component used to save large files to disk";
private const string _name = "SendLargeFileDecoded";
private const string _version = "1.0.0.0";
public string Description
{
get { return _description; }
}
public string Name
{
get { return _name; }
}
public string Version
{
get { return _version; }
}
#endregion
#region IComponentUI
private IntPtr _icon = new IntPtr();
public IntPtr Icon
{
get { return _icon; }
}
public System.Collections.IEnumerator Validate(object projectSystem)
{
return null;
}
#endregion
#region IComponent
public IBaseMessage Execute(IPipelineContext pContext, IBaseMessage pInMsg)
{
if (_largeFileLocation == null || _largeFileLocation.Length == 0)
_largeFileLocation = Path.GetTempPath();
if (_thresholdSize == null || _thresholdSize == 0)
_thresholdSize = 4096;
if (pInMsg.BodyPart.GetOriginalDataStream().Length > _thresholdSize)
{
Stream originalStream = pInMsg.BodyPart.GetOriginalDataStream();
string srcFileName = pInMsg.Context.Read("ReceivedFileName", "http://schemas.microsoft.com/BizTalk/2003/file-properties").ToString();
string largeFilePath = _largeFileLocation + System.IO.Path.GetFileName(srcFileName);
FileStream fs = new FileStream(largeFilePath, FileMode.Create);
// Write message to disk
byte[] buffer = new byte[1];
int bytesRead = originalStream.Read(buffer, 0, buffer.Length);
while (bytesRead != 0)
{
fs.Flush();
fs.Write(buffer, 0, buffer.Length);
bytesRead = originalStream.Read(buffer, 0, buffer.Length);
}
fs.Flush();
fs.Close();
// Create a small xml file
string xmlInfo = "<MsgInfo xmlns='http://SendLargeFiles'><LargeFilePath>" + largeFilePath + "</LargeFilePath></MsgInfo>";
byte[] byteArray = System.Text.Encoding.UTF8.GetBytes(xmlInfo);
MemoryStream ms = new MemoryStream(byteArray);
pInMsg.BodyPart.Data = ms;
}
return pInMsg;
}
#endregion
#region IPersistPropertyBag
private string _largeFileLocation;
private int _thresholdSize;
public string LargeFileLocation
{
get { return _largeFileLocation; }
set { _largeFileLocation = value; }
}
public int ThresholdSize
{
get { return _thresholdSize; }
set { _thresholdSize = value; }
}
public void GetClassID(out Guid classID)
{
classID = new Guid("CA47347C-010C-4B21-BFCB-22F153FA141F");
}
public void InitNew()
{
}
public void Load(IPropertyBag propertyBag, int errorLog)
{
object val1 = null;
object val2 = null;
try
{
propertyBag.Read("LargeFileLocation", out val1, 0);
propertyBag.Read("ThresholdSize", out val2, 0);
}
catch (ArgumentException)
{
}
catch (Exception ex)
{
throw new ApplicationException("Error reading PropertyBag: " + ex.Message);
}
if (val1 != null)
_largeFileLocation = (string)val1;
if (val2 != null)
_thresholdSize = (int)val2;
}
public void Save(IPropertyBag propertyBag, bool clearDirty, bool saveAllProperties)
{
object val1 = (object)_largeFileLocation;
propertyBag.Write("LargeFileLocation", ref val1);
object val2 = (object)_thresholdSize;
propertyBag.Write("ThresholdSize", ref val2);
}
#endregion
}
}
The issue here is the LargeFileLocation is configurable in the receive pipeline. If I give a location for the first time for example E:\ABC\ the files are sent to the location.
But if I change the location to E:\DEF\ the files are still being sent to the previous location E:\ABC. I tried to create a new biztalk application deleting the old one but still I get the files dropped in to the old location E:\ABC\ not sure why.
Most likely the issue is with respect to Property definition of LargeFileLocation and its implementation and usage in IPersistPropertyBag interfaces. You can try following things:
Check if you have added E:\ABC path in Pipeline at design time. If
yes remove it from there and set in Admin console for first time
also and see how it behaves, my feeling is it will take temp path
location.
Change the Properties and IPersistPropertyBag implementation to use property with declaration such as public string LargeFileName {get;set;} i.e. no local variables _largeFileName.
Have you deleted the dll in %BizTalkFolder%\Pipeline Components\ ?
To refresh the pipeline component, you need delete the old dll file/remove the item in VS toolbox. then restart the VS, deploy it again.
and for this LargeFileLocation , I suggest you make it as a property so you can config it.

Xamarin Forms Labs Camera - Permanently Saving Images and Calling Them

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 ());

Resources