IsolatedStorageSettings WP8 - windows-phone-8

I have one problem which I cannot resolve (at least I didn't found solution yet...) I wanted to add data into IsolatedStorageSettings in WP8. My goal is to check if there are settings already in there, but when I want to check I get an exception which I cannot resolve.
private IsolatedStorageSettings appSettings = new IsolatedStorageSettings();
private void Button_Click(object sender, RoutedEventArgs e)
{
//correct this part
if (String.IsNullOrEmpty((string)appSettings["ICE1"])||
String.IsNullOrEmpty((string)appSettings["ICE2"]) ||
String.IsNullOrEmpty((string)appSettings["ICE3"]) ||
String.IsNullOrEmpty((string)appSettings["address"]) ||
String.IsNullOrEmpty((string)appSettings["fullName"]))
{
appSettings.Add("fullName", fullName.Text);
appSettings.Save();
appSettings.Add("address", address.Text);
appSettings.Save();
if (Regex.IsMatch(prefix1.Text, "^+\\d{2,3}") && Regex.IsMatch(number1.Text, "d{6,10}"))
{
appSettings.Add("ICE1", prefix1.Text + number1.Text);
appSettings.Save();
}
else
{
MessageBox.Show("Invalid prefix number, please use +01 and for numbers only 0-9...");
}
if (Regex.IsMatch(prefix2.Text, "^+\\d{2,3}") && Regex.IsMatch(number2.Text, "d{6,10}"))
{
appSettings.Add("ICE2", prefix2.Text + number2.Text);
appSettings.Save();
}
else
{
MessageBox.Show("Invalid prefix number, please use +01 and for numbers only 0-9...");
}
if (Regex.IsMatch(prefix2.Text, "^+\\d{2,3}") && Regex.IsMatch(number2.Text, "d{6,10}"))
{
appSettings.Add("ICE3", prefix2.Text + number2.Text);
appSettings.Save();
}
else
{
MessageBox.Show("Invalid prefix number, please use +01 and for numbers only 0-9...");
}
MessageBox.Show("Your information is saved...!");
}
else
{
//
appSettings["fullName"] = fullName.Text;
appSettings.Save();
appSettings["address"] = address.Text;
appSettings.Save();
if (Regex.IsMatch(prefix1.Text, "^+\\d{2,3}") && Regex.IsMatch(number1.Text, "d{6,10}"))
{
appSettings["ICE1"]= prefix1.Text + number1.Text;
appSettings.Save();
}
else
{
MessageBox.Show("Invalid prefix number, please use +01 and for numbers only 0-9...");
}
if (Regex.IsMatch(prefix2.Text, "^+\\d{2,3}") && Regex.IsMatch(number2.Text, "d{6,10}"))
{
appSettings["ICE2"] = prefix2.Text + number2.Text;
appSettings.Save();
}
else
{
MessageBox.Show("Invalid prefix number, please use +01 and for numbers only 0-9...");
}
if (Regex.IsMatch(prefix2.Text, "^+\\d{2,3}") && Regex.IsMatch(number2.Text, "d{6,10}"))
{
appSettings["ICE3"] = prefix3.Text + number3.Text;
appSettings.Save();
}
else
{
MessageBox.Show("Invalid prefix number, please use +01 and for numbers only 0-9...");
}
MessageBox.Show("Your information is saved...!");
}
Can someone explain how IsolatedStorageWorks?
How can I correct this part because this is causing the problem:
if (String.IsNullOrEmpty((string)appSettings["ICE1"])||
String.IsNullOrEmpty((string)appSettings["ICE2"]) ||
String.IsNullOrEmpty((string)appSettings["ICE3"]) ||
String.IsNullOrEmpty((string)appSettings["address"]) ||
String.IsNullOrEmpty((string)appSettings["fullName"]))
Do I need to do appSettings.Save() every each time when I wish to add the data or update-it...?
I also have another problem of getting data from IsolatedStorageSettings:
public WindowsPhoneControl2()
{
InitializeComponent();
}
string ice1;
string ice2;
string ice3;
PhoneCallTask ptask = new PhoneCallTask();
private void Image_Tap(object sender, System.Windows.Input.GestureEventArgs e)
{
ptask.PhoneNumber = ice1;
ptask.DisplayName = "Contact person 1";
ptask.Show();
}
private void Image_Tap_1(object sender, System.Windows.Input.GestureEventArgs e)
{
ptask.PhoneNumber = ice2;
ptask.DisplayName = "Contact person 2";
ptask.Show();
}
private void Image_Tap_2(object sender, System.Windows.Input.GestureEventArgs e)
{
ptask.PhoneNumber = ice3;
ptask.DisplayName = "Contact person 3";
ptask.Show();
}
private void UserControl_Loaded(object sender, RoutedEventArgs e)
{
IsolatedStorageSettings appSettings = IsolatedStorageSettings.ApplicationSettings;
appSettings.Contains("fullName");
fullName.Text = (string)appSettings["fullName"];
address.Text = (string)appSettings["address"];
phone1.Text = (string)appSettings["ICE1"];
phone2.Text = (string)appSettings["ICE1"];
phone3.Text = (string)appSettings["ICE1"];
ice1 = phone1.Text;
ice2 = phone2.Text;
ice3 = phone3.Text;
}
especially this part which is supposed to get data from dictionary:
fullName.Text = (string)appSettings["fullName"];
address.Text = (string)appSettings["address"];
phone1.Text = (string)appSettings["ICE1"];
phone2.Text = (string)appSettings["ICE1"];
phone3.Text = (string)appSettings["ICE1"];

IsolatedStorage Settins works like a dictionary.
I think you should change:
private IsolatedStorageSettings userSettings = IsolatedStorageSettings.ApplicationSettings;
I would rather use method Contains to check whether key is there:
if (userSettings.Contains("ICE1")||
userSettings.Contains("ICE2") ||
userSettings.Contains("ICE3") ||
userSettings.Contains("address") ||
userSettings.Contains("fullName"))
According to MSDN, Settings are saved when the Application is closed or you call Save:
Data written to the IsolatedStorageSettings object is saved when the application that
uses the class is closed. If you want your application to write to isolated storage
immediately, you can call the Save method in application code.
EDIT
Sample code to play with:
public partial class MainPage : PhoneApplicationPage
{
private IsolatedStorageSettings userSettings = IsolatedStorageSettings.ApplicationSettings;
public MainPage()
{
InitializeComponent();
bool isKey = userSettings.Contains("anyKey"); //toggle break point at this line
userSettings.Add("anyKey", "myValue");
isKey = userSettings.Contains("anyKey");
string value = (string)userSettings["anyKey"];
}
}

IsolatedStorageSetting stores data in key/value pair. If there exist a key there must would be a value regarding this key. so just simpley check whether key exist in setting or not using if(settings.Contains("YourKey")). If the condition true do your work. Thanks

Related

Mobile Vision Searching cameraSource detections for items in a list

I am currently trying to write an android app in which a user can blacklist any food ingredients he or she wants to avoid. The user should then be able to scan a label and instantly be told whether or not any blacklisted ingredients are found via text recognition.
I am using a cameraSource to detect the text in real time which appears to somewhat work, but only when very few words are present on screen. When there are too many words on screen, it cannot find anything.
What is going wrong when larger amounts of words are present?
private SurfaceView cameraView;
private TextView textView;
private CameraSource cameraSource;
private const int RequestCameraPermissionID = 1001;
public JavaList<string> userIngredients;
public ISharedPreferences pref;
public ISharedPreferencesEditor edit;
public Bitmap imageBitmap;
protected override void OnCreate(Bundle bundle)
{
base.OnCreate(bundle);
// Set our view from the "main" layout resource
SetContentView(Resource.Layout.ScanLayout);
cameraView = FindViewById<SurfaceView>(Resource.Id.surface_view);
textView = FindViewById<TextView>(Resource.Id.text_view);
pref = Application.Context.GetSharedPreferences("UserPrefs", FileCreationMode.Private);
edit = pref.Edit();
var preferences = pref.GetStringSet("UserPrefs", new JavaList<string>());
userIngredients = new JavaList<string>(preferences);
var bitmapOptions = new BitmapFactory.Options();
TextRecognizer textRecognizer = new TextRecognizer.Builder(ApplicationContext).Build();
if (!textRecognizer.IsOperational)
{
Log.Error("Main Activity", "Detector dependancies are not yet available");
}
else
{
cameraSource = new CameraSource.Builder(ApplicationContext, textRecognizer)
.SetFacing(CameraFacing.Back)
.SetRequestedFps(2.0f)
.SetAutoFocusEnabled(true)
.Build();
cameraView.Holder.AddCallback(this);
textRecognizer.SetProcessor(this);
}
}
public void SurfaceCreated(ISurfaceHolder holder)
{
if (ActivityCompat.CheckSelfPermission(ApplicationContext, Manifest.Permission.Camera) != Android.Content.PM.Permission.Granted)
{
//Request Permission
ActivityCompat.RequestPermissions(this, new string[] {
Android.Manifest.Permission.Camera
}, RequestCameraPermissionID);
return;
}
cameraSource.Start(cameraView.Holder);
}
public void SurfaceDestroyed(ISurfaceHolder holder)
{
cameraSource.Stop();
}
public void ReceiveDetections(Detections detections)
{
bool blackListedFound = false;
SparseArray items = detections.DetectedItems;
if (items.Size() != 0)
{
textView.Post(() =>
{
for (int i = 0; i < items.Size(); ++i)
{
for (int j = 0; j < userIngredients.Size(); j++)
{
if (((TextBlock)items.ValueAt(i)).Value.Equals(userIngredients[j]))
{
blackListedFound = true;
textView.Text = "Not reccomended\nIngredient Found: " + userIngredients[j];
}
}
}
});
}
else if (blackListedFound == false)
textView.Post(() =>
{
textView.Text = "No Ingredients found";
});
}
}
}
Here are some example images of my current problem;
Here is an example of the app failing to find a blacklisted ingredient (Water);

