How can I save some user data locally on my Xamarin Forms app? - xamarin

I have a simple Xamarin Forms app. I've now got a simple POCO object (eg. User instance or an list of the most recent tweets or orders or whatever).
How can I store this object locally to the device? Lets imagine I serialize it as JSON.
Also, how secure is this data? Is it part of Keychains, etc? Auto backed up?
cheers!

You have a couple options.
SQLite. This option is cross-platform and works well if you have a lot of data. You get the added bonus of transaction support and async support as well. EDIT: In the past I suggested using SQLite.Net-PCL. Due to issues involving Android 7.0 support (and an apparent sunsetting of support) I now recommend making use of the project that was originally forked from: sqlite-net
Local storage. There's a great nuget that supports cross-platform storage. For more information see PCLStorage
There's also Application.Current.Properties implemented in Xamarin.Forms that allow simple Key-Value pairs of data.
I think you'll have to investigate and find out which route serves your needs best.
As far as security, that depends on where you put your data on each device. Android stores app data in a secure app folder by default (not all that secure if you're rooted). iOS has several different folders for data storage based on different needs. Read more here: iOS Data Storage

Another option is the Xamarin Forms settings plugin.
E.g. If you need to store a user instance, just serialize it to json when storing and deserialize it when reading.
Uses the native settings management
Android: SharedPreferences
iOS: NSUserDefaults
Windows Phone: IsolatedStorageSettings
Windows RT / UWP: ApplicationDataContainer
public User CurrentUser
{
get
{
User user = null;
var serializedUser = CrossSettings.Current.GetValueOrDefault<string>(UserKey);
if (serializedUser != null)
{
user = JsonConvert.DeserializeObject<User>(serializedUser);
}
return user;
}
set
{
CrossSettings.Current.AddOrUpdateValue(UserKey, JsonConvert.SerializeObject(value));
}
}
EDIT:
There is a new solution for this. Just use Xamarin.Essentials.
Preferences.Set(UserKey, JsonConvert.SerializeObject(value));
var user= JsonConvert.DeserializeObject<User>(Preferences.Get(UserKey, "default_value");

Please use Xamarin.Essentials
The Preferences class helps to store application preferences in a key/value store.
To save a value:
Preferences.Set("my_key", "my_value");
To get a value:
var myValue = Preferences.Get("my_key", "default_value");

If you want to store a simple value, such as a string, follow this Example code.
setting the value of the "totalSeats.Text" to the "SeatNumbers" key from page1
Application.Current.Properties["SeatNumbers"] = totalSeats.Text;
await Application.Current.SavePropertiesAsync();
then, you can simply get the value from any other page (page2)
var value = Application.Current.Properties["SeatNumbers"].ToString();
Additionally, you can set that value to another Label or Entry etc.
SeatNumbersEntry.Text = value;

If it's Key value(one value) data storage, follow below code
Application.Current.Properties["AppNumber"] = "123"
await Application.Current.SavePropertiesAsync();
Getting the same value
var value = Application.Current.Properties["AppNumber"];

Related

How can i use internal database from scratch

How can i using internal database for example (sqlite) for offline app in nativescript without using any plugin.
i'm searched every were how i can installed or used sqlite or other internal database for nativescript but i didn't have any answer.
Just like you would do with any code that you need to access the native APIs
e.g. (JavaScript) Android example
var query = "select sqlite_version() AS sqlite_version";
var db = android.database.sqlite.SQLiteDatabase.openOrCreateDatabase(":memory:", null);
var cursor = db.rawQuery(query, null);
var sqliteVersion = "";
if (cursor.moveToNext()) {
sqliteVersion = cursor.getString(0);
console.log(sqliteVersion);
}
The API references for SQLite in Android here and that said you can now follow a basic Android database tutorial and implement it step by step in your NativeScript application using JavaScript or TypeScript
Still, the plugin could provide all that wrapped in a ready-to-go functionality so unless you are lacking something it will be easier to use the nativescript-sqlite and avoid writing native code for Android and then for iOS.

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.

Windows Phone: Navigate between apps

I have an app that needs to include a links to a second app in the same phone.
If the app is not installed the link should point to the windows store to install it (that part is working fine).
But if the app is already installed the link should go straight to the app and open it. How can I do that?
The app has two versions one form WP7 and other from WP8. if the solution is different for them please point the difference.
Thanks for the help...
I believe a URI Association is what you want. You should be able to create a different association in your WP7 app and in your WP8 app, and handle them accordingly.
A URI association allows your app to automatically launch when another app launches a special URI.
Also note:
If you are interested only in launching your own apps, consider using
APIs from the Windows.Phone.Management.Deployment namespace. You can
use this API to check for other apps that you’ve published, and then
launch them if they’re installed.
You basically just need to update the WMAppManifest.xml file to include the URI Association and then listen for that URI. Example:
<Extensions>
<Protocol Name="contoso" NavUriFragment="encodedLaunchUri=%s" TaskID="_default" />
</Extensions>
Then you can use a custom URI Mapper to handle your association (full example in top link above):
public override Uri MapUri(Uri uri)
{
tempUri = System.Net.HttpUtility.UrlDecode(uri.ToString());
// URI association launch for contoso.
if (tempUri.Contains("contoso:ShowProducts?CategoryID="))
{
// Get the category ID (after "CategoryID=").
int categoryIdIndex = tempUri.IndexOf("CategoryID=") + 11;
string categoryId = tempUri.Substring(categoryIdIndex);
// Map the show products request to ShowProducts.xaml
return new Uri("/ShowProducts.xaml?CategoryID=" + categoryId, UriKind.Relative);
}
// Otherwise perform normal launch.
return uri;
}
Hope this helps!
Is the secondary app one that you have created? If so, do something like this:
IEnumerable<Package> packages = InstallationManager.FindPackagesForCurrentPublisher();
foreach (Package package in packages)
{
if (package.Id.ProductId.ToString().ToLower() == "product id of secondary app")
{
//Launch the app
package.Launch();
}
}
Make sure that your publisher ids match in the WMAppManifest for both apps.
If this secondary app was published by someone else, you'll need to use a custom Uri schema. The app needs to have this feature added by the developer, you can't just launch any app.

Setting UUID manually

My server generates UUID for uploaded files, so i need to set UUID to the fileState after i received answer from upload server (to successfully use delete function). I added and implemented
setUuid: function(id, uuid)
In UploadHandler, FineUploaderBasic and UploadHandlerXhr to solve this issue but this involve editing fine-uploader sources, is there any other way around? I have feeling this can break something internally.
I would suggest not passing the UUID back to fine uploader. It would be simpler to associate your UUID with fine uploader's UUID server side. You could maintain a map of associations in the session if you don't want to persist them.
I encountered this issue and found some documentation that states you can set the UUID from the server side by returning it from the upload method.
click image where newUuid is being set
Here is my return method using C#
return new FineUploaderResult(true, new { newUuid = attachmentId });

Frameworks using Redis

I would like to know if there are any MVC framework compatible with Redis as a database. (Not just as a caching datastore).
Thanks
I would not expect any MVC framework to be tied to a database. Your implementation of the Model would provide access to whatever backing store (either directly or via one or more layers) was appropriate. You should be looking at the clients that Redis supports, with those you should be able to utilise MVC frameworks on any of the support client platforms.
+1 for Padrino.
Another great option is Monk. It includes Ohm(its actually written by some of the same guys) and is based on Sinatra. Its really easy to get started with and very flexible.
In Ruby you can use Ohm as ORM. If you want an MVC framework, it can be plugged to Padrino.
try to investigate cqrs architecture with event sourcing.
And you can download example of this from github.it is Ruby on Rails application with Redis DB
You should definitely check out my C# ServiceStack.Redis Client. The client provides a typed API that can store any type and other high-level functionality, i.e. Strong-typed messaging API, Transactional Support, Pipelining, etc.
Here's is an mini clone of Stack Overflow built with it, using only one page of C#:
Sample Code from Redis StackOverflow:
public User GetOrCreateUser(User user)
{
if (user.DisplayName.IsNullOrEmpty())
throw new ArgumentNullException("DisplayName");
var userIdAliasKey = "id:User:DisplayName:" + user.DisplayName.ToLower();
using (var redis = RedisManager.GetClient())
{
//Get a typed version of redis client that works with <User>
var redisUsers = redis.As<User>();
//Find user by DisplayName if exists
var userKey = redis.GetValue(userIdAliasKey);
if (userKey != null)
return redisUsers.GetValue(userKey);
//Generate Id for New User
if (user.Id == default(long))
user.Id = redisUsers.GetNextSequence();
redisUsers.Store(user);
//Save reference to User key using the DisplayName alias
redis.SetEntry(userIdAliasKey, user.CreateUrn());
return redisUsers.GetById(user.Id);
}
}
grails has redis support in GORM through the redis plugin. Any domain class can be stored in redis (or any one of the other supported nosql stores) instead of a relational database.

Resources