declaring key in IsolatedStorageSettings - windows-phone-8

my goal is retrieve value of counter which was stored last time when application closed.
i.e. i am storing the counter value in isolated storage. if counter has value 5 and application is closed and again started i should be able to retrieve 5.
for this purpose i have written following code but i cannot make out of it.
IsolatedStorageSettings isoStoreSettings = IsolatedStorageSettings.ApplicationSettings;
int count=0;
isoStoreSettings["flag"];
if (isoStoreSettings["flag"]!="set")
{
isoStoreSettings["count"] = count;
isoStoreSettings["flag"] = "set";
}
count = isoStorageSettings["count"]; //using the value of count stored previously
//some code which updates the count variable
isoStorageSettings["count"]=count;
the problem with this code is that declaration of key in isolatedstorage is now allowed, we must assign some value to that key
but if i assign value to that key, it will reinitialize the key each time application is started.
so, if anyone can solve this, please help
even there is any other alternative to isolatedstorage for my goal then also please share.

If you want to load your count every time the App is Launched then put your code in Application_Launching event in App.xaml.cs:
// declare static variable which you will be able to access from anywhere
public static int count;
private void Application_Launching(object sender, LaunchingEventArgs e)
{
IsolatedStorageSettings settings = IsolatedStorageSettings.ApplicationSettings;
if (settings.Contains("count")) count = (int)settings["count"];
else count = 0;
}
On Clising event - save your variable:
private void Application_Closing(object sender, ClosingEventArgs e)
{
IsolatedStorageSettings settings = IsolatedStorageSettings.ApplicationSettings;
if (settings.Contains("count")) settings["count"] = count;
else settings.Add("count", count);
settings.Save();
}
From anywhere in your code, you should be able to access your variable like this:
int myVariable = App.count;
App.count++;
// and so on
Note that you may also think about Activated and Deactivated events - for more information read MSDN.
I also don't know what flag suppose to do, but code above should save your variable just fine.

Use updated count value in Add method like below:
IsolatedStorageSettings isolatedStorageSettingsCount = IsolatedStorageSettings.ApplicationSettings;
if (isolatedStorageSettingsCount.Contains("count"))
{
isolatedStorageSettingsCount.Remove("count");
isolatedStorageSettingsCount.Add("count",5);
IsolatedStorageSettings.ApplicationSettings.Save();
}
else
{
isolatedStorageSettingsCount.Add("count",5);
IsolatedStorageSettings.ApplicationSettings.Save();
}
To retrive your count value use below code:
IsolatedStorageSettings isolatedStorageSettingsCount = IsolatedStorageSettings.ApplicationSettings;
string strCount = (string)isolatedStorageSettingsCount["count"];
int count=Convert.ToInt32(strCount);

Related

Actually there was zero interactions with this mock error?

I am trying to write test case but stuck with this error. How to fix this error ?
#Override
public boolean isDuplicateSystemDetail(SystemFormBean systemFormBean){
List<BrmSystem> list = systemDao.isDuplicateSystemDetail(systemFormBean);
if(CollectionUtils.isNotEmpty(list)){
return true;
}else{
return false;
}
}
---------------------------------------------------------------------------
#Test
public void isDuplicateSystemDetail_Should_Return_True(){
List<BrmSystem> list = new ArrayList<BrmSystem>();
BrmSystem brmSystem = new BrmSystem();
SystemFormBean systemFormBean = new SystemFormBean();
brmSystem.setSystemName("Test");
list.add(brmSystem);
when(systemDao.isDuplicateSystemDetail(systemFormBean)).thenReturn(list);
}
Probably SystemFormBean class doesn't override equals(). So when isDuplicateSystemDetail(systemFormBean) invokes, it has another object of this class as a parameter which is not the same as the one you've created manually (by default Object.equals() compares memory adresses which would be false in your case).
Try to override equals() to compare by f.e. actual fields of SystemFormBean or rewrite "when" clause as
systemDao.isDuplicateSystemDetail(Mockito.any(SystemFormBean.class))

Adding "rate my app" to Web App Template

