Trouble populating an input with an App Properties value - xamarin

Working on my first Xamarin Forms app. I put this in my App's OnStart() method:
Application.Current.Properties["Email"] = "gern#blanston.org";
That should set the value as soon as the Application starts, right?
Then I created a Login content page with an EmailAddress entry. In the page initialization, I've got this:
if (Application.Current.Properties.ContainsKey("Email"))
{
EmailAddress.Text = Application.Current.Properties["Email"] as string;
}
When I run the app, the EmailAddress Entry element is not populated.
What am I doing wrong?

OnStart command is called after App constructor and you probably creating login page in App constructor and checking in login page constructor but OnStart is not called yet. Set it before you created login/main page
Application.Current.Properties["Email"] = "gern#blanston.org";
var navPage = new MainPage();

It should work.
Here is the Documentation.
You can try to use SavePropertiesAsync
The Properties dictionary is saved to the device automatically. Data added to the dictionary will be available when the application returns from the background or even after it is restarted.
Xamarin.Forms 1.4 introduced an additional method on the Application class - SavePropertiesAsync() - which can be called to proactively persist the Properties dictionary. This is to allow you to save properties after important updates rather than risk them not getting serialized out due to a crash or being killed by the OS.

Related

How to Close/Exit current instance of Xamarin.Forms app while loading a new one

We are facing a strange issue. Not sure if it is design flaw of the existing application. Your help/suggestion is appreciated.
We have a Xamarin.forms app. Targeted both for iOS and Android.
Problem is coming mainly in Android app.
Application flow:
once we logout from the application, app opens an logout activity and delete user info and other data.
opens a new activity for login which contains client SSO implementation
on successful login, app is setting user info and fetch data from web service.
then it calls LoadApplication method so that flow comes back in main application
Now if user perform logout/login several times, its opening a new application instance by calling LoadApplication method and then displaying home screen
So when user is tapping back button in home page, app is not closing and displays previous instance of same application.
User need to press back button several times (depending how many time user perform logout-login).
Is there any goodway to stop this?
Can we close current instance of the application before LoadApplication being called?
Stuck for a long time.
I'd try to avoid to call LoadApplication more then once. You should control the navigation stack.
Given you are on the LogoutPage
remove all views via PopToRootAsync
show the LoginPage
await Navigation.PopToRootAsync(false);
await Navigation.PushAsync(new LoginPage(), true);
This blog post may be worth a reading: https://jfarrell.net/2015/01/22/understanding-xamarin-forms-navigation/
Kindly try this.
https://stackoverflow.com/a/36885388/1941942
[Activity (NoHistory = true)]
public class LoginActivity : Activity { }
The saving instance error has gone a while after I implement it on MainActivity.

How to access session from a view in ASP .NET Core MVC 1.0

