search contacts by phone number, filter using a 3 digit prefix - windows-phone-7

I want to get all the phone numbers in my contacts that start with a specific 3 digits, eg "012" when i hit a button.
I've been working on it using the following code:
private void ButtonContacts_Click(object sender, RoutedEventArgs e)
{
Contacts cons = new Contacts();
//Identify the method that runs after the asynchronous search completes.
cons.SearchCompleted += new EventHandler<ContactsSearchEventArgs>(Contacts_SearchCompleted);
//Start the asynchronous search.
cons.SearchAsync("0109", FilterKind.PhoneNumber, "State String 5");
}
void Contacts_SearchCompleted(object sender, ContactsSearchEventArgs e)
{
try
{
//Bind the results to the user interface.
ContactResultsData.DataContext = e.Results;
}
catch (System.Exception)
{
//No results
}
if (ContactResultsData.Items.Any())
{
ContactResultsLabel.Text = "results";
}
else
{
ContactResultsLabel.Text = "no results";
}
}
but the FilterKind.PhoneNumber only works when it has at least the last 6 digits matched of a phone number.
Any idea how to achieve this?
BTW I'm a total beginner.

As you say, the filter of the contacts api only match if the last six digits are the same, you can see it in the documentation, so you can't do it using it.
In my opinion the best way to do it is receive the all contact list and after that use LINQ to find the contact that you want.
private void ButtonBase_OnClick(object sender, RoutedEventArgs e)
{
var contacts = new Contacts();
contacts.SearchCompleted += Contacts_SearchCompleted;
contacts.SearchAsync(null, FilterKind.None, null);
}
void Contacts_SearchCompleted(object sender, ContactsSearchEventArgs e)
{
var results = e.Results.ToArray();
var myContacts = results.Where(c => c.PhoneNumbers.Any(p => p.PhoneNumber.StartsWith("66"))).ToArray();
}
You can see in the last line the query to find the contacts that some of their numbers start with 66. You can change this query as you want to match the numbers that you want.

Related

Read Data from URL / Windows Phone