There's a project called Web App Template (aka WAT - http://wat.codeplex.com/) that allows you to wrap a webapp as a Windows 8 / Windows Phone 8 application. I've done that to an app, now I'm trying to add the "rate my app" feature to it. I don't see where/if I can inject code for this component to be added.
I'm following a guide here: http://developer.nokia.com/community/wiki/Implement_%22Rate_My_App%22_in_under_60_seconds
I'm stuck at Step 5 - where do I add the Event Handler? There is no MainPage.xaml.cs and I don't see any similar files.
I imagine that WAT is calling another library to load a web browser. Is there some way I can inject an Event Handler and method into this library?
I suggest not to prompt the user with 'rate my app' thing in the first opening of the app as user should be given some time to see what the app looks like and how it functions. Therefore, keeping the number of app launches and asking to rate the app after some 5th - 10th launch of app will make more sense. Besides you should check if you already prompted the user to rate your app, if so never prompt again. (Otherwise you will piss them off with 'rate my app' thing)
In order to achieve this, you should at first keep the app launch count in app settings class.
The interface for storing any kind of setting:
public interface ISettingService
{
void Save();
void Save(string key, object value);
bool AddOrUpdateValue(string Key, object value);
bool IsExist(string key);
T Load<T>(string key);
T GetValueOrDefault<T>(string Key, T defaultValue);
}
The rating service class that consumes the above interface to store such count and settings:
public class RatingService
{
private const string IsAppRatedKeyName = "isApprated";
private const string TabViewCountKeyName = "tabViewCount";
private const bool IsAppratedDefault = false;
private const int TabViewCountDefault = 0;
private const int ShowRatingInEveryN = 7;
private readonly ISettingService _settingService;
[Dependency]
public RatingService(ISettingService settingService)
{
_settingService = settingService;
}
public void RateApp()
{
if (_settingService.AddOrUpdateValue(IsAppRatedKeyName, true))
_settingService.Save();
}
public bool IsNeedShowMessage()
{
return (_settingService.GetValueOrDefault(TabViewCountKeyName, TabViewCountDefault)%ShowRatingInEveryN) == 0;
}
public void IncreaseTabViewCount()
{
int tabCount = _settingService.GetValueOrDefault(TabViewCountKeyName, TabViewCountDefault);
if (_settingService.AddOrUpdateValue(TabViewCountKeyName, (tabCount + 1)))
_settingService.Save();
}
public bool IsAppRated()
{
return _settingService.GetValueOrDefault(IsAppRatedKeyName, IsAppratedDefault);
}
}
This is how you will run such functionality and prompt the user to rate the app (if previously not rated) anywhere in your project (mainpage or some other page where user launches some functionality):
private void RunRating()
{
if (!RatingService.IsAppRated() && RatingService.IsNeedShowMessage())
{
MessageBoxResult result = MessageBox.Show("Review the app?", "Would you like to review this awesome app?",
MessageBoxButton.OKCancel);
//show message.
if (result == MessageBoxResult.OK)
{
RatingService.RateApp();
new MarketplaceReviewTask().Show();
}
}
}

Storing and getting data in windows phone app

I have created a Windows phone app based on a quiz game. I want that when the user give the correct answer for some question then a small tick mark will be permanently on in the tab of the question.
I want to store score for every question so that i can display that in a place name as 'your score'. And that score will not be reset even if the app is closed.
you could use app IsolatedStorage for saving the file.
reference
#region Save and Load Parameters from the Application Storage
void saveToAppStorage(String ParameterName, String ParameterValue)
{
// use mySettings to access the Apps Storage
IsolatedStorageSettings mySettings = IsolatedStorageSettings.ApplicationSettings;
// check if the paramter is already stored
if (mySettings.Contains(ParameterName))
{
// if parameter exists write the new value
mySettings[ParameterName] = ParameterValue;
}
else
{
// if parameter does not exist create it
mySettings.Add(ParameterName, ParameterValue);
}
}
String loadFromAppStorage(String ParameterName)
{
String returnValue = "_notSet_";
// use mySettings to access the Apps Storage
IsolatedStorageSettings mySettings = IsolatedStorageSettings.ApplicationSettings;
// check if the paramter exists
if (mySettings.Contains(ParameterName))
{
// if parameter exists write the new value
mySettings.TryGetValue<String>(ParameterName, out returnValue);
// alternatively the following statement can be used:
// returnValue = (String)mySettings[ParameterName];
}
return returnValue;
}
#endregion

Unable to save class objects to a SharedObject FIle

