Saving a custom object using IsloatedStorageSettings - windows-phone-7

I'm trying to save an object in IsolatedStorageSettings to save the high scores for my game, but whenever I try to save an updated copy of the object C# seems to think the object hasn't changed. I tried creating a custom Equals function for the HighScores class but that doesn't seem to help.
Any idea what I'm doing wrong?
Thanks
public bool AddOrUpdateValue(string Key, Object value)
{
bool valueChanged = false;
// If the key exists
if (isolatedStore.Contains(Key))
{
// If the value has changed
if (isolatedStore[Key] != value) //This keeps returning false
{
// Store the new value
isolatedStore[Key] = value;
valueChanged = true;
}
}
// Otherwise create the key.
else
{
isolatedStore.Add(Key, value);
valueChanged = true;
}
return valueChanged;
}
//This is located inside the HighScores class
public bool Equals(HighScores newHighScores)
{
for (int i = 0; i < highScores.Length; i++)
{
if (!highScores[i].Name.Equals(newHighScores.GetIndex(i).Name))
{
return false;
}
if (!highScores[i].Time.Equals(newHighScores.GetIndex(i).Time))
{
return false;
}
}
return true;
}

You haven't implemented the equality operators '==' and '!=' and these compare reference equality, you are going to have provide the implementation which maps on to your 'Equals' method
http://msdn.microsoft.com/en-us/library/ms173147%28v=vs.80%29.aspx

You should do isolatedStore.Save() to commit the changes

Related

How to prevent user pressing multiple keys Javafx?

