xamarin form cannot keep last state - c#

I am trying to keep the state of some variable of my xamarin form when I close the app and start it but is not working
I have 2 variable "isconnected" and "eric"
var app = App.Current;
app.Properties["UserIsConnected"] = true;
app.Properties["userName"] = "eric";
await app.SavePropertiesAsync();
After closing the app when I restart it and trying to get the values of my variable like this :
((bool)App.Current.Properties["UserIsConnected"] ))
((string)App.Current.Properties["userName"] ))
I have this error:
System.Collections.Generic.KeyNotFoundException: The given key 'UserIsConnected' was not present in the dictionary.
How can I saved my variable and get them when restart the app?
thanks in advance for your help

You need to check if the value is exist before we get the value of it. You can do it like this:
private async Task saveDataAsync() {
if (App.Current.Properties.ContainsKey("UserIsConnected"))
{
//Do something awesome.
bool UserIsConnected = ((bool)App.Current.Properties["UserIsConnected"]);
string name = ((string)App.Current.Properties["userName"]);
System.Diagnostics.Debug.WriteLine("UserIsConnected= " + UserIsConnected +" name =" + name);
}
else {
var app = App.Current;
app.Properties["UserIsConnected"] = true;
app.Properties["userName"] = "eric";
await app.SavePropertiesAsync();
}
}

You seem to be saving a property with the key "isconnected" and trying to retrieve it with a different key ("UserIsConnected").
EDIT:
OK, thanks for clearing that the error I pointed out was a typo. As for the problem, try this instead:
App.Current.Properties.Add("UserIsConnected", true);
await App.Current.SavePropertiesAsync();
And make sure you check if the key exists before using it:
if (App.Current.Properties.ContainsKey("UserIsConnected"))
{
//Do something awesome.
}

Related

How to point to the correct Store in Outlook automation by C#?

I have a lot of VBA automation that interlinks an Outlook and Word solution; it is fine, but time is inexorable... so, I'm start to decorating and extending that old solution, wraping it with C#/VS2017.
Through a conventional Winform I can choose my patients, and from this action I do a lot of actions, including open the correct Outlook contact; that's the problem, because I can't get the correct Store; the patients.pst, depending on the machine, may be the 1st, 2nd, 3rd...
In VBA I do this:
WhichStoreNameToPointAt="patients"
Set myNamespace = myolApp.GetNamespace("MAPI")
For i = 1 To myNamespace.Stores.Count Step 1
If myNamespace.Stores.item(i).DisplayName = WhichStoreNameToPointAt Then
intOutlookItemStore = i
End if
End If
Set myFolderPatients = myNamespace.Stores.item(intOutlookItemStore).GetDefaultFolder(olFolderContacts)
And it always functions like a charm.
In C# I tried a lot of variations, and could not point to the correct store:
public void OpenPatientContact(string patientName)
{
Outlook.Store whichStore = null;
Outlook.NameSpace nameSpace = OlkApp.Session;
int i = 1;
foreach (Outlook.Folder folder in nameSpace.Folders)
{
bool p = false;
if (whichStoreNameToPointAt == folder.Name)
{
p = true;
whichStore = folder.Store;
//Correct Store selected; I can tell because of this watch:
//whichStore.displayname == whichStoreNameToPointAt
}
i++;
if (p)
break;
}
var contactItemsOlk = whichStore.Session.GetDefaultFolder
(Outlook.OlDefaultFolders.olFolderContacts).Items;
// The problem is below; always the first Store
Outlook.ContactItem contact = (Outlook.ContactItem)contactItemsOlk
.Find(string.Format("[FullName]='{0}'", patientName)); //[1];
if (contact != null)
{
contact.Display(true);
}
else
{
MessageBox.Show("The contact information was not found.");
}
}
Unfortunately, it keeps pointing ever to the same first Store, the one that has no patients...
If I change the Store order I can get past this and test other stuff, but of course it is not the right way.
Any other heads/eyes to see the light?
TIA
While seated writing the question, looking at a yellow rubber duck - and a lot of other stuff that belongs to my 1 yo daughter ;), I realized that whichStore.Session.GetDefaultFolder is a little strange in this context. I only changed this
var contactItemsOlk = whichStore.Session.GetDefaultFolder
(Outlook.OlDefaultFolders.olFolderContacts).Items;
To that:
var contactItemsOlk = whichStore.GetDefaultFolder
(Outlook.OlDefaultFolders.olFolderContacts).Items;
Voilá! Magic happens with C# too!
Session returns the default NameSpace object for the current session.
PS: yellow rubber duck; guys of The Pragmatic Programmer really knows some secrets and tricks ;)
Thanks Thomas and Hunt!

can't load scores from leaderboard

