Append contacts in contact list in WP8 - windows-phone-8

I want to add more that one contacts to contact list from a xml file, but saveContactTask.Show();
added one contact to contact list, Please anyone tell me how to resolve this issue .
This is my code:
private void AddContacts(object sender, RoutedEventArgs e)
{
using (IsolatedStorageFile istf = IsolatedStorageFile.GetUserStoreForApplication())
{
using (IsolatedStorageFileStream istfs = istf.OpenFile("MyContacts.xml",FileMode.Open))
{
XDocument doc = XDocument.Load(istfs);
var query = from d in doc.Root.Descendants("Contacts")
select new
{
firstName = d.Element("name").Value,
mobilePhone = d.Element("phone").Value
};
foreach (var po in query)
{
saveContactTask.FirstName = po.firstName;
saveContactTask.MobilePhone = po.mobilePhone;
saveContactTask.Show();
}
}
}

SaveContactTask class is designed to add only one contact at a time and Show() function is asynchronous. You can't add second contact until the first call will be finished. Your code should be rewritten to react on saveContactTask.Completed += new EventHandler<SaveContactResult>(saveContactTask_Completed); event and start adding the second(etc) contact only when the previous is finished. There is possibility, that new SaveContactTask should be used for the second(etc) contact, bear it in mind.
Try something like this (it's only a sample of idea):
private List<Contact> listToAdd;
private SaveContactTask saveTask;
saveTask.Completed += addComplete;
void addComplete(...)
{
if ( listToAdd.Count > 0 )
{
Contact contact = listToAdd[0];
listToAdd.RemoveAt(0);
saveTask. (set values from contact)
saveTask.Show();
}
}

Related

Wait until async operation ends Windows Phone

I am trying to parse some pois from a xml download from a server and I saw that it is done after the program continues in the main thread. I haven't found a way to solve it because I need it.
using System.Threading;
namespace XML_Parser
{
class XMLParserPOI_Wiki
{
private static XMLParserPOI_Wiki objSingle = new XMLParserPOI_Wiki();
public static XMLParserPOI_Wiki ObjSingle
{
get { return objSingle; }
set { objSingle = value; }
}
private List<POI> places;
public List<POI> Places
{
get { return places; }
}
private XMLParserPOI_Wiki()
{
}
public void parseWikitude(string url)
{
places = new List<POI>();
WebClient wc = new WebClient();
wc.DownloadStringCompleted += HttpsCompleted;
wc.DownloadStringAsync(new Uri(url));
}
private void HttpsCompleted(object sender, DownloadStringCompletedEventArgs e)
{
if (e.Error == null)
{
XDocument xdoc = XDocument.Parse(e.Result, LoadOptions.None);
XNamespace ns = "http://www.opengis.net/kml/2.2";
XNamespace ns2 = "http://www.openarml.org/wikitude/1.0";
var placemarkers = xdoc.Root.Descendants(ns + "Placemark");
places =
(from query in xdoc.Root.Descendants(ns + "Placemark")
select new POI
(
...
)).ToList();
System.Diagnostics.Debug.WriteLine("Lista");
System.Diagnostics.Debug.WriteLine(places.Count);
}
}
}
}
In my main class:
XMLParserPOI_Wiki parserXML = XMLParserPOI_Wiki.ObjSingle;
parserXML.parseWikitude("http://myurl.php");
System.Diagnostics.Debug.WriteLine("Lista de pois");
System.Diagnostics.Debug.WriteLine(parserXML.Places.Count);
for (int i = 0; i < parserXML.Places.Count; i++)
{
System.Diagnostics.Debug.WriteLine(parserXML.Places[i].getName());
}
It prints Lista de POis and 0, before Lista and X (number of pois)
I guess I should freeze main thread but I tried a couple of times with some examples and they didn't work.
Can you point me to any tutorial about this? More than get an answer I want to understand how to deal with this kind of operations
First of all, you don't want to block (freeze) the UI thread EVER!
This is called asynchronous programming. There are two things you can do to solve your problem (I recommend option 2!):
Use the classic callback model. You basically call some long operation on a background thread and give a function to it, to execute when the long operation is done. Here's how to do it in your case.
At the end of the HttpsCompleted method, invoke what you need on the UI Thread using:
Deployment.Current.Dispatcher.BeginInvoke(delegate() {
//The code here will be invoked on the UI thread
});
If you want to make the parseWikitude method reusable, you should pass an Action to it. This way you can call it from multiple places and tell it what to do on the UI thread when the parsing is done. Something like this:
public void parseWikitude(string url, Action callback) {
places = new List<POI>();
WebClient wc = new WebClient();
wc.DownloadStringCompleted += HttpsCompleted;
wc.DownloadStringAsync(new Uri(url), callback);
}
private void HttpsCompleted(object sender, DownloadStringCompletedEventArgs e)
{
if (e.Error == null)
{
...
var callback = (Action)e.UserState;
Deployment.Current.Dispatcher.BeginInvoke(callback);
}
}
//And then when you use it, you do it like that
parserXML.parseWikitude("http://myurl.php", delegate() {
//The code here will be executed on the UI thread, after the parsing is done
});
Use the (rather) new asnyc pattern in .NET. You should read about this, as it is one of the best features of .NET if you ask me. :) It basically does the callback thing automatically and makes the code a lot easier to read/maintain/work-with. Once you get used to it, that is.
Here's an example:
public Task<List<POI>> parseWikitude(string url) {
TaskCompletionSource<List<POI>> resultTaskSource = new TaskCompletionSource<List<POI>>();
WebClient wc = new WebClient();
wc.DownloadStringCompleted += HttpsCompleted;
wc.DownloadStringAsync(new Uri(url), resultTaskSource);
return resultTaskSource.Task;
}
private void HttpsCompleted(object sender, DownloadStringCompletedEventArgs e)
{
if (e.Error == null)
{
//If needed, run the code here in a background thread
//...
var resultTaskSource = (TaskCompletionSource<List<POI>>)e.UserState;
resultTaskSource.SetResult(places);
}
}
//And when you need to use it, do it like that (note, this must be invoked in an async method!)
var places = await parser.parseWikitude("http://myurl.php");
//The code here will be executed on the same thread when the parsing is done, but the thread will not be blocked while the download is happening.
So, these are the two ways you can handle it. Option one is old-school, classic and easy. Option two is the new and cool way of doing async stuff. It really is a must-know. Simplifies a lot of things once you get used to it.
P.S. Sorry if I got carried away. :D

Fetching Contacts From People Hub

I am building a Windows Phone 8 application. For that I require to fetch contacts from People Hub App. Is there any way I can keep these contacts even after the application closes?
I have looked into data caching but if the contact has been updated then caching won't work.
This can be done.
I've implemented this with the Group Contacts app.
In my solution, I used SQLite to store contacts into various categories based on user preference.
When the app starts up, I initialize my local database using SQLite and pull contacts from there as well as retrieving all the contacts the phone itself.
Example:
await ContactsRepository.Instance.Initialize();
var appContacts = await ContactsRepository.Instance.Get();
var phoneContacts = await ContactServices.Instance.LoadContacts(Contacts, SelectedCategory);
MergeContacts(appContacts, phoneContacts);
.
.
When ever the app starts up, it needs to create a database if one does not already exist.
Example:
public async Task Initialize()
{
_connection = new SQLiteAsyncConnection(Constants.DATABASE_FILE_NAME);
await EnsureTableExist<ContactReference>(_connection);
}
private async Task EnsureTableExist<T>(SQLiteAsyncConnection connection) where T : new()
{
bool noTableExists = false;
try
{
var query = await connection.Table<T>().FirstOrDefaultAsync();
}
catch (SQLiteException ex)
{
if (ex.Message.Contains("no such table"))
{
noTableExists = true;
}
}
if (noTableExists)
{
await connection.CreateTableAsync<T>();
}
}
Windows 8.1 uses a ContactManager to retrieve contacts from the People Hub.
Example:
public async Task<ObservableCollection<Contact>> LoadContacts(ObservableCollection<Contact> contacts, Category category)
{
contacts.Clear();
try
{
var contactStore = await ContactManager.RequestStoreAsync();
var result = await contactStore.FindContactsAsync();
foreach (var item in result)
{
contacts.Add(item);
}
}
catch (Exception ex)
{
Debug.WriteLine(ex.Message);
}
return contacts;
}
Then I manage my contact collection between the phone's contact list and my app's contact list.
Example:
private void MergeContacts(ObservableCollection<ContactReference> appContacts, ObservableCollection<Contact> phoneContacts)
{
foreach (var contact in phoneContacts)
{
var contactExists = appContacts.Any(c => c.ContactId == contact.Id);
if (!contactExists)
{
OthersCategory.Contacts.Add(contact);
}
Category category = GetCategory(contact);
if (category == null)
{
OthersCategory.Contacts.Add(contact);
}
}
SortContacts(OthersCategory);
}
I created an entity class to support my local database operations.
Example:
public class ContactReference
{
[PrimaryKey]
public string ContactId { get; set; }
public string CategoryName { get; set; }
}
NOTE:
The emulator that VS2013 provides does not have a list of imaginary contacts.
As a result, I found testing easier by using my personal phone for debugging.

Exchange Web Services - How to retrieve a Contact using the Account extended property

I am using C# and the Exchange Web Services API and have been unable to find a way to retrieve a contact using the extended property named Account. We have used this field to hold an integer number that is meaningful to an in-house developed system. Under WebDAV, we knew how to retrieve the Contact but need some help (hopefully a short example or code snippet) to demonstrate how to do this.
I have used extended property with appointments, so maybe they work on the same concept as the contacts.
The Idea is to put a Guid for appointments as their native IDs are not constant.
private static readonly PropertyDefinitionBase AppointementIdPropertyDefinition = new ExtendedPropertyDefinition(DefaultExtendedPropertySet.PublicStrings, "AppointmentID", MapiPropertyType.String);
public static PropertySet PropertySet = new PropertySet(BasePropertySet.FirstClassProperties, AppointementIdPropertyDefinition);
//Setting the property for the appointment
public static void SetGuidForAppointement(Appointment appointment)
{
try
{
appointment.SetExtendedProperty((ExtendedPropertyDefinition)AppointementIdPropertyDefinition, Guid.NewGuid().ToString());
appointment.Update(ConflictResolutionMode.AlwaysOverwrite, SendInvitationsOrCancellationsMode.SendToNone);
}
catch (Exception ex)
{
// logging the exception
}
}
//Getting the property for the appointment
public static string GetGuidForAppointement(Appointment appointment)
{
var result = "";
try
{
appointment.Load(PropertySet);
foreach (var extendedProperty in appointment.ExtendedProperties)
{
if (extendedProperty.PropertyDefinition.Name == "AppointmentID")
{
result = extendedProperty.Value.ToString();
}
}
}
catch (Exception ex)
{
// logging the exception
}
return result;
}
Not sure if you still need this... but I just solved something close myself:
My answer here should be in the ballpark of what you want. I'm using a boolean as well as Account here:
ExchangeService service = this.GetService(); // my method to build service
FolderId folderID = GetPublicFolderID(service, "My Address Book");
ContactsFolder folder = ContactsFolder.Bind(service, folderID);
int folderCount = folder.TotalCount;
var guid = DefaultExtendedPropertySet.PublicStrings;
var epdAccount = new ExtendedPropertyDefinition(0x3A00, MapiPropertyType.String);
var epdCID = new ExtendedPropertyDefinition(0x3A4A, MapiPropertyType.String);
var epdCBLN = new ExtendedPropertyDefinition(guid, "CustomBln", MapiPropertyType.Boolean);
var epdCDBL = new ExtendedPropertyDefinition(guid, "CustomDbl", MapiPropertyType.Double);
var view = new ItemView(folderCount);
view.PropertySet = new PropertySet(BasePropertySet.FirstClassProperties);
view.PropertySet.Add(epdAccount);
view.PropertySet.Add(epdCID);
view.PropertySet.Add(epdCBLN);
view.PropertySet.Add(epdCDBL);
//var searchOrFilterCollection = new List<SearchFilter>();
//searchOrFilterCollection.Add(new SearchFilter.IsEqualTo(epdCBLN, true));
//searchOrFilterCollection.Add(new SearchFilter.IsEqualTo(epdAccount, "user"));
//var filter = new SearchFilter.SearchFilterCollection(LogicalOperator.And, searchOrFilterCollection);
var filter = new SearchFilter.IsEqualTo(epdAccount, "user");
var contacts = service.FindItems(folderID, filter, view);
foreach (Contact contact in contacts)
{
string Account;
int CID;
bool CBLN;
double CDBL;
contact.GetLoadedPropertyDefinitions();
contact.TryGetProperty(epdAccuont, out Account);
contact.TryGetProperty(epdCID, out CID);
contact.TryGetProperty(epdCBLN, out CBLN);
contact.TryGetProperty(epdCDBL, out CDBL);
Console.WriteLine(String.Format("{0, -20} - {1} - {2} - {3} - {4}"
, contact.DisplayName
, contact.EmailAddresses[EmailAddressKey.EmailAddress1]
, Account
, CID
, CBLN
, CDBL
));
}

SSIS Scripting Component: Get child records for creating Object

Got it working - Posted My solution below but will like to know if there is better way
Hello All
I am trying to create Domain Event for a newly created (after migration) domain object in my database.
for Objects without any internal child objects it worked fine by using Script Component. The problem is in how to get the child rows to add information to event object.
Ex. Customer-> Customer Locations.
I am creating Event in Script Component- as tranformation- (have reference to my Domain event module) and then creating sending serialized information about event as a column value. The input rows currently provide data for the parent object.
Please advise.
Regards,
The Mar
Edit 1
I would like to add that current I am doing processsing in
public override void Input0_ProcessInputRow(Input0Buffer Row)
I am looking for something like create a a data reader in this function
loop through data rows -> create child objecta nd add it to parent colelction
Still on google and PreExecute and ProcessInput Seems something to look at .
This is my solution. I am a total newbie in SSIS , so this may not be the best solution.
[Microsoft.SqlServer.Dts.Pipeline.SSISScriptComponentEntryPointAttribute]
public class ScriptMain : UserComponent
{
IDTSConnectionManager100 connectionManager;
SqlCommand cmd = null;
SqlConnection conn = null;
SqlDataReader reader = null;
public override void AcquireConnections(object Transaction)
{
try
{
connectionManager = this.Connections.ScriptConnectionManager;
conn = connectionManager.AcquireConnection(Transaction) as SqlConnection;
// Hard to debug failure- better off logging info to file
//using (StreamWriter outfile =
// new StreamWriter(#"f:\Migration.txt"))
//{
// outfile.Write(conn.ToString());
// outfile.Write(conn.State.ToString());
//}
}
catch (Exception ex)
{
//using (StreamWriter outfile =
// new StreamWriter(#"f:\Migration.txt"))
//{
// outfile.Write(" EEEEEEEEEEEEEEEEEEEE"+ ex.ToString());
//}
}
}
public override void PreExecute()
{
base.PreExecute();
cmd = new SqlCommand("SELECT [CustomerLocation fields] FROM customerlocationView where custid=#CustId", conn);
cmd.Parameters.Add("CustId", SqlDbType.UniqueIdentifier);
}
public override void PostExecute()
{
base.PostExecute();
/*
Add your code here for postprocessing or remove if not needed
You can set read/write variables here, for example:
Variables.MyIntVar = 100
*/
}
public override void Input0_ProcessInputRow(Input0Buffer Row)
{
Collection<CustomerLocation> locations = new Collection<CustomerLocation>();
cmd.Parameters["CustId"].Value = Row.id;
// Any error always saw that reader reamians open on connection
if (reader != null)
{
if (!reader.IsClosed)
{
reader.Close();
}
}
reader = cmd.ExecuteReader();
if (reader != null)
{
while (reader.Read())
{
// Get Child Details
var customerLocation = new CustomerLocation(....,...,...,);
customerLocation.CustId = Row.id;
locations.Add(customerLocation);
}
}
var newCustomerCreated = new NewCustomerCreated(Row.id,,...,...,locations);
var serializedEvent = JsonConvert.SerializeObject(newCustomerCreated, Formatting.Indented,
new JsonSerializerSettings { TypeNameHandling = TypeNameHandling.Objects, ReferenceLoopHandling = ReferenceLoopHandling.Ignore });
Row.SerializedEvent = serializedEvent;
Row.EventId = newCustomerCreated.EventId;
...
...
...
....
..
.
Row.Version = 1;
// using (StreamWriter outfile =
// new StreamWriter(#"f:\Migration.txt", true))
// {
// if (reader != null)
// {
// outfile.WriteLine(reader.HasRows);
//outfile.WriteLine(serializedEvent);
// }
// else
// {
// outfile.Write("reader is Null");
// }
//}
reader.Close();
}
public override void ReleaseConnections()
{
base.ReleaseConnections();
connectionManager.ReleaseConnection(conn);
}
}
One thing to note is that a different approach to create connection is to
get the connection string from connectionManager and use it to create OLEDB connection.

ASync JSON REST call problem with MVVM

I am trying to implement the MVVM patter for my WP7 Silverlight app and I am running into a problem with the async JSON Rest call. I moved into my ViewModel class the following two methods that were on my WP7 app Page.
public void FetchGames()
{
ObservableCollection<Game> G = new ObservableCollection<Game>();
//REST call in here
var webClient = new WebClient();
Uri uri = new Uri("http://www.somewebsite.com/get/games/league/" + league);
webClient.OpenReadCompleted += new OpenReadCompletedEventHandler(OpenReadCompletedGames);
webClient.OpenReadAsync(uri);
}
private void OpenReadCompletedGames(object sender, OpenReadCompletedEventArgs e)
{
DataContractJsonSerializer ser = null;
ser = new DataContractJsonSerializer(typeof(ObservableCollection<Game>));
Games = ser.ReadObject(e.Result) as ObservableCollection<Game>;
this.IsDataLoaded = true;
}
Now the problem is that because it is an async call the following code does not work. The following code is on my app Page.
protected override void OnNavigatedTo(System.Windows.Navigation.NavigationEventArgs e)
{
base.OnNavigatedTo(e);
if (NavigationContext.QueryString.TryGetValue("league", out league))
{
try
{
App.gViewModel.league = league;
App.gViewModel.FetchGames();
if(App.gViewModel.IsDataLoaded)
{
lbTeams.ItemsSource = App.gViewModel.Games;
}
}
catch ()
{
//error logging in here
}
}
}
Stepping thru the code shows that FetchGames is called then hits the next line ( if(App.gViewModel.IsDataLoaded)
) before the async call is finished. So IsDataLoaded is always false and I cant bind the listbox on the page.
Doing a lot of googleing I have some possible solutions but I am unable convert them to my particular problem. One is like this and it has to do with continuation passing style'. I couldn't get it to work tho and would greatly appreciate some help.
Thanks!
void DoSomethingAsync( Action<string> callback ) {
HttpWebRequest req; // TODO: build your request
req.BeginGetResponse( result => {
// This anonymous function is a closure and has access
// to the containing (or enclosing) function.
var response = req.EndGetResponse( result );
// Get the result string and call the callback
string resultString = null; // TODO: read from the stream
callback(resultString);
}, null );
}
This can be resolved by moving
lbTeams.ItemsSource = App.gViewModel.Games;
to the end of the OpenReadCompletedGames method. You'll need to use the Dispatcher to update the UI from here.
Dispatcher.BeginInvoke( () => { lbTeams.ItemsSource = App.gViewModel.Games; } );