Export / Import Xamarin.Essentials Preferences - xamarin.forms

I was looking for a quick / simple way to import and export the Preferences object exposed by Xamarin.Essentials. Any suggestions?

According to your description, you want to save data in preference and get data from Preferences, am I right? if yes, please take a look the following code:
using Xamarin.Essentials;
private void Btn1_Clicked(object sender, EventArgs e)
{
Preferences.Set("key1", "this is test");
}
private void Btn2_Clicked(object sender, EventArgs e)
{
var myValue = Preferences.Get("key1","");
}
More detailed info about Xamarin.Essentials: Preferences, please take a look the following article:
https://learn.microsoft.com/en-us/xamarin/essentials/preferences?tabs=android
https://www.c-sharpcorner.com/article/xamarin-forms-application-preferences-using-xamarin-essentials/
Update:
If you want to save everything in Preferences, I suggest you can Serialization the data you want to save and deserialization the data that you want to get using Newtonsoft.Json.
Firstly, install Newtonsoft.Json by Nuget package, then do this:
public partial class Page13 : ContentPage
{
public List<person> persons { get; set; }
public Page13()
{
InitializeComponent();
persons = new List<person>()
{
new person(){username="cherry",age=12},
new person(){username="barry",age=14}
};
}
private void Btn1_Clicked(object sender, EventArgs e)
{
string list = Newtonsoft.Json.JsonConvert.SerializeObject(persons);
Preferences.Set("key1", list);
}
private void Btn2_Clicked(object sender, EventArgs e)
{
var myValue = Newtonsoft.Json.JsonConvert.DeserializeObject<List<person>>(Preferences.Get("key1", "")) ;
}
}
public class person
{
public string username { get; set; }
public int age { get; set; }
}
I use List to do example, but you can Serialization evertthing object to string, then save this string in Preference, deserialization string in to object to get data.

So I was not able to find a built in way to do this. I had to manually write code in my app to go through all my preferences, serialize them and them write the string to disk. Likewise for import I had to take a serialized string, reserialize it and then manually place the values back in my preferences.

Related

SignalR send object - newbie

With Signal R, if trying to send an object, what is the syntax to pass the model?
private async void FormLoaded(object sender, RoutedEventArgs e)
{
//Connection stuff...
Proxy.On("sendHello", () => OnSendDataConnection(ModelBuilder()));
}
private void OnSendDataConnection(ConnectionModel model)
{
Dispatcher.Invoke(DispatcherPriority.Normal,model?????)
this.Dispatcher.Invoke((Action)(LoadW));
}
Looking at the question (text, and not the code) I understand you are trying to send Complex object to JS side and use it there? Is that correct?
In that case the solution is supposed to be simple:
From the ASP.NET.SignalR site:
You can specify a return type and parameters, including complex types
and arrays, as you would in any C# method. Any data that you receive
in parameters or return to the caller is communicated between the
client and the server by using JSON, and SignalR handles the binding
of complex objects and arrays of objects automatically.
Example C#:
public void SendMessage(string name, string message)
{
Clients.All.addContosoChatMessageToPage(new ContosoChatMessage() { UserName = name, Message = message });
}
JS:
var contosoChatHubProxy = $.connection.contosoChatHub;
contosoChatHubProxy.client.addMessageToPage = function (message) {
console.log(message.UserName + ' ' + message.Message);
});
Where ContosoChatMessage is:
public class ContosoChatMessage
{
public string UserName { get; set; }
public string Message { get; set; }
}
(read on for examples...)
So basically, in JS once 'model' received, you should be able to use 'model.XY', where XY is a member of the model complex object.
I hope it helps.
In my case, I needed to convert my fields to properties, otherwise, it doesn't send the information properly.
From
public string myField;
to
public string myField {get; set;}

ASP.NET is System.Web.UI.Page thread safe

I am wondering if the following code is thread safe?
Can i be be sure that UniqueFoo will indeed be the Unique Foo and will not be override?
public partial class Dummy : System.Web.UI.Page
{
public string UniqueFoo{ get; set; }
protected void Page_Load(object sender, EventArgs e)
{
var id = int.Parse(Request["Id"]);
UniqueFoo = SomeThreadSafeWCF.GetUniqueFoo(id);
}
}
what about the following (static)
public partial class Dummy : System.Web.UI.Page
{
public static string UniqueFoo{ get; set; }
protected void Page_Load(object sender, EventArgs e)
{
var id = int.Parse(Request["Id"]);
UniqueFoo = SomeThreadSafeWCF.GetUniqueFoo(id);
}
}
i later want to use UniqueFoo in a [WebMethod]
[WebMethod]
public static void SetSomeObject(SetSomeObject obj)
{
SomeThreadSafeWCF service = new SomeThreadSafeWCF ();
service.SetSomeObject(UniqueFoo, obj);
}
EDIT:
I am getting SetSomeObject from JS and UniqueFoo is coming from ASP.NET
will i have any issues when NOT using the static in my Dummy class according to your answers?
Surely your first sample is thread safe because when a request of a page post to the Web Server asp.net make new instance of your page and call page_load so if your SomeThreadSafeWCF.GetUniqueFoo() always make a unique Foo everything is thread save
Your second code snippet is not thread safe because you are modifying the value of a static field. So for example if later in this page you attempt to read the value of this UniqueFoo field you might not get the value you expect.
The first code snippet is fine because the field is not static.
If you want to use the UniqueFoo in a WebMethod then I would recommend you to pass it to this web method when calling it.
[WebMethod]
public static void SetSomeObject(SetSomeObject obj, string uniqueFoo)
{
SomeThreadSafeWCF service = new SomeThreadSafeWCF ();
service.SetSomeObject(uniqueFoo, obj);
}