I am trying to access session data from inside a view.
Use Case: I'm storing status messages in the session that will be displayed at the top of the page. Currently I implemented this by using a DisplayMessages() function that sets some ViewData[....] properties and calling it at the beginning of every controller action.
Goal: I want to only set the status message once without needing additional code in the controller to display the messages on the next page load.
So I'm trying to access the messages that are stored in the session directly from the view.
So far I have tried the following:
Dependency Injection of an IHttpContextAccessor (doesn't seem to work anymore with ASP .NET Core MVC 1.0.0
Creating a static class to access the session, including the change from next() to next.invoke() suggested in the comment
This didn't work. I could access the HttpContext and Session.IsAvailable was true, but there was no data in the session.
The following should work in the view: Context.Session.TryGetValue
If you are using the SessionExtensions then Context.Session.GetString will work.
Injecting IHttpContextAccessor does work, but starting with ASP.NET Core 1.0.0 RC2, the IHttpContextAcessor is not registered by default, because it has significant performance overhead per request. See this GitHub announcement for more information.
Tratcher posted:
IHttpContextAccessor can be used to access the HttpContext for the current thread. However, maintaining this state has non-trivial performance costs so it has been removed from the default set of services.
Developers that depend on it can add it back as needed:
services.AddSingleton<IHttpContextAccessor, HttpContextAccessor>();
But in your use case, I would suggest using a ViewComponent, which is a reusable piece of View with logic, that do not depend on a controller.
The documentation can be found here.
In your Views you would simply embed it with
#await Component.InvokeAsync("PriorityList", new { maxPriority = 2, isDone = false })
or
#Component.Invoke("PriorityList", new { maxPriority = 2, isDone = false })
for synchronous calls.

Xamarin.forms how to auto save user name like browser

I am developing a mobile application using Xamarin.Forms
I had the following Home page contains login info:
How can we have the application to automatically save the user name, so that they do not have to type it in each time (as in a browser)?
You can use Properties dictionary in Xamarin.Forms Application class. And let the Xamarin.Forms framework handle persisting user name between app restarts and pausing/resuming your app.
Save user name by writing it to Properties dictionary
var properties = Xamarin.Forms.App.Current.Properties;
if(!properties.ContainsKey("username")
{
properties.Add("username", username);
}
else
{
properties["username"] = username;
}
Then, when your login screen is about to appear (for example in OnAppearing method) check Properties for user name:
var properties = Xamarin.Forms.App.Current.Properties;
if(properties.ContainsKey("username")
{
var savedUsername = (string)properties["username"];
}
If it's not there, then it means that this is first time when user log in into your application.
A very similar question was posed just a few days ago - my answer on that question also applies to your question: The best way to save Configuration data in Xamarin.Forms based app?
Essentially, you want to store the information using the native settings functionality. I would advise against using Application.Properties for now. It is currently not reliable on Android, and in the past has had other problems. The nuget package referenced in my linked answer is a better approach and will save you some headache in the future.
The right way to be done is through the App settings plugin
https://github.com/jamesmontemagno/Xamarin.Plugins/tree/master/Settings
What i did in my application is.
1) Installed Plugin.Settings from nuget
2)Added to Helpers->Settings.cs (autogenerated file by plugin) the following
public static class Settings
{
private static ISettings AppSettings
{
get { return CrossSettings.Current; }
}
private const string UserNameKey = "username_key";
private static readonly string UserNameDefault = "demo";
public static string UserName
{
get { return AppSettings.GetValueOrDefault<string>(UserNameKey, UserNameDefault); }
set { AppSettings.AddOrUpdateValue<string>(UserNameKey, value); }
}
}
3)In order to keep the username in the Application Context set
Settings.UserName = ViewModel.Username;
4)When you login screen starts
string username = Settings.UserName;
The answer is simple: persistance. Servers do this by setting cookies containing the data (or reference to it) that they want you to see when rendering the form field.
In order to do this in an app (with Xamarin for instance), you need to store the user's data into a file or database somewhere. Since you're using Xamarin you can probably use some sort of ConfigurationManager to keep track of this.
Obviously you could just create a config file in the local storage you have for your app (I don't think you need permissions to create files in that space).
When you have the info stored somewhere, just retrieve it and set the input's value to it.

session state service failed prism (Windows store app)

I am trying to react to suspend events within my Windows Store App. I added the appropriate callback method, but I've run into a problem:
App.Current.Suspending += Current_Suspending;
void Current_Suspending(object sender, Windows.ApplicationModel.SuspendingEventArgs e){}
The problem is that, when I trigger the suspension event in Visual Studio and the callback method is called (I have checked it with a breakpoint), it immediately terminates with an Exception:
session state service failed.
Any suggestions on how to solve this problem?
If you are using Prism as I was this can happen when the SessionStateService chokes on serializing an object. Relevant navigation parameters and anything manually added get serialized at app termination or suspension. In my specific case i had a non-nullable enum that wasn't being set on an object used as a navigation parameter. I used the following to verify the DataContractSerializer wasn't having issues with object.
test.Add("testitem", new WorkflowStep());
MemoryStream sessionData = new MemoryStream();
DataContractSerializer serializer = new DataContractSerializer(typeof(Dictionary<string, object>));
serializer.WriteObject(sessionData, test);

MVC3 + WIF - FederationResult missing "wctx"

I have an MVC3 app for which I want to implement claims support. My goal is as follows:
provide a SignIn link, which when clicked displays a popup window with username/password and Facebook/WindowsLive/Google etc. links
automatically redirect to my SignIn page when a protected controller is accessed e.g. /Order/Delete
I've set up the application and providers in AppFabricLabs.com and included the STS in my project. I've also created an implementation of IAuthorizationFilter so I can mark my controllers as [WifAuth] and successfully get the OnAuthorization method called. I've implemented the use-case where the visitor has not been authenticated like this:
private static void AuthenticateUser(AuthorizationContext context)
{
var fam = FederatedAuthentication.WSFederationAuthenticationModule;
var signIn = new SignInRequestMessage(new Uri(fam.Issuer), fam.Realm);
context.Result = new RedirectResult(signIn.WriteQueryString());
}
and successfully get AppFabricLabs page with my Identity Provider choices (haven't figured out how to customise that page). When I log in my returnUrl gets called so I land in a controller method /Home/FederationResult, however the form posted to me contains only wa and wresult fields but I need wctx to know where to send the user... I haven't been able to figure out why.
the wresult is an XML document that contains (amongst a bzillion other things) the name and e-mail address of the user logging in but sadly does not contain the url to which the user was headed.
have I failed to configure something or am I just off base? thoughts anyone?
e
Just specify a Context for the SignInRequestMessage:
signIn.Context = HttpContext.Current.Request.RawUrl;
The wctx parameter is included in every request/response and also part of the form posted finally to your site.

Resources