Passing a StorageFile to OnNavigatedTo in a C# WinRT app - c#

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)
{
...
}
}

Related

Aumatica - Event When File is Attached to Document

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

How to prerender a UserControl with async/await on server-side for ASP.net WebForms

I have to deal with a WebForms (.Net 4.7) application, that loads server-side prerendered UserControls, by calling a HttpHandler by Javascript/Angular from client-side.
The HttpHandler prerenders the UserControls by this old "hack"
public class MyHandler : IHttpHandler
{
public override void ProcessRequest(HttpContext context)
{
var page = new Page();
var control = page.LoadControl("~/MyFancyUC.ascx");
var form = new HtmlForm { ID = "Form1" };
form.Controls.Add(control);
page.Controls.Add(form);
var stringBuilder = new StringBuilder();
using (StringWriter output = new StringWriter(stringBuilder))
{
HttpContext.Current.Server.Execute(page, output, false);
}
context.Response.Write(stringBuilder.ToString());
}
}
As this style worked several years very well, I can't use async/await style within the UserControls, because I'm getting an error, that the Page needs to have the Async=true attribute.
The UserControls look like this:
public partial class MyFancyUC: UserControl
{
protected void Page_Load(object sender, EventArgs e)
{
Page.RegisterAsyncTask(new PageAsyncTask(HandleAsync));
}
private async Task HandleAsync()
{
var data = await GetDataAsync();
BindData(data);
}
}
I already tried to create a simple page class, that sets the Async mode programmatically, and use it in the "MyHandler" HttpHandler, but this doesn't work either.
public class AsyncPage : Page
{
public AsyncPage()
{
this.AsyncMode = true;
}
}
}
When I debug the UserControl, the Page property always shows AsyncMode=false, IsAsync = false.
So I guess, this is caused by HttpServerUtility.Execute() call, that is not capable of running a WebForms page in Async mode.
Does anyone know how to deal with this ?
An asynchronous HTTP handler must implement IHttpAsyncHandler Interface.
An asynchronous Page must have its AsyncMode property set to true.
You have to use IHttpAsyncHandler

Execute same function on every page in Xamarin.Forms

I have a function that I need to perform to do some checks (e.g: CheckForUpdate, CheckNetworkConnection, CheckUserAuthorization, ...) on every page appearing or somehow before user request completed.
so I made a c# class and called it BasePage.cs:
public static class BasePage
{
public static async void CheckForUpdate()
{
// actual codes to check for updates are not included here
// just a sample alert
await App.Current.MainPage.DisplayAlert("Update", "There is a new version avaiable to update, would you like to download?", "Download", "Skip");
}
}
and used it in my pages like below:
LoginPage.cs
[XamlCompilation(XamlCompilationOptions.Compile)]
public partial class LoginPage : ContentPage
{
public LoginPage()
{
InitializeComponent();
}
protected async override void OnAppearing()
{
await Task.Run(() => BasePage.CheckForUpdate());
}
}
I don't know if this is best practice or not (I guess not) but it's not displaying alert anyhow.
so my question is what is the best way to execute functions on every page and why the code above doesn't work.
Your code doesn't seem to run on UI thread. Just use Device.BeginInvokeOnMainThread, try like below
protected override void OnAppearing()
{
Device.BeginInvokeOnMainThread(() => {
BaseClass.CheckForUpdate();
});
}
Hope it help you.

Change language for the whole application inside a fragment?

Let's say this is the call stack:
Fragment2 (current position)
Fragment1
HostingActivity
The user has just navigated to fragment2 (which is the settings screen). He chooses a second language, and then navigates back to Fragment1. I want the app to show content from the second language as soon as he enters fragment1.
I've read that the best approach would be to let all the fragments derive from a base-fragment which configures the locale inside the OnResume() method.
public class BaseFragment : Fragment
{
public override void OnResume()
{
string langCode = prefs.GetString("settings_language", "en_US");
Resources res = Application.Context.Resources;
// Change locale settings in the app.
DisplayMetrics dm = res.DisplayMetrics;
Configuration conf = res.Configuration;
conf.SetLocale(new Locale(langCode.ToLower()));
res.UpdateConfiguration(conf, dm);
OnConfigurationChanged(conf);
base.OnResume();
}
}
I've attempted this, but without any luck. I didn't see any change whatsoever.
I'm open to hear any suggestions.
PS. To ensure that I didn't mess up any of the naming conventions required by Android in the values folder, I tried rebooting the emulator (with adb shell) using the language I wanted and it worked as expected.
You can create a base class that sets the CurrentCulture like this and inherit from it:
internal class MyBaseActivity : Activity
{
protected override void OnResume ()
{
base.OnResume ();
// Get the language from wherever.
var userSelectedCulture = new CultureInfo ("fr-FR");
Thread.CurrentThread.CurrentCulture = userSelectedCulture;
}
}
And here is how to inherit and use it:
public class MainActivity : MyBaseActivity
{
protected override void OnResume()
{
base.OnResume(); // Do not forget to call base.OnResume()
// Rest of Your Code...
}
}

C# windows 8 app creating a file

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.

Categories