I'm trying to create a file then write to the file and read from it as well... kind of like settings for my app to load every time it loads. Why is this not working for me? I'm running visual studio 2012 and I think when I run the program there the file should be created in the project's folder... my method it's async and void... don't really know what is going on haha
StorageFile sampleFile = await Windows.Storage.ApplicationData.Current.LocalFolder.CreateFileAsync("config.txt", CreationCollisionOption.ReplaceExisting);
How can I create this in the local folder? so every time the program runs no matter in what computer it will create the file and load it when the user close and re-open the program?
Man, great question!
Here's the exact logic to do what you are asking:
public class MyData
{
public string Title { get; set; }
}
public sealed partial class MainPage : Page
{
public MainPage()
{
this.InitializeComponent();
}
protected async override void OnNavigatedTo(NavigationEventArgs e)
{
this.DataContext = await LoadData();
}
protected override void OnNavigatedFrom(NavigationEventArgs e)
{
SaveData(this.DataContext as MyData);
base.OnNavigatedFrom(e);
}
private async Task<MyData> LoadData()
{
var _Data = await StorageHelper.ReadFileAsync<MyData>(
this.GetType().ToString(), StorageHelper.StorageStrategies.Local);
return _Data ?? new MyData() { Title = "Welcome" };
}
private async void SaveData(MyData data)
{
await StorageHelper.WriteFileAsync(
this.GetType().ToString(), data, StorageHelper.StorageStrategies.Local);
}
}
The StorageHelper class can be found here. or on my blog http://jerrynixon.com
Best of luck!
How can I create this in the local folder?
You can't, and anyway you're not supposed to... Windows Store apps run in a sandbox, they have a very restricted access to the file system. Basically, you have access to:
your app's LocalFolder (which is not the installation folder) and RoamingFolder
documents library, pictures library, music library, etc, depending on your app's capabilities (declared in the app manifest)
files selected by the user using a file picker
And I think that's about it... You can also access the files in the installation folder (Package.Current.InstallationFolder), but only for reading.
Related
I'm looking to run a method when a file is attached to a document in Acumatica (POOrder in this case). Essentially an event that is fired when a file is attached.
Through my research I was not able to find any documentation or similar questions that relate so I am unable to provide any code.
File upload within the Acumatica system is done through the UploadFileMaintenance graph. The data record that is referenced is UploadFile
You can accomplish your goal of "run a method when a file is attached to a document in Acumatica" a variety of ways.
You can add an event handler to UploadFileMaintenance via an extension as seen below
public class UploadFileMaintenanceExtension : PXGraphExtension<UploadFileMaintenance>
{
public virtual void __(Events.RowInserting<UploadFile> e)
{
}
public virtual void __(Events.RowInserted<UploadFile> e)
{
}
}
Actions can then be determined based on the files origination information ect.
Similarly you can add an event for file saving specific to PO with the following
public class POOrderEntryExtension : PXGraphExtension<POOrderEntry>
{
public override void Initialize()
{
PXGraph.InstanceCreated.AddHandler<UploadFileMaintenance>((graph) =>
graph.RowInserting.AddHandler<UploadFile>((sender, e) =>
{
//Your code here
}));
base.Initialize();
}
}
I have an aplication where at some point i need to acess user's contacts list and get data from there. For this i used Xamarin.Forms.Contacts(1.0.5) plugins and it worked well. I was able to get Name Number Email PhotoUri PhotoUriThumbnail from each contact. And then i display some of the infos on my aplication. However, i am not able to display image from PhotoUri directory. PhotoUri is a string with this format : content://android/.... I tried converting PhotoUri to ImageSource and then use it on xaml file but nothing worked... Can anyone help ?
For getting data from a content:// URI, you can use the ContentResolver. Specifically you can load the contents from the file with ContentResolver.OpenInputStream (see here). To display the image you could use a StreamImageSource (see here). Given you already have an Uri, you can instantiate the StreamImageSource as seen in the following snippet
var contentResolver = Application.ApplicationContext.ContentResolver;
var streamImageSource = new StreamImageSource()
{
Stream = (cancellationToken) => Task.FromResult(contentResolver.OpenInputStream(uri));
}
Please note: If PhotoUri is note derived from Android.Net.Uri you'll have to convert it to the latter.
Edit
The code presented works from MainActivity, only. As an workaround I've added an static property Instance to MainActivity that is assigned in OnCreate
public static MainActivity Instance { get; private set; }
protected override void OnCreate(Bundle savedInstanceState)
{
this.Window.RequestFeature(WindowFeatures.ActionBar);
this.SetTheme(Resource.Style.MainTheme);
base.OnCreate(savedInstanceState);
MainActivity.Instance = this;
// whatever
}
you can then use
var contentResolver = MainActivity.Instance.Application.ApplicationContext.ContentResolver;
which might not be optimal, but works. Alternatively (which I'd prefer) you could inject the MainActivity to your instances.
Edit 2
Since the question arose how to use this code from Xamarin.Forms, I'll give a short outline. If you're not using dependency injection, the easiest way will be using DependencyService (see here). Create an interface in your shared code
public interface IContentLoader
{
ImageSource LoadFromContentUri(Uri uri);
}
The implementation of this interface has to be added to the platform project
[assembly: Dependency (typeof (Droid.ContentLoader))]
namespace Droid
{
public class ContentLoader : IContentLoader
{
public ImageSource LoadFromContentUri(Uri uri)
{
var contentResolver = MainActivity.Instance.Application.ApplicationContext.ContentResolver;
var streamImageSource = new StreamImageSource()
{
Stream = (cancellationToken) => Task.FromResult(contentResolver.OpenInputStream(Android.Net.Uri.Parse(uri.ToString())));
}
return streamImageSource;
}
}
}
Now the IContentLoader can be used from your Xamarin.Forms project using the DependencyService:
var contentLoader = DependencyService.Get<IContentLoader>();
// ...
var imageSource = contentLoader.LoadFromContentUri(uri);
Please note: If you are programming for iOS and Android, you'll have to take care that you can load your images from both platforms.
I get a System.NotImplementedException error whenever I try to launch the page on the emulator that takes photographs. Whenever I attempt to take a photo with the emulator's camera, I get taken to the main page in the Xamarin Studio project that launches the user interface. I get the error:
System.NotImplementedException has been thrown
This functionality is not implemented in the portable version of this assembly. You should reference the NuGet package from your main application project in order to reference the platform-specific implementation.
Here is the code:
using UIKit;
namespace Relate.iOS
{
public class Application
{
// This is the main entry point of the application.
static void Main(string[] args)
{
/* if you want to use a different Application Delegate class
from "AppDelegate" you can specify it here. */
UIApplication.Main(args, null, "AppDelegate");
}
}
}
Can anyone help?
Here is the code for the camera. I added Media Plugin to my project.
using System;
using Relate.Model;
using Xamarin.Forms;
using Plugin.Media;
namespace Relate.Views
{
public partial class EditMemberPage : ContentPage
{
public EditMemberPage()
{
InitializeComponent();
saveButton.Clicked += async (sender, args) =>
{
if (CrossMedia.Current.IsCameraAvailable &&
CrossMedia.Current.IsTakePhotoSupported)
{
// Supply media options for saving our photo after
it's taken.
var mediaOptions = new
Plugin.Media.Abstractions.StoreCameraMediaOptions
{
Directory = "Receipts",
Name = $"{DateTime.UtcNow}.jpg"
};
// Take a photo of the business receipt.
var file = await
CrossMedia.Current.TakePhotoAsync(mediaOptions);
}
};
}
async void SaveButton_OnClicked(object sender, EventArgs e)
{
var famMemberItem = (FamMember)BindingContext;
await App.Database.SaveFamMemberAsync(famMemberItem);
await Navigation.PopAsync();
}
}
}
The answer here should explain why this is not working for you: https://forums.xamarin.com/discussion/93536/error-while-accessing-camera
You cannot access platform specific features using portable common libraries. If you want to access your emulators camera you'll have to use something like Media Plugin
https://github.com/jamesmontemagno/MediaPlugin
In my C# WinRT app, I would like to pass a StorageFile to a new navigation page inside a frame so that the page can open the document and put the file's contents into a RichEditBox. I've tried to add an optional parameter to OnNavigatedTo with a StorageFile, but it causes the app to crash.
I tried to make it so that I can navigate to the page like this from another page that contains a frame:
RootFrame.Navigate(typeof(Editor), file);
And launch the framed page like so:
protected override async void OnNavigatedTo(Windows.UI.Xaml.Navigation.NavigationEventArgs e, Windows.Storage.StorageFile file)
{
if (file)
{
try
{
EditorBox.Document.SetText(Windows.UI.Text.TextSetOptions.None, await Windows.Storage.FileIO.ReadTextAsync(file));
}
catch
{
}
}
}
But doing this, I get the following errors:
'TestApp.Page3.OnNavigatedTo(Windows.UI.Xaml.Navigation.NavigationEventArgs, Windows.Storage.StorageFile)' is a new virtual member in sealed class 'TestApp.Page3'
'TestApp.Page3.OnNavigatedTo(Windows.UI.Xaml.Navigation.NavigationEventArgs, Windows.Storage.StorageFile)': no suitable method found to override
Is there any way to do something similar to what I am trying to accomplish?
You can only override existing methods. You can't override what doesn't exist - you'd create something new instead. However Windows wouldn't call a method it doesn't know. So stick with what Windows has to offer:
protected override async void OnNavigatedTo(NavigationEventArgs e)
{
var file = e.Parameter as Windows.Storage.StorageFile;
if (file!=null)
{
...
}
}
What I want to achieve:
I want to initiate audio playback from an mp3 and/or aac HTTP stream in a WP7 application
I want to initiate playback from a specific 'PhoneApplicationPage' instance, but still allow navigation to other pages whilst maintaining playback without any interuption - i.e. I want playback to be 'application-scope'
I want to be able to 'seek' within my media
I playback to continue whilst the phone is locked
What I have tried:
MediaElement:
If the MediaElement is not owned by a page, no sound is produced when Play() is called, despite no exceptions being thrown.
After following 'http://blog.jayway.com/2010/10/04/enable-background-audio-for-multiple-pages-in-windows-phone-7/', playback still resets between page transitions
It also seems like a quite a hacky way of doing things...
Microsoft.Xna.Framework.MediaPlayer:
Works, but "MediaPlayer.PlayPosition" is read-only, and there is no seek method.
See post: 'http://forums.create.msdn.com/forums/t/17318.aspx' - Apparently this is by design due to XBox constraints with Xna (?!)
Microsoft Silverlight Media Framework:
http://smf.codeplex.com/
My favourite option, as it seems very comprehensive
Downloaded 'Silverlight Media Framework 2.3, WP7 specific' assemblies from:
http://smf.codeplex.com/releases/view/57991#DownloadId=190196
I know this is hacky, but to get something working, in the code below, the 'SMFPlayer' is static, and added to each page's layout on navigation.
If the 'SMFPlayer' is not owned by a page, no sound is produced when Play() is called, despite no exceptions being thrown.
Playback still resets between page transitions...
Code:
using System;
using System.Diagnostics;
using Microsoft.Phone.Controls;
using Microsoft.SilverlightMediaFramework.Core;
using Microsoft.SilverlightMediaFramework.Core.Media;
using Microsoft.SilverlightMediaFramework.Plugins.Primitives;
namespace WindowsPhoneApplication1
{
public partial class MainPage : PhoneApplicationPage
{
public static readonly SMFPlayer Player = new SMFPlayer();
static MainPage()
{
Player.VolumeLevel = 1.0f;
Player.Playlist.Add(new PlaylistItem {MediaSource = new Uri("http://smf.vertigo.com/videos/wildlife.wmv", UriKind.Absolute)});
Player.LogLevel = LogLevel.All;
Player.LogEntryReceived += PlayerLogEntryReceived;
}
// Constructor
public MainPage()
{
InitializeComponent();
}
protected override void OnNavigatedTo(System.Windows.Navigation.NavigationEventArgs e)
{
base.OnNavigatedTo(e);
LayoutRoot.Children.Add(Player);
}
protected override void OnNavigatingFrom(System.Windows.Navigation.NavigatingCancelEventArgs e)
{
base.OnNavigatingFrom(e);
LayoutRoot.Children.Remove(Player);
}
private static void PlayerLogEntryReceived(object sender, CustomEventArgs<LogEntry> e)
{
Debug.WriteLine(e.Value.Severity + e.Value.Message + e.Value.Type);
}
private void button1_Click(object sender, System.Windows.RoutedEventArgs e)
{
this.NavigationService.Navigate(new Uri("/Page1.xaml", UriKind.RelativeOrAbsolute));
}
}
}
Does anyone have any idea how I can satisfy my requirements?
Example code?
From an architectural point of view, what I really want is a Media Service which i can send streaming URLs to without caring about which page is currently shown.
I eventually found a simple, but effective solution:
http://blog.reis.se/post/Enable-background-audio-for-multiple-pages-in-Windows-Phone-7-e28093-Take-2.aspx
In App.xaml:
<APPLICATION.RESOURCES>
<MEDIAELEMENT x:key="GlobalMedia"></MEDIAELEMENT>
</APPLICATION.RESOURCES>
In App.xaml.cs:
public static MediaElement GlobalMediaElement
{
get { return Current.Resources["GlobalMedia"] as MediaElement; }
}
In your page:
public partial class MyPage : PhoneApplicationPage
{
MediaElement MEAudio;
public MainPage()
{
InitializeComponent();
MEAudio = App.GlobalMediaElement;
}
private void OnSomeEvent(object sender, RoutedEventArgs e)
{
MEAudio.xxxxx();