Please I need help in my issue!
I have the following link ; which stored specific numbers (data) I will use it in my windows phone application.
http://jaradat.eb2a.com/read.php
How I can read the latest number stored in the link (this number will change) ; and show it in my windows phone application.
Should I use the webclient to access the data in url like the following ?
WebClient wc = new WebClient();
wc.DownloadStringCompleted += HttpCompleted;
wc.DownloadStringAsync(new Uri("http://jaradat.eb2a.com/read.php"));
private void HttpCompleted(object sender, DownloadStringCompletedEventArgs e)
{
if (e.Error == null)
{
// do something here
}
And How I can read the latest value in the link ? should divide it to tokens ?
The method you have indicated in your question is correct for retrieving the data from the link. Though there are other ways of doing it.
Here are some references if you want to learn further.
Making a HTTP request and listening its completion in Windows Phone
HttpWebRequest Fundamentals - Windows Phone Services Consumption - Part 1
HttpWebRequest Fundamentals - Windows Phone Services Consumption - Part 2
Your question seems to be about how to retrieve the last value in the response.
Try this...
private void HttpCompleted(object sender, DownloadStringCompletedEventArgs e)
{
if (e.Error == null)
{
//this will break the string into two tokens
string[] first_lot = e.Result.Split('"');
//assuming you want to read the first lot first_lot[0].Split(',');
// seccond lot first_lot[1].Split(',');
string[] numbers = first_lot[0].Split(',');
int last_digit = int.Parse(numbers[numbers.Length - 1]);
}
}
Observations
If possible, tweak the server code to return only one digit. It will
save the application user a lot of data costs.
Consider using JSON data format as the response format on the server side code.
Just do it
WebClientwc = new WebClient();
wc.DownloadStringCompleted += HttpCompleted;
wc.DownloadStringAsync(new Uri("http://jaradat.eb2a.com/read.php"));
private void HttpCompleted(object sender, DownloadStringCompletedEventArgs e)
{
if (e.Error == null)
{
var resultString = e.Result;
var parts = resultString.Split('"').Select(n => n).ToArray();
int[] resultIntArrayFirst = parts[1].Split(',').Select(n => Convert.ToInt32(n)).ToArray();
double [] resultIntArraySecond = parts[3].Split(',').Select(Convert.ToDouble).ToArray();
double lastValue = resultIntArraySecond[resultIntArraySecond.Length - 1];
}
}
Hope its help.

wp7 How can i send with email a google or bing hyperlink with my current location

I just want to send (email) my current location with hyperlink (when you click it, it will open google or bing map with the location) and not like text.
As of now there is no support for HTML data in the email sent by the EMailComposeTask.You can refer to this discussion.
Easy: use the EmailComposeTask and in the text just set something with maps:11.111,22.222, where 11.111 is the latitude and 22.222 is the longitude.
Windows Phone email client will see the "maps:" text and auto-convert it to a link that opens with the Bing maps app!
You could try the following:
private void StartLocationButton_Click(object sender, RoutedEventArgs e)
{
// The watcher variable should be scoped to the class
if (watcher == null)
{
watcher = new GeoCoordinateWatcher(GeoPositionAccuracy.High);
watcher.MovementThreshold = 20;
watcher.StatusChanged += new
EventHandler<GeoPositionStatusChangedEventArgs>(watcher_StatusChanged);
}
watcher.Start();
}
void watcher_StatusChanged(object sender, GeoPositionStatusChangedEventArgs e)
{
Dispatcher.BeginInvoke(() => MyStatusChanged(e)); //Call BeginInvoke as discussed below…
}
void MyStatusChanged(GeoPositionStatusChangedEventArgs e)
{
if (e.Status == GeoPositionStatus.Ready)
{
var link = String.Format("http://www.google.com/maps?q={0}+{1}",
e.Position.Location.Latitude.ToString("0.000000"),
e.Position.Location.Longitude.ToString("0.000000"));
EmailComposeTask emailComposeTask = new EmailComposeTask();
emailComposeTask.To = "send#mail.com";
emailComposeTask.Body = link;
emailComposeTask.Subject = "GPS";
emailComposeTask.Show();
//Stop the Location Service to conserve battery power.
watcher.Stop();
}
}

Unable to show the selected item in the Wp7 Listpicker control

Basically i am trying to pull the contacts from the phone and showing them in the Listpicker control for a feature in my app. I have two Listpickers, one for name of contacts list and the other showing the list of phonenumbers for the chosen contact.
Here is my code:
//Declarations
ContactsSearchEventArgs e1;
String SelectedName;
String SelectedNumber;
List<string> contacts = new List<string>();
List<string> phnum = new List<string>();
public AddressBook() // Constructor
{
InitializeComponent();
Contacts contacts = new Contacts();
contacts.SearchCompleted += new EventHandler<ContactsSearchEventArgs>(contacts_SearchCompleted);
contacts.SearchAsync(string.Empty,FilterKind.None,null);
}
void contacts_SearchCompleted(object sender, ContactsSearchEventArgs e)
{
e1 = e;
foreach (var result in e.Results)
{
if (result.PhoneNumbers.Count() != 0)
{
contacts.Add(result.DisplayName.ToString());
}
}
Namelist.ItemsSource = contacts;
}
private void Namelist_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
SelectedName = (sender as ListPicker).SelectedItem.ToString();
phnum.Clear();
foreach (var result in e1.Results)
{
if (SelectedName == result.DisplayName)
{
phnum.Add(result.PhoneNumbers.FirstOrDefault().ToString());
}
}
Numbers.ItemsSource = phnum;
}
private void Numbers_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
SelectedNumber = (sender as ListPicker).SelectedItem.ToString();
}
Am able to populate the Numberlist with phonenumbers for the chosen name at the Listpicker background, but the number is not showing up in the front. I think Numbers_SelectionChanged() event is called only one time when the page loads and am not seeing it triggerd when i change the contact list. Anyone has an idea of where am going wrong ?
If you change
List<string>
To
ObservableCollection<string>
this should work.
Also then you only need to set the ItemSource once, in Xaml or you constructor.
But you may run into another issue with the November 2011 Toolkit and ListPicker.
See more in thread.
private void Namelist_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
SelectedName = (sender as ListPicker).SelectedItem.ToString();
phnum = new List<string>(); // Changed instead of phnum.Clear()
foreach (var result in e1.Results)
{
if (SelectedName == result.DisplayName)
{
phnum.Add(result.PhoneNumbers.FirstOrDefault().ToString());
}
}
Numbers.ItemsSource = phnum;
}
This works !!. While debugging i found its phnum.Clear() giving a problem. So i thought to create a new instance of phnum list for selected contact.