i'm setting up a leaderboard system in my unity game, using the google play games services plugin.
i want to load score in order to integrate them in my custom LeaderbordUI,
I followed the documentation and used the ILeaderboard.LoadScores but it's not working.
when i check the logcat i get this :
02-04 11:03:56.580: W/Unity(18969): !!! [Play Games Plugin DLL] 02/04/19 11:03:56 +01:00 WARNING: Error returned from fetch: -108
I have tried to loadScore with the method "Social.LoadScores" and "PlayGamesPlatform.Instance.LoadScores", but i'm getting the same warning.
PS: when i use Social.ShowLeaderboardUI() it shows me the leaderboard.
but when i use PlayGamesPlatform.Instance.ShowLeaderboardUI(LB_Stars.id) to show a specific leaderboard it gives me "hmm,something went wrong in play games"
public void LoadLeaderboard()
{
LB_Stars.LoadScores(ok =>
{
if (ok)
{
LoadUsersAndDisplay(LB_Stars);
}
else
{
Debug.Log("Error retrieving STARS leaderboard");
}
});
}
internal void LoadUsersAndDisplay(ILeaderboard lbStar)
{
Debug.Log("gonna load user and display them");
List<string> userIds = new List<string>();
foreach (IScore score in lbStar.scores)
{
userIds.Add(score.userID);
}
Social.LoadUsers(userIds.ToArray(), (users) =>
{
string status = "Leaderboard loading: " + lbStar.title + " count = " +
lbStar.scores.Length;
foreach (IScore score in lbStar.scores)
{
IUserProfile user = FindUser(users, score.userID);
if (user != null)
{
UserLeaderboardClone = Instantiate(UserLeaderboardPrefab);
UserLeaderboardClone.name = score.rank.ToString();
LeaderboardUserScript lbUser = UserLeaderboardClone.GetComponent<LeaderboardUserScript>();
lbUser.transform.SetParent(LBScrollview.content.transform, false);
FillUserInfo(lbUser, user, score);
}
}
});
}
Okay i've figured it out, based on a comment on github https://github.com/playgameservices/play-games-plugin-for-unity/issues/2045#issuecomment-350335234
After spending a couple of hours on this, my problem turned out to be my game was using leaderboard ids from another app.
So it failed with this "unauthorized error", however the exact cause was not given.
The reason why it happened was because the play games configuration in unity was caching old values. When you open it - it has the correct ids, however in the generated GPGSids.cs file - wrong ids are present.
The solution was simply to regenerate that by re-saving the configuration.

How to do a inner join using LINQ [duplicate]

This question already has answers here:
What is a NullReferenceException, and how do I fix it?
(27 answers)
Closed 7 years ago.
I have a LINQ Statement to check if someone is entering the URL for a voucher Redemption. The way i get this voucher is by using a regular url, with an extra hashed CampaignID, Which is called my VoucherRedemption, as shown below.
if (Request.QueryString["voucherRedemption"] != null)
{
String VoucherRemption = Request.QueryString["voucherRedemption"];
MSCDatabaseDataContext MSCDB2 = new MSCDatabaseDataContext();
var getCampaign = from campaign in MSCDB2.Tbl_Campaigns
where campaign.Link.Contains(VoucherRemption)
select campaign;
var VoucherCampaign = getCampaign.FirstOrDefault();
campaignName.Value = VoucherCampaign.CampaignName;
campaignDescription.Value = VoucherCampaign.CampaignDescription;
txtStartDate.Text = VoucherCampaign.StartDate.ToString();
txtDateEnd.Text = VoucherCampaign.EndDate.ToString();
campaignAudience.Value = VoucherCampaign.Target.ToString();
txtDiscount.Text = VoucherCampaign.Discount.ToString();
txtTsCs.Text = VoucherCampaign.TermsConditions;
txtTsCs.ReadOnly = true;
CalendarExtender1.Enabled = false;
CalendarExtender2.Enabled = false;
txtStartDate.ReadOnly = true;
txtDateEnd.ReadOnly = true;
txtDiscount.ReadOnly = true;
txtEmail.Visible = true;
}
Now i keep getting a:
System.NullReferenceException: Object reference not set to an instance of an object.
But the weird thing is, is that yesterday it was working. But only yesterday. The other days it wasn't. Not its gone back to being broken. Is there somehow I can fix this?
Edit: I have checked that article, and still cant seem to find the problem. It was working yesterday
You don't have a null check after
var VoucherCampaign = getCampaign.FirstOrDefault();
this is very dangerous as it can return a default (aka null) at any time. The database connection could have failed, you got a timeout, there was no result from your query or you simply are not allowed to access the database. All would result in a null pointer when you try to use voucherCampaign. Try changing it to something like this:
.
var VoucherCampaign = getCampaign.FirstOrDefault();
if (VoucherCampaign == null) {
//print a error message here so you know soemthing is wrong
return;
}
//rest of your code
It wont resolve the reason why you get a null. But at least your application won't crash on a null pointer in this function. If you want to know why you don't get a return change the firstrodefault to a first and put a try catch around it. The exception in your catch block will hold more information about why your query did not work.