Removing First Item from listbox while binding to listbox

I have parsed the feed http://www.toucheradio.com/toneradio/android/toriLite/AndroidRSS.xml
And all items from rss feed displayed in listbox.Now I dont want to get first item I have to omit it.How Can I do it.
MainPage.xaml.cs:
namespace tori
{
public partial class MainPage : PhoneApplicationPage
{
// Constructor
public MainPage()
{
InitializeComponent();
// is there network connection available
if (!System.Net.NetworkInformation.NetworkInterface.GetIsNetworkAvailable())
{
MessageBox.Show("No network connection available!");
return;
}
// start loading XML-data
WebClient downloader = new WebClient();
Uri uri = new Uri(" http://www.toucheradio.com/toneradio/android/toriLite/AndroidRSS.xml", UriKind.Absolute);
downloader.DownloadStringCompleted += new DownloadStringCompletedEventHandler(ChannelDownloaded);
downloader.DownloadStringAsync(uri);
}
void ChannelDownloaded(object sender, DownloadStringCompletedEventArgs e)
{
if (e.Result == null || e.Error != null)
{
MessageBox.Show("There was an error downloading the XML-file!");
}
else
{
// Deserialize if download succeeds
XDocument document = XDocument.Parse(e.Result);
var queue = from item in document.Descendants("item")
select new Item
{
title = item.Element("title").Value
,
link = item.Element("link").Value
,
ThumbnailUrl = item.Element(item.GetNamespaceOfPrefix("media") + "thumbnail").Attribute("url").Value
,
};
itemsList.ItemsSource = queue;
}
}
public class Item
{
public string title { get; set; }
public string ThumbnailUrl { get; set; }
public string link { get; set; }
}
If I write queue.RemoveAt(0);
i was getting error at RemoveAt.
Can anybody please tell me how can I do that.
Many Thanks in advance.
You can easily do this using LINQ Skip extension method (documentation here).
Just try the sample below:
itemsList.ItemsSource = queue.Skip(1);
As well you can rewrite the query to omit the first item before applying the projection in the select method using the methods chain approach:
var queue = document.Descendants("item")
.Skip(1)
.Select(item => new Item
{
title = item.Element("title").Value,
link = item.Element("link").Value,
ThumbnailUrl = item.Element(item.GetNamespaceOfPrefix("media") + "thumbnail").Attribute("url").Value,
})
.ToList();
itemsList.ItemsSource = queue;
UPDATE / DUE TO COMMENTS
And as well if you need to skip items at certain indexes you may use the Where method and the HasSet as in the sample below:
var document = XDocument.Parse(e.Result);
var indexes = new HashSet<int> { 1, 3, 4 };
var queue = document.Descendants("item")
.Select(item => new Item
{
title = item.Element("title").Value,
link = item.Element("link").Value,
ThumbnailUrl =
item.Element(item.GetNamespaceOfPrefix("media") + "thumbnail").Attribute("url").Value,
})
.Where((x, i) => !indexes.Contains(i))
.ToList();
Items.ItemsSource = queue;

Toggle Button Checked Property Windows Phone 8

I add a toggle button on Windows Phone 8 . When i checked (on), its save a value in Isolated storage and I check that value in constructor whatever it has a toggle value or null. If there is a toggle value I want to display toggle button checked . But I dont know the property to how to checked it when application is run .
Toggle Button XAML :
<toolkit:ToggleSwitch x:Name="toggle" Content="On" Width="165" FontSize="28" VerticalAlignment="Center" HorizontalAlignment="Right"/>
C# :
public Subscription()
{
InitializeComponent();
this.toggle.Checked += new EventHandler<RoutedEventArgs>(toggle_Checked);
this.toggle.Unchecked += new EventHandler<RoutedEventArgs>(toggle_Unchecked);
var appSettings = IsolatedStorageSettings.ApplicationSettings;
if (HasSValue() == "NoValue")
{
// Here i want to Display toggle button unchecked
}
else
{
// Here i want to Display toggle button checked
}
}
void toggle_Unchecked(object sender, RoutedEventArgs e)
{
this.toggle.Content = "Off";
this.toggle.SwitchForeground = new SolidColorBrush(Colors.Red);
var appSettings = IsolatedStorageSettings.ApplicationSettings;
appSettings.Remove("toggleValue");
appSettings.Save();
}
void toggle_Checked(object sender, RoutedEventArgs e)
{
this.toggle.Content = "On";
this.toggle.SwitchForeground = new SolidColorBrush(Colors.Green);
MessageBox.Show("R U Sure ?");
var appSettings = IsolatedStorageSettings.ApplicationSettings;
appSettings.Add("toggleValue", "MAHIN");
appSettings.Save();
}
public string HasSValue()
{
var appSettings = IsolatedStorageSettings.ApplicationSettings;
if (appSettings.Contains("toggleValue"))
{
return (string) appSettings["toggleValue"];
}
else
{
return "NoValue";
}
}
Try this
if (HasSValue() == "NoValue")
{
this.toggle.IsChecked = false;
}
else
{
this.toggle.IsChecked = true;
}
Hope this helps
Update your Constructor as follows
public Subscription()
{
InitializeComponent();
var appSettings = IsolatedStorageSettings.ApplicationSettings;
if (HasSValue() == "NoValue")
{
// Here i want to Display toggle button unchecked
}
else
{
// Here i want to Display toggle button checked
}
this.toggle.Checked += new EventHandler<RoutedEventArgs>(toggle_Checked);
this.toggle.Unchecked += new EventHandler<RoutedEventArgs>(toggle_Unchecked);
}

How to send windows phone 8 application data to server

I have only two input parameters in my feedback form, email, feedback and a submit button only.
I want to send(POST) this data to a specific URL like http://questoons.com/data.php
So how can I post data from windows phone 8 app to a specific URL?
Any code sample or web link would be highly appreciated.
I reccomend to write a specific class for working with POST.
public class PostRequestParameters
{
public List<PostRequestParameterObject> prms;
public PostRequestParameters()
{
prms = new List<PostRequestParameterObject>();
}
public void AddPair(string id, string val)
{
prms.Add(new PostRequestParameterObject(id, val));
}
public String FormPostData()
{
StringBuilder buffer = new StringBuilder();
for (int i = 0; i < prms.Count; i++)
{
if (i == 0)
{
buffer.Append(System.Net.HttpUtility.UrlEncode(prms[i].id) + "=" + System.Net.HttpUtility.UrlEncode(prms[i].value));
}
else
{
buffer.Append("&" + System.Net.HttpUtility.UrlEncode(prms[i].id) + "=" + System.Net.HttpUtility.UrlEncode(prms[i].value));
}
}
return buffer.ToString();
}
}
public class PostRequestParameterObject
{
public string id;
public string value;
public PostRequestParameterObject(string id, string val)
{
this.id = id;
this.value = val;
}
}
Then you can use it to send POST data:
private void buttonSend_Tap(object sender, System.Windows.Input.GestureEventArgs e)
{
WebClient wc = new WebClient();
wc.UploadStringCompleted += new UploadStringCompletedEventHandler(wc_UploadStringCompleted);
wc.Headers["Content-Type"] = "application/x-www-form-urlencoded";
wc.Encoding = Encoding.UTF8;
PostRequestParameters prms = new PostRequestParameters();
prms.AddPair("par1", textBox1.Text);
prms.AddPair("par2", textBox2.Text);
prms.AddPair("par3", GetMPar3());
wc.UploadStringAsync(new Uri(url), "POST", prms.FormPostData(), null);
}
// you can parse response here
private void wc_UploadStringCompleted(object sender, UploadStringCompletedEventArgs e)
{
// do something
}
You can try using WebClient's UploadStringAsync() function :
string URI = "http://www.myurl.com/post.php";
string myParameters = "param1=value1&param2=value2&param3=value3";
var wc = new WebClient();
wc.Headers[HttpRequestHeader.ContentType] = "application/x-www-form-urlencoded";
wc.UploadStringAsync(new Uri(URI, UriKind.Absolute), myParameters);
[For Reference]

SWT JFace: SelectionProvider not working in TabFolder

In a GraphicalEditor I created a tab folder:
private final String[] tabNames = { "Text", "Image" };
private ResourcesTextComposite comText;
private ResourcesImageComposite comImage;
...
public void createPartControl(Composite parent) {
...
tabFolder = new TabFolder(parent, SWT.BORDER);
for (int loopIndex = 0; loopIndex < tabNames.length; loopIndex++) {
TabItem tabItem = new TabItem(tabFolder, SWT.NULL);
tabItem.setText(tabNames[loopIndex]);
if (loopIndex == 0) {
comText = new ResourcesTextComposite(tabFolder, SWT.NONE,
resources);
tabItem.setControl(comText);
} else if (loopIndex == 1) {
comImage = new ResourcesImageComposite(tabFolder, SWT.NONE,
resources);
tabItem.setControl(comImage);
}
}
...
}
it has 2 tab items and each item has a composite in it, and each composite has a TableViewer respectively.
I tried this to make each TableViewer the selection provider when the user selects the corresponding tab item (the same function createPartControl of the editor):
public void createPartControl(Composite parent) {
...
tabFolder.addSelectionListener(new SelectionListener() {
public void widgetSelected(SelectionEvent e) {
int tabIdx = tabFolder.getSelectionIndex();
getSite().setSelectionProvider(null);
if (tabIdx == 0) {
getSite().setSelectionProvider(comText.getViewer());
} else if (tabIdx == 1) {
getSite().setSelectionProvider(comImage.getViewer());
}
System.out.println("widgetSelected" + getSite() + ": "
+ getSite().getSelectionProvider());
}
public void widgetDefaultSelected(SelectionEvent e) {
widgetSelected(e);
}
});
...
}
I hope when I select a row in a TableViewer, the Properties view will show the selected model's properties, I've complete those IPropertySource things and they works well in other editors that has no tab folders, so I think the problem should be in the Selection Provider area.
Any ideas or has anyone encountered the same problem?
If you have multiple selection providers in a view or editor, then you need to use a mediator like org.eclipse.jdt.internal.ui.viewsupport.SelectionProviderMediator. Note that it is unfortunately internal, so you need to copy it to your own project