I have a player that can move when pressing the arrow keys. I would like to prevent the user to press multiple arrows at the same time.
This what I have tried:
boolean[] pressedKeys = new boolean[4];
canvas.setOnKeyPressed(event -> {
if (!Arrays.asList(pressedKeys).contains(true)){
if (event.getCode() == KeyCode.UP){
pressedKeys[0] = true;
} else if (event.getCode() == KeyCode.RIGHT){
pressedKeys[1] = true;
} else if (event.getCode() == KeyCode.DOWN){
pressedKeys[2] = true;
} else if (event.getCode() == KeyCode.LEFT){
pressedKeys[3] = true;
}
}
});
canvas.setOnKeyReleased(event -> {
if (event.getCode() == KeyCode.UP){
pressedKeys[0] = false;
} else if (event.getCode() == KeyCode.RIGHT){
pressedKeys[1] = false;
} else if (event.getCode() == KeyCode.DOWN){
pressedKeys[2] = false;
} else if (event.getCode() == KeyCode.LEFT){
pressedKeys[3] = false;
}
});
But it does not work, here I can still press the right and the up arrows for example.
Thanks for any help
I'd create an event handler implementation like this:
class InputHandler implements EventHandler<KeyEvent> {
final private Set<KeyCode> activeKeys = new HashSet<>();
#Override
public void handle(KeyEvent event) {
if (activeKeys.isEmpty() && KeyEvent.KEY_PRESSED.equals(event.getEventType())) {
activeKeys.add(event.getCode());
} else if (KeyEvent.KEY_RELEASED.equals(event.getEventType())) {
activeKeys.remove(event.getCode());
}
}
public Set<KeyCode> getActiveKeys() {
return Collections.unmodifiableSet(activeKeys);
}
}
The check activeKeys.isEmpty() ensures that we don't register a new keypress until a prior key is released.
A single value for the activeKey could be used instead of the activeKeys HashSet, I just adapted this from a prior solution which works in a more general case.
To use it:
InputHandler inputHandler = new InputHandler();
scene.setOnKeyPressed(inputHandler);
scene.setOnKeyReleased(inputHandler);
Then, if it is something like a game where the input is checked on each frame update of an AnimationTimer, in the update method you can check the current active keys for the frame and action them, like this:
private AnimationTimer createGameLoop() {
return new AnimationTimer() {
public void handle(long now) {
update(now, inputHandler.getActiveKeys());
if (isGameOver()) {
this.stop();
}
}
};
I am not sure if your chosen strategy will result in a desirable user experience, you will need to try it out and see how well it works in your application.
I found a solution, thanks to #kleopatra
This is what I made:
boolean pressedKeys = false, releasedKeys = true;
canvas.setOnKeyPressed(event -> {
if (releasedKeys){
// Code goes here
pressedKeys = true;
releasedKeys = false;
}
});
canvas.setOnKeyReleased(event -> {
if (pressedKeys){
pressedKeys = false;
releasedKeys = true;
}
});
Like this, its not possible to press multiple keys at one time

Cannot validate textfield using codeigniter validation using callback

I want to validate from and to text fields using codeigniter validation. I have created
validateSchedule function that will validate on callback but here validation is not
working it is working only for required condition.
public function validateSchedule()
{
$fromDate=$_POST['from_date'];
$toDate=$_POST['toDate'];
if(empty($toDate) || empty($fromDate))
{
return TRUE;
}
else
{
$diffNoof_days = 10;
if(strtotime($fromDate) > strtotime($toDate)){
$this->form_validation->set_message('validateSchedule','from_date_must_be_smaller_than_to_date');
return FALSE;
}else if(strtotime($fromDate) == strtotime($toDate)){
$this->form_validation->set_message('validateSchedule','from_date_to_must_not_be_same');
return FALSE;
}else if($diffNoof_days>10)
{
$this->form_validation->set_message('validateSchedule','duration_should_not_exceed_10_days');
return FALSE;
}
}
}
$this->form_validation->set_rules('from_date','From Date','trim|required');
$this->form_validation->set_rules('to_date','To Date','trim|required|callback_validateSchedule');
You don't show the actual callback, so I'm speculating that you have named the method wrong by not removing the callback_ prefix. In other words, the definition
public callback_validateSchedule($str)
{
...
}
should be
public validateSchedule($str)
{
...
}
If I have guessed wrong please show the actual code for validateSchedule()

Trying to save comma-separated list

Trying to save selections from a CheckBoxList as a comma-separated list (string) in DB (one or more choices selected). I am using a proxy in order to save as a string because otherwise I'd have to create separate tables in the DB for a relation - the work is not worth it for this simple scenario and I was hoping that I could just convert it to a string and avoid that.
The CheckBoxList uses an enum for it's choices:
public enum Selection
{
Selection1,
Selection2,
Selection3
}
Not to be convoluted, but I use [Display(Name="Choice 1")] and an extension class to display something friendly on the UI. Not sure if I can save that string instead of just the enum, although I think if I save as enum it's not a big deal for me to "display" the friendly string on UI on some confirmation page.
This is the "Record" class that saves a string in the DB:
public virtual string MyCheckBox { get; set; }
This is the "Proxy", which is some sample I found but not directly dealing with enum, and which uses IEnumerable<string> (or should it be IEnumerable<Selection>?):
public IEnumerable<string> MyCheckBox
{
get
{
if (String.IsNullOrWhiteSpace(Record.MyCheckBox)) return new string[] { };
return Record
.MyCheckBox
.Split(new[] { ',' }, StringSplitOptions.RemoveEmptyEntries)
.Select(r => r.Trim())
.Where(r => !String.IsNullOrEmpty(r));
}
set
{
Record.MyCheckBox = value == null ? null : String.Join(",", value);
}
}
To save in the DB, I am trying to do this in a create class:
proxy.MyCheckBox = record.MyCheckBox; //getting error here
but am getting the error:
Cannot implicitly convert 'string' to System.Collections.Generic.IEnumerable'
I don't know, if it's possible or better, to use Parse or ToString from the API for enum values.
I know that doing something like this will store whatever I put in the ("") into the DB, so it's just a matter of figuring out how to overcome the error (or, if there is an alternative):
proxy.MyCheckBox = new[] {"foo", "bar"};
I am not good with this stuff and have just been digging and digging to come up with a solution. Any help is much appreciated.
You can accomplish this using a custom user type. The example below uses an ISet<string> on the class and stores the values as a delimited string.
[Serializable]
public class CommaDelimitedSet : IUserType
{
const string delimiter = ",";
#region IUserType Members
public new bool Equals(object x, object y)
{
if (ReferenceEquals(x, y))
{
return true;
}
var xSet = x as ISet<string>;
var ySet = y as ISet<string>;
if (xSet == null || ySet == null)
{
return false;
}
// compare set contents
return xSet.Except(ySet).Count() == 0 && ySet.Except(xSet).Count() == 0;
}
public int GetHashCode(object x)
{
return x.GetHashCode();
}
public object NullSafeGet(IDataReader rs, string[] names, object owner)
{
var outValue = NHibernateUtil.String.NullSafeGet(rs, names[0]) as string;
if (string.IsNullOrEmpty(outValue))
{
return new HashSet<string>();
}
else
{
var splitArray = outValue.Split(new[] {Delimiter}, StringSplitOptions.RemoveEmptyEntries);
return new HashSet<string>(splitArray);
}
}
public void NullSafeSet(IDbCommand cmd, object value, int index)
{
var inValue = value as ISet<string>;
object setValue = inValue == null ? null : string.Join(Delimiter, inValue);
NHibernateUtil.String.NullSafeSet(cmd, setValue, index);
}
public object DeepCopy(object value)
{
// return new ISet so that Equals can work
// see http://www.mail-archive.com/nhusers#googlegroups.com/msg11054.html
var set = value as ISet<string>;
if (set == null)
{
return null;
}
return new HashSet<string>(set);
}
public object Replace(object original, object target, object owner)
{
return original;
}
public object Assemble(object cached, object owner)
{
return DeepCopy(cached);
}
public object Disassemble(object value)
{
return DeepCopy(value);
}
public SqlType[] SqlTypes
{
get { return new[] {new SqlType(DbType.String)}; }
}
public Type ReturnedType
{
get { return typeof(ISet<string>); }
}
public bool IsMutable
{
get { return false; }
}
#endregion
}
Usage in mapping file:
Map(x => x.CheckboxValues.CustomType<CommaDelimitedSet>();

GWT - setText and setValue not working for TextBox on initial load

I have a couple of text-boxes on a page where the user can enter some numeric values; however, try as I might, I can't fill those text-boxes with default values - specifically I would like 0.0 displayed in both upon page load.
Here is how I create them and what I have tried -
GroupSection engineering_group = new GroupSection();
KSTextBox engrDesignTextBox = new KSTextBox();
engrDesignTextBox.setWidth("2.875em");
//engrDesignTextBox.setWatermarkText("0.0"); ==> this works, but not what I need
//engrDesignTextBox.setText("0.0"); ==> this doesn't work
engrDesignTextBox.setValue("0.0"); // doesn't work either
KSTextBox engrScienceTextBox = new KSTextBox();
engrScienceTextBox.setWidth("2.875em");
//engrScienceTextBox.setWatermarkText("0.0"); ==> this works, but not what I need
//engrScienceTextBox.setText("0.0"); ==> this doesn't work
engrScienceTextBox.setValue("0.0"); // doesn't work either
I'm thinking that I need to attach an "onload" event listener and then try the setText in there? That seems overkill for something that should be rather simple.
Incidentally, I have attached onBlurHandlers for both these text boxes and they work as expected (see code below)
The following code will simply insert0.0 if the user clicks or tabs out of the text-box while it is EMPTY.
engrDesignTextBox.addBlurHandler(new BlurHandler() {
#Override
public void onBlur(BlurEvent blurEvent) {
if(((KSTextBox)blurEvent.getSource()).getText().length() < 1) {
((KSTextBox)blurEvent.getSource()).setText("0.0");
}
}
});
engrScienceTextBox.addBlurHandler(new BlurHandler() {
#Override
public void onBlur(BlurEvent blurEvent) {
if(((KSTextBox)blurEvent.getSource()).getText().length() < 1) {
((KSTextBox)blurEvent.getSource()).setText("0.0");
}
}
});
EDIT : As requested here is how I have defined the setText and setValue methods in KSTextBox
public class KSTextBox extends TextBox implements HasWatermark {
.
.
.
#Override
public void setText(String text) {
String oldValue = super.getText();
if(hasWatermark) {
if(text == null || (text != null && text.isEmpty())){
super.setText(watermarkText);
addStyleName("watermark-text");
watermarkShowing = true;
}
else{
super.setText(text);
removeStyleName("watermark-text");
watermarkShowing = false;
}
}
else{
super.setText(text);
}
ValueChangeEvent.fireIfNotEqual(this, oldValue, text);
}
#Override
public void setValue(String value) {
if(hasWatermark) {
if(value == null || (value != null && value.isEmpty())){
super.setValue(watermarkText);
addStyleName("watermark-text");
watermarkShowing = true;
}
else{
super.setValue(value);
removeStyleName("watermark-text");
watermarkShowing = false;
}
}
else{
super.setValue(value);
}
}
So, getting back to the original question, how I do I initially set the values for these textboxes to 0.0?
That should have worked.Its very suprising. Is there a possibility that some other code is resetting the value after you did a setText or a setValue? Try debugging it in hosted mode.Put a breakpoint in setText and see when and how many times it is getting invoked

WP7 find control inside header of pivotitem

For my WP7 app, I need to find a date control which I have placed in the header template of the pivotitem.
How do I access this datepicker control in the code behind for the currently selected PivotItem?
public static T FindName<T>(string name, DependencyObject reference) where T : FrameworkElement
{
if (string.IsNullOrEmpty(name))
{
throw new ArgumentNullException("name");
}
if (reference == null)
{
throw new ArgumentNullException("reference");
}
return FindNameInternal<T>(name, reference);
}
private static T FindNameInternal<T>(string name, DependencyObject reference) where T : FrameworkElement
{
foreach (DependencyObject obj in GetChildren(reference))
{
T elem = obj as T;
if (elem != null && elem.Name == name)
{
return elem;
}
elem = FindNameInternal<T>(name, obj);
if (elem != null)
{
return elem;
}
else
{
//if (obj.GetType().FullName == "System.Windows.Controls.DataField")
// elem = (obj as DataField).Content as T;
if (elem != null && elem.Name == name)
return elem;
}
}
return null;
}
private static IEnumerable<DependencyObject> GetChildren(DependencyObject reference)
{
int childCount = VisualTreeHelper.GetChildrenCount(reference);
if (childCount > 0)
{
for (int i = 0; i < childCount; i++)
{
yield return VisualTreeHelper.GetChild(reference, i);
}
}
}
I don't know of any real good solution to this. I guess my initial thought was why do you need a reference to the DatePicker object? But I guess you have your reasons.
A possible solution though:
You could use the VisualTreeHelper to traverse the visual tree from your pivot item and stop when you find an object of the correct type (DatePicker). Create a helper function like this:
private static DependencyObject GetDependencyObjectFromVisualTree(DependencyObject startObject, Type type)
{
DependencyObject parent = startObject;
while (parent != null)
{
if (type.IsInstanceOfType(parent))
break;
parent = VisualTreeHelper.GetParent(parent);
}
return parent;
}
Then call it with the PivotItem as the DependencyObject, typeof(DatePicker) as the type and finally cast the returned DependencyObject to a DatePicker.
HTH
The regular Parent/Child relationship doesn't really work for the Pivot control. What you can do is search for the DatePicked component directly in the PivotItem:
((DatePicker)((PivotItem)MainPivot.SelectedItem).FindName("DateControl"))
MainPivot is the Pivot control. I am getting the currently selected item via SelectedItem - notice that I am casting it to PivotItem directly, since otherwise I get an object. Then I am looking for a control named DateControl, given that you have a x:Name set for it.
All that needs to be done after that is cast the object to DatePicker and access its properties the same way you would do for any other control.

Resources