I have tried to save login value as true if user has logged in once by using
Application.Current.Properties["isLoggedIn"] = "true";
but its not working. If i remove my app from background it again shows the login page but if user is logged in it should show the next page.
When using 'Application Properties Dictionary' you have to keep in mind few things:
According to the official documentation: 'The Properties dictionary is saved to the device automatically'. However, if you want to ensure persistence you have to explicitly call SavePropertiesAsync().
The Properties dictionary can only serialize primitive types for storage. Attempting to store other types such as List can fail silently.
Read the official documentation carefully and pay attention to details. Here is a code example:
private async Task SaveApplicationProperty<T>(string key, T value)
{
Xamarin.Forms.Application.Current.Properties[key] = value;
await Xamarin.Forms.Application.Current.SavePropertiesAsync();
}
private T LoadApplicationProperty<T>(string key)
{
return (T) Xamarin.Forms.Application.Current.Properties[key];
}
// To save your property
await SaveApplicationProperty("isLoggedIn", true);
// To load your property
bool isLoggedIn = LoadApplicationProperty<bool>("isLoggedIn");
Base on your needs you may consider Local Database or Settings Plugin instead. However for saving just a few primitive values Application Properties approach should be good enough.
Xamarin Forms now includes Xamarin Forms Essentials and contains the Preferences component that you need. Check out the official website and try it.
https://learn.microsoft.com/en-us/xamarin/essentials/preferences?tabs=ios
This is an example of how to manage preferences with Essentials.
To save a value for a given key in preferences:
Preferences.Set("my_key", "my_value");
To retrieve a value from preferences or a default if not set:
var myValue = Preferences.Get("my_key", "default_value");
To remove the key from preferences:
Preferences.Remove("my_key");
To remove all preferences:
Preferences.Clear();
Supported Data Types:
bool
double
int
float
long
string
DateTime
First we set the key and value using below code
Xamarin.Essentials.Preferences.Set("UserId", content.userId);
We can get the above value in any page of project using below code
Xamarin.Essentials.Preferences.Get("UserId", "");
Related
I am programmatically setting up a cluster resource (specifically, a Generic Service), using the Windows MI API (Microsoft.Management.Infrastructure).
I can add the service resource just fine. However, my service requires the "Use Network Name for computer name" checkbox to be checked (this is available in the Cluster Manager UI by looking at the Properties for the resource).
I can't figure out how to set this using the MI API. I have searched MSDN and multiple other resources for this without luck. Does anybody know if this is possible? Scripting with Powershell would be fine as well.
I was able to figure this out, after a lot of trial and error, and the discovery of an API bug along the way.
It turns out cluster resource objects have a property called PrivateProperties, which is basically a property bag. Inside, there's a property called UseNetworkName, which corresponds to the checkbox in the UI (and also, the ServiceName property, which is also required for things to work).
The 'wbemtest' tool was invaluable in finding this out. Once you open the resource instance in it, you have to double-click the PrivateProperties property to bring up a dialog which has a "View Embedded" button, which is then what shows you the properties inside. Somehow I had missed this before.
Now, setting this property was yet another pain. Due to what looks like a bug in the API, retrieving the resource instance with CimSession.GetInstance() does not populate property values. This misled me into thinking I had to add the PrivateProperties property and its inner properties myself, which only resulted in lots of cryptic errors.
I finally stumbled upon this old MSDN post about it, where I realized the property is dynamic and automatically set by WMI. So, in the end, all you have to do is know how to get the property bag using CimSession.QueryInstances(), so you can then set the inner properties like any other property.
This is what the whole thing looks like (I ommitted the code for adding the resource):
using (var session = CimSession.Create("YOUR_CLUSTER", new DComSessionOptions()))
{
// This query finds the newly created resource and fills in the
// private props we'll change. We have to do a manual WQL query
// because CimSession.GetInstance doesn't populate prop values.
var query =
"SELECT PrivateProperties FROM MSCluster_Resource WHERE Id=\"{YOUR-RES-GUID}\"";
// Lookup the resource. For some reason QueryInstances does not like
// the namespace in the regular form - it must be exactly like this
// for the call to work!
var res = session.QueryInstances(#"root/mscluster", "WQL", query).First();
// Add net name dependency so setting UseNetworkName works.
session.InvokeMethod(
res,
"AddDependency",
new CimMethodParametersCollection
{
CimMethodParameter.Create(
"Resource", "YOUR_NET_NAME_HERE", CimFlags.Parameter)
});
// Get private prop bag and set our props.
var privProps =
(CimInstance)res.CimInstanceProperties["PrivateProperties"].Value;
privProps.CimInstanceProperties["ServiceName"].Value = "YOUR_SVC_HERE";
privProps.CimInstanceProperties["UseNetworkName"].Value = 1;
// Persist the changes.
session.ModifyInstance(#"\root\mscluster", res);
}
Note how the quirks in the API make things more complicated than they should be: QueryInstances expects the namespace in a special way, and also, if you don't add the network name dependency first, setting private properties fails silently.
Finally, I also figured out how to set this through PowerShell. You have to use the Set-ClusterParameter command, see this other answer for the full info.
I have the following code:
var propertyInstance = new DynamicPropertyInstance()
{
DynamicPropertyId = new EntityReference(DynamicProperty.EntityLogicalName, Guid.Parse("0ceedfcc-68b2-e711-8168-e0071b658ea1")),
ValueString = jobId.ToString(),
RegardingObjectId = line.ToEntityReference(),
};
crmContext.AddObject(dynamicPropertyInstance);
crmContext.SaveChanges();
It is successfully adding a DynamicPropertyInstance to a SalesOrderLine, but when viewing the Order in the CRM UI it does not pass the validation (as it is a required property). I've not managed to find a way to make this property valid. Editing the property that I've added in the UI (resetting the value) also fails to mark the instance as valid. Adding exactly the same property through the UI does mark it as valid.
The Id of the DynamicProperty is correct, as verified by loading the 2 instance records through the SDK and comparing the properties. Rather strangely, when I load the 2 records through the SDK the one I've created in code has a validationstatus of true (even though it's not) and the one that I've created in the UI has a validationstatus of false and ValueString returns null (which is wrong). All of the other properties either match or have relevant values (such as dates, object Ids etc)
I'm probably missing a method call to recalculate whether the instance is valid or not, but I can't find anything in the documentation to support that. Failing that, it's possibly a bug in CRM
Raised a case with Microsoft support, and was given some workaround code:
//Get DynamicPropertyInstance
UpdateProductPropertiesRequest UpdateRequest = new UpdateProductPropertiesRequest();
UpdateRequest.PropertyInstanceList = new EntityCollection();
UpdateRequest.PropertyInstanceList.EntityName = DynamicPropertyInstance.EntityLogicalName;
Entity dpInstance = new Entity(DynamicPropertyInstance.EntityLogicalName, Dpi.Id);
dpInstance.Attributes.Add(nameof(Dpi.ValueString).ToLower(), "Blarg");
dpInstance.Attributes.Add(nameof(Dpi.DynamicPropertyInstanceid).ToLower(), Dpi.Id);
dpInstance.Attributes.Add(nameof(Dpi.RegardingObjectId).ToLower(), new EntityReference(SalesOrderDetail.EntityLogicalName, line.Id));
dpInstance.Attributes.Add(nameof(Dpi.DynamicPropertyId).ToLower(), new EntityReference(DynamicProperty.EntityLogicalName, dpId));
UpdateRequest.PropertyInstanceList.Entities.Add(dpInstance);
crmContext.Execute(UpdateRequest);
Basically, it looks like you have to re-set or re-attach the entities for CRM to pick it up, so this is a workaround for a bug in CRM
In my app i'm having two variables, which i want to retain even after my application is closed.
Which would be the right way to accompolish it?
You can store the values in an IsolatedStorage. There is a very nice article on MSDN regarding the persistance of information on Windows Phone. You can read it here http://msdn.microsoft.com/en-us/library/gg680266(v=pandp.11).aspx
The example shown by Microsoft looks something like this:
private const string CAR_PHOTO_FILE_NAME = "CarPhoto.jpg";
private const string CAR_KEY = "FuelTracker.Car";
private static readonly IsolatedStorageSettings appSettings =
IsolatedStorageSettings.ApplicationSettings;
public static void SaveCar(Action errorCallback)
{
try
{
appSettings[CAR_KEY] = Car;
appSettings.Save();
DeleteTempCarPhoto();
SaveCarPhoto(CAR_PHOTO_FILE_NAME, Car.Picture, errorCallback);
NotifyCarUpdated();
}
catch (IsolatedStorageException)
{
errorCallback();
}
}
The process of reading the information is very much the same. Go through the article and adopt it for your own needs.
There are a number of different storages available on Windows Phone 7.x as well as Windows Phone 8
If these two values of yours are settings, you want to preserve, I recommend you to use the IsolatedStorageSettings. This is a simple key / value store to save and load variables after restart your app. See the the following sample of MSDN (How to create settings)
See a list of other API's and samples on when and how to use it here (Data for Windows Phone on MSDN)
is it possible in a WP7 app to save some objects which i create and then load it when the app is started again?
You'll want to look to store persistent items into IsolatedStorage. You can see an overview and an example of how to use IsolatedStorage here. There are also a range of examples on this site, showing how to save different types of objects.
Here's an example storing a string, but you should be able to store any type of object this way.
Add IsolatedStorage to your references:
using System.IO.IsolatedStorage;
In your class:
private string myString;
In the Loaded event for your page:
try
{
myString = (string)IsolatedStorageSettings.ApplicationSettings["myString"];
}
catch
{
IsolatedStorageSettings.ApplicationSettings.Add("myString", "this value is a string");
}
and later, when you want to save:
IsolatedStorageSettings.ApplicationSettings["myString"] = myString;
try after
the example code above to add this.
IsolatedStorageSettings.ApplicationSettings.save
I put some properties in the App.xaml.cs file which I am using to store data and populate textboxes as I navigate through my application:
public String appRXName { set; get; }
public String appRXNumber { set; get; }
Originally I had a pivot control that called different pages to gather data, but then I moved that pivot control item off to its own page that still calls other pages to collect data. Now when I run the application I get an error.
Basically it was working when I had it inside the original Pivot control. Once I moved it to a separate page (pivot page calles it) then I started to get this error:
System.ArgumentNullException was unhandled Message=Value can not be null. Parameter name: Text
No matter what page I hit always the second item in the list displays the error.
txtRxNotes.Text = (Application.Current as App).appDosageNotes;
txtQuantity.Text = (Application.Current as App).appQuantity.ToString();
I found something online about a RootVisual but I'm not sure if that is what I looking at or not. Does anyone have any ideas?
The ArgumentNullException is being thrown because the value that you are trying to set for the Text property is null, which you cannot do; the Text property is not a nullable type.
Without knowing how and when these application-level properties are being set it's difficult to provide a good explanation of why the behavior is different since your refactor, but you could either:
Put a null check in the code that accesses these application-level properties.
Initialise the application-level properties to string.Empty in the application constructor.