Error throw exception when insert data with thread

I have probem when use thread in winform.
I have error when debug program.
My Application throw exception when start program.
I define class RunInUIThread is:
private void RunInUIThread(Delegate method)
{
this.BeginInvoke(method);
}
And in RunInUIThread method like:
BaiXeBUS baixe = new BaiXeBUS();
RunInUIThread(new ThreadStart(delegate ()
{
BaiXeDTO obj = new BaiXeDTO(); //Map all to define database
txtKhuVucBai.Text = mReader.CurrentCardIDBlock1.ToString();
txtMaThe.Text = mReader.CurrentCardIDBlock2.ToString();
//If I comment all below code. It's work. But I need Insert data to database.
txtKhuVucBai.Text = obj.IDBaiXe.ToString();
txtMaThe.Text = obj.IDRF.ToString();
obj.BienSoXe = textBox1.Text;
obj.HinhBienSo = color.ToString();
obj.HinhChuXe = img.ToString();
obj.ThoiGianVao = DateTime.Now.ToLocalTime();
obj.ThoiGianRa = DateTime.Now.ToLocalTime();
baixe.BaiXe_Insert(obj); //Contain data access layer to insert data with store procedure.
}));
Why my code not work. Someone can explain me and how to fix problem?
Thank all reader!!!
What I mean is trying to run this block of code without the ThreadStart
{
BaiXeDTO obj = new BaiXeDTO(); //Map all to define database
txtKhuVucBai.Text = mReader.CurrentCardIDBlock1.ToString();
txtMaThe.Text = mReader.CurrentCardIDBlock2.ToString();
//If I comment all below code. It's work. But I need Insert data to database.
txtKhuVucBai.Text = obj.IDBaiXe.ToString();
txtMaThe.Text = obj.IDRF.ToString();
obj.BienSoXe = textBox1.Text;
obj.HinhBienSo = color.ToString();
obj.HinhChuXe = img.ToString();
obj.ThoiGianVao = DateTime.Now.ToLocalTime();
obj.ThoiGianRa = DateTime.Now.ToLocalTime();
baixe.BaiXe_Insert(obj); //Contain data access layer to insert data with store procedure.
}
This is to debug your code within the main thread.
#JoelLegaspiEnriquez, your recommned me to remove [STAThread] in Program.cs?
If I comment this line. This have problem in control AxLiveX1 is control of camera ip.
The txtKhuVucBai.Text = mReader.CurrentCardIDBlock1.ToString(); is Guid type with 16byte: 8d58d690-6b71-4ee8-85ad-006db0287bf1.
But i assign txtKhuVucBai to Guid type is:
private Guid mCurrentCardIDBlock1;
public Guid CurrentCardIDBlock1
{
get { return mCurrentCardIDBlock1; }
}
The mCurrentCardIDBlock1 is type of RFID reader with 32 character random.

Big websites not loading at all - error

I have created a web browser for windows phone 7. In that am saving the history of browsing also with title of that page. But due to this codes when i tried to load a somewhat big website like thinkdigit,etc. are not loading. At the same time if i delete that particular codes then no history is being recorded in the history page. It shows error for the below highlighted code - "An unknown error has occurred. Error: 80020006". I think its due to big site or else do i need to put milliseconds or what i have to do???
Thanks in advance for your hard work!!!
Below is the codes i have used for it-
private void browsers_Navigated(object sender,System.Windows.Navigation.NavigationEventArgs e)
{
pbarWebClient.Visibility = System.Windows.Visibility.Collapsed;
if (!fromHistory)
{
if (HistoryStack_Index < HistoryStack.Count)
{
HistoryStack.RemoveRange(HistoryStack_Index, HistoryStack.Count - HistoryStack_Index);
}
HistoryStack.Add(e.Uri);
if (!app.incognito)
{
********string title = (string)browsers[this.currentIndex].InvokeScript("eval", "document.title.toString()");********----->This is the error.
stream.WriteLine(title + ";" + e.Uri.ToString());
}
HistoryStack_Index += 1;
}
fromHistory = false;
navigationcancelled = false;
Stop.Visibility = Visibility.Collapsed;
}
I would expect that eval has been overridden or in some other way suppressed on the site(s) in question.
"80020006" is a javascript invocation error code. Simply assuming that a javascript method will be available and work in the same way on any site is not always going to be true.
Finally i got the suitable answer for my own question. Just replace the above codes with this-
if (!app.incognito)
{
Thread.Sleep(100);
Dispatcher.BeginInvoke(() =>
{
string title = (string)browsers[this.currentIndex].InvokeScript("eval", "document.title.toString()");
stream.WriteLine(title + ";" + e.Uri.ToString());
});
}

Categories