ASP.NET: Is it possible to keep complex object such as list<> is the session?

ASP.NET: Is it possible to keep complex object such as List<object> is the session? If yes, how to do so? I'm trying to keep a list in the session, but I'm being told that I cannot convert that List to a string.
EDIT
[Serializable]
public class Client
{
public string ClientType { get; set; }
public string ClientName { get; set; }
public string SubClientName { get; set; }
public string Project { get; set; }
public string Service { get; set; }
public string Activity { get; set; }
}
List<Client> ListOfClients;
protected void Page_Load(object sender, EventArgs e)
{
if(!IsPostBack)
{
ListOfClients = new List<Client> { new Client()};
Session["ListOfClients"] = ListOfClients;//This is where the error occurs
//Cannot convert List<Client> to string...
}
}
There are many operations to execute, but the idea is to keep whatever is in the list of clients in the session.
Thanks for helping.
Yes, you can store any serializable object into a session variable. For example:
List<string> list;
Session["list"] = list;
Then to return the value:
List<string> list = (List<string>)Session["list"];
You can store anything in the session object as long as session state is in InProc mode.
Otherwise what you store has to be serialisable.
Note that the type of what you store is object, so you cast the reference that you get back:
ListOfClients = Session["ListOfClients"] as List<Client>;
Since you wrote in a comment that the error happens when compiling as opposed to at runtime, I suspect that you have some other object called Session that masks the Page.Session.
Try to hover your mouse over the Session text in Visual Studio. The tooltip should show you that Session is of type
System.Web.SessionState.HttpSessionState
If it's showing something else, you need to search both your markup (.aspx file) and code behind file to see if you have declared something else with the name/id Session and then change that name/id.

JSON.NET Serializer for WCF REST Services

I am trying to use the NETFx Json.NET MediaTypeFormatter nuget package to swap out the default DataContractJsonSerializer in my WCF REST service (4.0 framework). I downloaded the package in my project and added the following lines of code in the Global.asax file.
void Application_Start(object sender, EventArgs e)
{
RegisterRoutes();
// Create Json.Net formatter serializing DateTime using the ISO 8601 format
var serializerSettings = new JsonSerializerSettings();
serializerSettings.Converters.Add(new IsoDateTimeConverter());
var config = HttpHostConfiguration.Create();
config.Configuration.OperationHandlerFactory.Formatters.Clear();
config.Configuration.OperationHandlerFactory.Formatters.Insert(0, new JsonNetMediaTypeFormatter(serializerSettings));
}
But when I run the service it still uses the DataContractJsonSerilizer for serialization. Below is the class I am returning from my service.
[DataContract]
public class SampleItem
{
[DataMember]
public int Id { get; set; }
[DataMember]
public string StringValue { get; set; }
[DataMember]
public DateTime DateTime { get; set; }
}
Below is the response from the service in Fiddler.
You can see that the DateTime is not in ISO format which I have specified in serializerSettings in the above code. This tells me that the JSON.NET serializer is not used for serializing the objects.
Would appreciate any help.
I feel dumb after I figured the answer. Happens at times :). I had to add the config to the RouteTable. Below is the code in Global.asax
public class Global : HttpApplication
{
void Application_Start(object sender, EventArgs e)
{
RegisterRoutes();
}
private void RegisterRoutes()
{
// Create Json.Net formatter serializing DateTime using the ISO 8601 format
var serializerSettings = new JsonSerializerSettings();
serializerSettings.Converters.Add(new IsoDateTimeConverter());
var config = HttpHostConfiguration.Create().Configuration;
config.OperationHandlerFactory.Formatters.Clear();
config.OperationHandlerFactory.Formatters.Insert(0, new JsonNetMediaTypeFormatter(serializerSettings));
var httpServiceFactory = new HttpServiceHostFactory
{
OperationHandlerFactory = config.OperationHandlerFactory,
MessageHandlerFactory = config.MessageHandlerFactory
};
RouteTable.Routes.Add(new ServiceRoute("Service1", httpServiceFactory, typeof(Service1)));
}
}
Hope it will help somebody if they happen to run into the same scenario.

asp.net store object class in viewstate (or other ideas)

I've build a class like this:
private class TestResults
{
public bool IsAdmitted { get; set; }
public bool IsDuplicate { get; set; }
public bool IsVerified { get; set; }
}
The values of this class are set at postback by clicking a radiobutton list. Problem however is I don't know how to save this values across multiple postbacks. I thought of using viewstate but I'm not quite sure how to do it with this class.
Maybe I'm missing some important thing here.
Hope someone can point me in the right direction
thanks for your time!
Kind regards,
Mark
Just sticking this class in viewstate is pretty simple:
ViewState["SomeUniqueKey"] = myTestResults;
var testResults = (TestResults)ViewState["SomeUniqueKey"];
Your class will need to be marked with the [Serializable] attribute though.
try using the Session cache instead
var testResults = new TestResults();
//set values
Session["TestResults"] = testResults;
Retrieving them later on:
var testResults = Session["TestResults"] as TestResults;
if (testResults != null)
{
//use it
}
You can use
Session.Add("TestResults", Your_Test_Result_Object)
Session Object Explanation
If you don't need this value on other pages or in other places throughout the app, you can use viewstate.
Use the Page.ViewState object bag to store it:
public partial class Page1 : Page {
protected void button1_click(object sender, EventArgs e) {
ViewState["myObject"] = testResultsObject;
}
}
You could also wrap the access to it in a property on the page:
public partial class Page1 : Page {
public TestResults TestResults {
get{ return ViewState["TestResults"] as TestResults; }
set{ ViewState["TestResults"] = value; }
}
}

Resources