How to get all contacts and write into file for Windows phone 7

The problem I want to solve:
Get all the contacts info like name and Mobile phone and write it into file and save in ISO.
How to use SearchAsync if I want to search available contacts in the phone?
How to iterate the return-results and write to file one by one of the contact into a file?
Here's the code I have:
private void btnSearch_Click(object sender, RoutedEventArgs e)
{
Contacts contacts = new Contacts();
contacts.SearchCompleted += new EventHandler<ContactsSearchEventArgs>(contacts_SearchCompleted);
contacts.SearchAsync(displayName,FilterKind.DisplayName,null);
//search for all contacts
contacts.SearchAsync(string.Empty, FilterKind.None, null);
}
Update:
The below code throw NullException error if the PhoneNumber is Empty. Why?
How to get all the possibile phone number other than result.PhoneNumbers.FirstOrDefault().ToString();
Same question for EmailAddresses
Using this to search all contacts in the phone:
contacts.SearchAsync(searchterm, FilterKind.None, null);
void contacts_SearchCompleted(object sender, ContactsSearchEventArgs e)
{
int intTTL = e.Results.Count();
if (intTTL != 0)
{
MessageBox.Show(intTTL.ToString());
foreach (var result in e.Results)
{
string strTTL;
string strName = result.DisplayName;
string MobileNo = result.PhoneNumbers.FirstOrDefault().ToString();
strTTL = strName + "," + MobileNo;
MessageBox.Show(strTTL);
}
else
{
MessageBox.Show("You have not entered any contact info at all.");
}
}
Have a look at this article to see how to get the Contacts:
To iterate:
void contacts_SearchCompleted(object sender, ContactsSearchEventArgs e)
{
foreach(var contact in e.Results)
{
// write to Isolated storage
}
}
See this MSDN page for writing files in isolated storage

How to add a numeric textbox in WP7 which can take a float value?

I am developing WP7 application. I am new to the WP7. I am also new to the silverlight. I have a textbox in my application. In this textbox user enters the amount. I want to give the facility in my application so that user can enter the float amount ( for e.g. 1000.50 or 499.9999). The user should be able to enter either two digit or four digit after the '.' .My code for the textbox is as follows.
<TextBox InputScope="Number" Height="68" HorizontalAlignment="Left" Margin="-12,0,0,141" Name="AmountTextBox" Text="" VerticalAlignment="Bottom" Width="187" LostFocus="AmountTextBox_LostFocus" BorderBrush="Gray" MaxLength="10"/>
I have done the following validations for the above textbox.
public void AmountTextBox_LostFocus(object sender, RoutedEventArgs e)
{
foreach (char c in AmountTextBox.Text)
{
if (!char.IsDigit(c))
{
MessageBox.Show("Only numeric values are allowed");
AmountTextBox.Focus();
return;
}
}
}
How to resolve the above issue. Can you please provide me any code or link through which I can resolve the above issue. If I am doing anything wrong then please guide me.
Download the free book Programming Windows Phone 7 by Charles Petzold. On page 380, in section TextBox Binding Updates, under Chapter 12: Data Bindings, he has an excellent example on validating floating point input.
For limiting the user input to 2 or 4 decimal places you'll have to add some logic to TextBox's TextChanged callback. For instance, you could convert the float to a string, search for the decimal and then figure out the length of the string to the right of the decimal.
On the other hand, if you just want to round the user input to 2 or 4 digits, take a look at the Fixed-Point ("F") Format Specifier section on this page.
I do the validation this way as shown in the code below.
No need for checking char by char and user culture is respected!
namespace Your_App_Namespace
{
public static class Globals
{
public static double safeval = 0; // variable to save former value!
public static bool isPositiveNumeric(string strval, System.Globalization.NumberStyles NumberStyle)
// checking if string strval contains positive number in USER CULTURE NUMBER FORMAT!
{
double result;
boolean test;
if (strval.Contains("-")) test = false;
else test = Double.TryParse(strval, NumberStyle, System.Globalization.CultureInfo.CurrentCulture, out result);
// if (test == false) MessageBox.Show("Not positive number!");
return test;
}
public static string numstr2string(string strval, string nofdec)
// conversion from numeric string into string in USER CULTURE NUMBER FORMAT!
// call example numstr2string("12.3456", "0.00") returns "12.34"
{
string retstr = "";
if (Globals.isPositiveNumeric(strval, System.Globalization.NumberStyles.Number)) retstr = double.Parse(strval).ToString(nofdec);
else retstr = Globals.safeval.ToString(nofdec);
return retstr;
}
public static string number2string(double numval, string nofdec)
// conversion from numeric value into string in USER CULTURE NUMBER FORMAT!
// call example number2string(12.3456, "0.00") returns "12.34"
{
string retstr = "";
if (Globals.isPositiveNumeric(numval.ToString(), System.Globalization.NumberStyles.Number)) retstr = numval.ToString(nofdec);
else retstr = Globals.safeval.ToString(nofdec);
return retstr;
}
}
// Other Your_App_Namespace content
}
// This the way how to use those functions in any of your app pages
// function to call when TextBox GotFocus
private void textbox_clear(object sender, System.Windows.RoutedEventArgs e)
{
TextBox txtbox = e.OriginalSource as TextBox;
// save original value
Globals.safeval = double.Parse(txtbox.Text);
txtbox.Text = "";
}
// function to call when TextBox LostFocus
private void textbox_change(object sender, System.Windows.RoutedEventArgs e)
{
TextBox txtbox = e.OriginalSource as TextBox;
// text from textbox into sting with checking and string format
txtbox.Text = Globals.numstr2string(txtbox.Text, "0.00");
}
You can always use this regex [-+]?[0-9].?[0-9] to determine if its a floating number.
public void AmountTextBox_LostFocus(object sender, RoutedEventArgs e)
{
Regex myRange = new Regex(#"[-+]?[0-9]*\.?[0-9]");
if (myRange.IsMatch(textBox1.Text))
// Match do whatever
else
// No match do whatever
}
The following code is working fine for me. I have tested it in my application. In the following code by adding some validations we can treat our general textbox as a numeric textbox which can accept the float values.
public void AmountTextBox_LostFocus(object sender, RoutedEventArgs e)
{
foreach (char c in AmountTextBox.Text)
{
if (!char.IsDigit(c) && !(c == '.'))
{
if (c == '-')
{
MessageBox.Show("Only positive values are allowed");
AmountTextBox.Focus();
return;
}
MessageBox.Show("Only numeric values are allowed");
AmountTextBox.Focus();
return;
}
}
string [] AmountArr = AmountTextBox.Text.Split('.');
if (AmountArr.Count() > 2)
{
MessageBox.Show("Only one decimal point are allowed");
AmountTextBox.Focus();
return;
}
if (AmountArr.Count() > 1)
{
int Digits = AmountArr[1].Count();
if (Digits > 2)
{
MessageBox.Show("Only two digits are allowed after decimal point");
AmountTextBox.Focus();
return;
}
}
}

Resources