Well basically as the title implies, I can't save my array to the shared object.
I have an array which contains different "soldiers" with different characteristics(Health,Armor,Weapon,Position,Exp,Level) etc etc and was wondering how I would go about saving it. When I reload the swf I get this trace (",,,") but before I reload it I get a correct array reading.
This is my code if it helps:
//Saving game
function saveGame(E:MouseEvent){
var so:SharedObject = SharedObject.getLocal("saveFile"); //Instantiating the shared object
so.data.savedUnitArray = towerDefenceMain.unitArray;// is the array that stores the Soldiers
trace(so.data.savedUnitArray); //returns correct trace
so.flush();//Saving the operation
}
//Loading the data back
var so:SharedObject = SharedObject.getLocal("saveFile");
if(so.data.savedUnitArray != undefined){
unitArray = so.data.savedUnitArray;
trace(unitArray); //returns (",,,,")
}
In order to save a custom object, you either have to make all its properties public and accessible, AND have no references to DisplayObjects, or implement IExternalizable and define writeExternal() and readExternal() methods. Note that if your object is read from elsewhere, it first is initialized via zero parameter call to its constructor, and then the instance's readExternal() is invoked.
The manual on IExternalizable
An example:
public class Tower2 extends Obstacle implements gameRunnable,IExternalizable {
// HUGE set of statistics skipped, all methods skipped
public function writeExternal(output:IDataOutput):void {
output.writeInt(gemType);
output.writeInt(gemGrade);
output.writeBoolean(affectsFlying); // as some gems might be elongated, saving this
output.writeInt(_targetMode); // placeholder for targetting
output.writeInt(kills);
// hehe, what else to write in here? Everything else is derivable
}
public function readExternal(input:IDataInput):void {
var gt:int = input.readInt();
var gg:int = input.readInt();
MakeGem(gt, gg); // this is the function that initializes everything that's the tower
raised = true; // will place manually if ever
affectsFlying = input.readBoolean();
gt = input.readInt();
SetTargetting(gt);
kills = input.readInt(); // kills
updateDamage(); // this updates damage respective to kills counter
}
So, for your Soldiers you only need to save essential data, and re-create everything else once you load your set of soldiers from the shared object.

Find out what fields are being updated

I'm using LINQ To SQL to update a user address.
I'm trying to track what fields were updated.
The GetChangeSet() method just tells me I'm updating an entity, but doesn't tell me what fields.
What else do I need?
var item = context.Dc.Ecs_TblUserAddresses.Single(a => a.ID == updatedAddress.AddressId);
//ChangeSet tracking
item.Address1 = updatedAddress.AddressLine1;
item.Address2 = updatedAddress.AddressLine2;
item.Address3 = updatedAddress.AddressLine3;
item.City = updatedAddress.City;
item.StateID = updatedAddress.StateId;
item.Zip = updatedAddress.Zip;
item.Zip4 = updatedAddress.Zip4;
item.LastChangeUserID = request.UserMakingRequest;
item.LastChangeDateTime = DateTime.UtcNow;
ChangeSet set = context.Dc.GetChangeSet();
foreach (var update in set.Updates)
{
if (update is EberlDataContext.EberlsDC.Entities.Ecs_TblUserAddress)
{
}
}
Use ITable.GetModifiedMembers. It returns an array of ModifiedMemberInfo objects, one for each modified property on the entity. ModifiedMemberInfo contains a CurrentValue and OriginalValue, showing you exactly what has changed. It's a very handy LINQ to SQL feature.
Example:
ModifiedMemberInfo[] modifiedMembers = context.YourTable.GetModifiedMembers(yourEntityObject);
foreach (ModifiedMemberInfo mmi in modifiedMembers)
{
Console.WriteLine(string.Format("{0} --> {1}", mmi.OriginalValue, mmi.CurrentValue));
}
You can detect Updates by observing notifications of changes. Notifications are provided through the PropertyChanging or PropertyChanged events in property setters.
E.g. you can extend your generated Ecs_TblUserAddresses class like this:
public partial class Ecs_TblUserAddresses
{
partial void OnCreated()
{
this.PropertyChanged += new PropertyChangedEventHandler(User_PropertyChanged);
}
protected void User_PropertyChanged(object sender, PropertyChangedEventArgs e)
{
string propertyName = e.PropertyName;
// do what you want
}
}
Alternatively, if you want to track a special property changing, you could use one of those OnPropertyNameChanging partial methods, e.g. (for City in your example):
partial void OnCityChanging(string value)
{
// value parameter holds a new value
}