private async void FindAndLoadContact(string givenName, string familyName) { ContactQueryOptions options = new ContactQueryOptions(); options.OrderBy = ContactQueryResultOrdering.GivenNameFamilyName; options.DesiredFields.Clear(); options.DesiredFields.Add(KnownContactProperties.GivenName); options.DesiredFields.Add(KnownContactProperties.FamilyName); options.DesiredFields.Add(KnownContactProperties.Email); options.DesiredFields.Add(KnownContactProperties.Telephone); ContactQueryResult query = store.CreateContactQuery(options); IReadOnlyList <StoredContact> contacts = await query.GetContactsAsync(); contact = contacts.First(item => item.GivenName == givenName && item.FamilyName == familyName); IDictionary <string, object> props = await contact.GetPropertiesAsync(); firstNameInput.Text = contact.GivenName; lastNameInput.Text = contact.FamilyName; if (props.ContainsKey(KnownContactProperties.Email)) { emailInput.Text = (string)props[KnownContactProperties.Email]; } if (props.ContainsKey(KnownContactProperties.Telephone)) { phoneInput.Text = (string)props[KnownContactProperties.Telephone]; } }
/// <summary> /// Saves the contact to native store /// </summary> /// <returns>Unique contact id of the stored contact</returns> public async Task <string> SaveToNativeContactStore() { ContactStore contactStore = await ContactStore.CreateOrOpenAsync( ContactStoreSystemAccessMode.ReadWrite, ContactStoreApplicationAccessMode.ReadOnly); StoredContact contact = null; // Update contact if already exists if (!String.IsNullOrEmpty(Id)) { contact = await contactStore.FindContactByIdAsync(Id); } if (contact == null) { contact = new StoredContact(contactStore); } // Set properties on stored contact await ToStoredContact(contact); // Save the contact await contact.SaveAsync(); return(contact.Id); }
public static Task <List <PContact> > GetContactsAsync(CancellationToken token) { return(Task.Run(() => { List <PContact> contacts = new List <PContact>(); try { using (IsolatedStorageFile store = IsolatedStorageFile.GetUserStoreForApplication()) { token.ThrowIfCancellationRequested(); var fileNames = store.GetFileNames(Directories.Contacts + "\\*"); foreach (var fileName in fileNames) { token.ThrowIfCancellationRequested(); string filePath = Path.Combine(Directories.Contacts, fileName); StoredContact scontact = new StoredContact(null); // (await DeserializeAndOpenAsync(filePath, FileMode.Open, FileAccess.ReadWrite)) as StoredContact; token.ThrowIfCancellationRequested(); PContact contact = new PContact(); contact.Name = fileName; contact.Path = filePath; contact.Contact = scontact; token.ThrowIfCancellationRequested(); contacts.Add(contact); } } token.ThrowIfCancellationRequested(); return contacts; } catch { return contacts; } }, token)); }
private async void bt_add_Click(object sender, RoutedEventArgs e) { //创建一个系统通信可以读写和其他程序制度的联系人存储 ContactStore conStore = await ContactStore.CreateOrOpenAsync(ContactStoreSystemAccessMode.ReadWrite, ContactStoreApplicationAccessMode.ReadOnly); //新增联系人 ContactInformation conInfo = new ContactInformation(); //获取ContacInformation类的属性map表 var properties = await conInfo.GetPropertiesAsync(); //添加电话属性 properties.Add(KnownContactProperties.FamilyName, "test"); properties.Add(KnownContactProperties.Telephone, "123456789"); //创建联系人对象 StoredContact storedContact = new StoredContact(conStore, conInfo); //获取安装包的一张图片文件用作联系人的头像 StorageFile imagefile = await Windows.ApplicationModel.Package.Current.InstalledLocation.GetFileAsync("Assets/1.jpeg"); ///设置头像,将图片数据转化成Stream对象,在转化成IInputStream对象。 //打开文件的可读数据流 Stream stream = await imagefile.OpenStreamForReadAsync(); //用Stream对象转化成为IIputStream对象 IInputStream inputStream = stream.AsInputStream(); //用IInputStream 对象设置为联系人头像 await storedContact.SetDisplayPictureAsync(inputStream); //保存联系人 await storedContact.SaveAsync(); ///获取头像,接收到的图片数据为IRandomAccessStream类型,如果要展示出来,需要创建一个BitmapImage对象, IRandomAccessStream raStream = await storedContact.GetDisplayPictureAsync(); BitmapImage bi = new BitmapImage(); bi.SetSource(raStream); image.Source = bi; }
/// <summary> /// Sets the name properties on the Stored contact /// </summary> /// <param name="contact"> /// <see cref="Windows.Phone.PersonalInformation.StoredContact">StoredContact</see> object /// </param> public void SetPropertiesOnStoredContact(ref StoredContact contact) { contact.GivenName = FirstName; contact.FamilyName = LastName; contact.HonorificPrefix = Prefix; contact.HonorificSuffix = Suffix; }
async private Task UpdateContact(string remoteId, string givenName, string familyName, string phone) { logger.debug("updating contact id={0} {1} {2} {3}", remoteId, givenName, familyName, phone); ContactStore store = await ContactStore.CreateOrOpenAsync(); string taggedRemoteId = remoteId; StoredContact contact = await store.FindContactByRemoteIdAsync(taggedRemoteId); if (contact != null) { logger.debug("contact id={0} exists in custom store, updating", remoteId); contact.GivenName = givenName; contact.FamilyName = familyName; IDictionary <string, object> props = await contact.GetPropertiesAsync(); props[KnownContactProperties.MobileTelephone] = phone; await contact.SaveAsync(); } else { await AddContact(remoteId, givenName, familyName, phone); } }
//async public void AddContactFromStore(string parameters) //{ // string[] tempParams = HttpUtility.UrlDecode(parameters).Split('~'); // string remoteId = tempParams[0]; // string givenName = tempParams[1]; // string familyName = tempParams[2]; // string street = tempParams[3]; // string city = tempParams[4]; // string state = tempParams[5]; // string zip = tempParams[6]; // string country = tempParams[7]; // string phone = tempParams[8]; // string email = tempParams[9]; // store = await ContactStore.CreateOrOpenAsync(ContactStoreSystemAccessMode.ReadWrite, ContactStoreApplicationAccessMode.ReadOnly); // StoredContact contact = new StoredContact(store); // RemoteIdHelper remoteIDHelper = new RemoteIdHelper(); // await remoteIDHelper.SetRemoteIdGuid(store); // contact.RemoteId = await remoteIDHelper.GetTaggedRemoteId(store, remoteId); // contact.GivenName = givenName; // contact.FamilyName = familyName; // string address = street + Environment.NewLine + city + ", " + state + " " + zip + Environment.NewLine + country; // IDictionary<string, object> props = await contact.GetPropertiesAsync(); // props.Add(KnownContactProperties.Email, email); // //props.Add(KnownContactProperties.Address, address); // props.Add(KnownContactProperties.Telephone, phone); // //IDictionary<string, object> extprops = await contact.GetExtendedPropertiesAsync(); // //extprops.Add("Codename", codeName); // await contact.SaveAsync(); //} #region Private methods async private void EditContact(string parameters) { string js = ""; // WP8 does not allow the editing of the contact. Just return NOT AVAILABLE IN WINDOES PHONE 8 message js = "javascript: var e = document.createEvent('Events');" + "e.initEvent('intel.xdk.contacts.edit',true,true);e.success=false;" + "e.error='NOT AVAILABLE IN WINDOES PHONE 8';document.dispatchEvent(e);"; //InjectJS("javascript:" + js); InvokeCustomScript(new ScriptCallback("eval", new string[] { js }), true); return; string[] args = WPCordovaClassLib.Cordova.JSON.JsonHelper.Deserialize <string[]>(parameters); getAllContacts(); string contactId = HttpUtility.UrlDecode(args[0]); if (busy == true) { js = "javascript: var e = document.createEvent('Events');" + "e.initEvent('intel.xdk.contacts.busy',true,true);e.success=false;" + "e.message='busy';document.dispatchEvent(e);"; //InjectJS("javascript:" + js); InvokeCustomScript(new ScriptCallback("eval", new string[] { js }), true); return; } try { ContactStore store = await ContactStore.CreateOrOpenAsync(ContactStoreSystemAccessMode.ReadWrite, ContactStoreApplicationAccessMode.ReadOnly); StoredContact contact = await store.FindContactByRemoteIdAsync(contactId); if (contact != null) { } else { js = string.Format("javascript: var e = document.createEvent('Events');" + "e.initEvent('intel.xdk.contacts.edit',true,true);e.success=false;" + "e.error='contact not found';e.contactid='{0}';document.dispatchEvent(e);", contactId); //InjectJS("javascript:" + js); InvokeCustomScript(new ScriptCallback("eval", new string[] { js }), true); return; } } catch (Exception e) { js = string.Format("javascript: var e = document.createEvent('Events');" + "e.initEvent('intel.xdk.contacts.edit',true,true);e.success=false;" + "e.error='{0}';e.contactid='{1}';document.dispatchEvent(e);", e.Message, contactId); //InjectJS("javascript:" + js); InvokeCustomScript(new ScriptCallback("eval", new string[] { js }), true); return; } }
/// <summary> /// Delete Contact /// </summary> /// <param name="id"></param> async private void DeleteContact(string id) { store = await ContactStore.CreateOrOpenAsync(ContactStoreSystemAccessMode.ReadWrite, ContactStoreApplicationAccessMode.ReadOnly); StoredContact contact = await store.FindContactByIdAsync(id); await store.DeleteContactAsync(id); }
private static async Task AddContact(RemoteContact remoteContact) { try { ContactStore store = await ContactStore.CreateOrOpenAsync(ContactStoreSystemAccessMode.ReadWrite, ContactStoreApplicationAccessMode.ReadOnly); var contact = new StoredContact(store); if (remoteContact.RemoteId == null) { return; } var remoteIdHelper = new RemoteIdHelper(); contact.RemoteId = await remoteIdHelper.GetTaggedRemoteId(store, remoteContact.RemoteId); IDictionary <string, object> props = await contact.GetPropertiesAsync(); if (remoteContact.Email != null) { props.Add(KnownContactProperties.Email, remoteContact.Email); } IDictionary <string, object> extprops = await contact.GetExtendedPropertiesAsync(); if (remoteContact.CodeName != null) { extprops.Add("Codename", remoteContact.CodeName); } if (remoteContact.DisplayName != null) { contact.DisplayName = remoteContact.DisplayName + " " + remoteContact.GivenName; } var prop = await contact.GetPropertiesAsync(); prop.Add(KnownContactProperties.MobileTelephone, "+1" + MdnGenerator(10)); prop.Add(KnownContactProperties.JobTitle, JobTitleGenerator()); prop.Add(KnownContactProperties.OfficeLocation, LocationGenerator()); prop.Add(KnownContactProperties.Notes, JobTitleGenerator()); Debug.WriteLine(contact.Store); await contact.SaveAsync(); Debug.WriteLine(String.Format("Adding:\n{0}", remoteContact.ToString())); } catch (Exception e) { Debug.WriteLine(e.Message); } }
public async Task SetPictureOnStoredContactAsync(StoredContact contact) { try { await contact.SetDisplayPictureAsync(FileManager.ReadAsStream( FileManager.GetAbsolutePath(PhotoPath))); } catch (Exception e) { Logger.Error("Error setting photo on stored contact. Reason - " + e.Message); } }
public static async void Save(string givenName, string familyName, string mobile) { ContactStore store = await ContactStore.CreateOrOpenAsync(); StoredContact contact = new StoredContact(store); contact.GivenName = givenName; contact.FamilyName = familyName; IDictionary<string, object> props = await contact.GetPropertiesAsync(); props.Add(KnownContactProperties.MobileTelephone, mobile); await contact.SaveAsync(); }
public async void Save(StoredContactViewModel contactViewModel) { await CheckForContactStore(); var contact = new StoredContact(ContactStore) { RemoteId = await _remoteIdHelper.GetTaggedRemoteId(ContactStore, contactViewModel.EMail), DisplayName = contactViewModel.NickName, GivenName = contactViewModel.FirstName, FamilyName = contactViewModel.FamilyName }; await contact.SaveAsync(); }
/// <summary> /// Creates a contact store and add contacts. /// </summary> public static async void CreateContactStore() { ContactStore contactStore = await ContactStore.CreateOrOpenAsync( ContactStoreSystemAccessMode.ReadWrite, ContactStoreApplicationAccessMode.ReadOnly); foreach (SampleContact sampleContact in SampleContact.CreateSampleContacts()) { StoredContact contact = new StoredContact(contactStore); IDictionary<string, object> props = await contact.GetPropertiesAsync(); if (!string.IsNullOrEmpty(sampleContact.FirstName)) { props.Add(KnownContactProperties.GivenName, sampleContact.FirstName); } if (!string.IsNullOrEmpty(sampleContact.LastName)) { props.Add(KnownContactProperties.FamilyName, sampleContact.LastName); } if (!string.IsNullOrEmpty(sampleContact.HomeEmail)) { props.Add(KnownContactProperties.Email, sampleContact.HomeEmail); } if (!string.IsNullOrEmpty(sampleContact.WorkEmail)) { props.Add(KnownContactProperties.WorkEmail, sampleContact.WorkEmail); } if (!string.IsNullOrEmpty(sampleContact.HomePhone)) { props.Add(KnownContactProperties.Telephone, sampleContact.HomePhone); } if (!string.IsNullOrEmpty(sampleContact.WorkPhone)) { props.Add(KnownContactProperties.CompanyTelephone, sampleContact.WorkPhone); } if (!string.IsNullOrEmpty(sampleContact.MobilePhone)) { props.Add(KnownContactProperties.MobileTelephone, sampleContact.MobilePhone); } await contact.SaveAsync(); } }
/// <summary> /// Creates a contact store and add contacts. /// </summary> public static async void CreateContactStore() { ContactStore contactStore = await ContactStore.CreateOrOpenAsync( ContactStoreSystemAccessMode.ReadWrite, ContactStoreApplicationAccessMode.ReadOnly); foreach (SampleContact sampleContact in SampleContact.CreateSampleContacts()) { StoredContact contact = new StoredContact(contactStore); IDictionary <string, object> props = await contact.GetPropertiesAsync(); if (!string.IsNullOrEmpty(sampleContact.FirstName)) { props.Add(KnownContactProperties.GivenName, sampleContact.FirstName); } if (!string.IsNullOrEmpty(sampleContact.LastName)) { props.Add(KnownContactProperties.FamilyName, sampleContact.LastName); } if (!string.IsNullOrEmpty(sampleContact.HomeEmail)) { props.Add(KnownContactProperties.Email, sampleContact.HomeEmail); } if (!string.IsNullOrEmpty(sampleContact.WorkEmail)) { props.Add(KnownContactProperties.WorkEmail, sampleContact.WorkEmail); } if (!string.IsNullOrEmpty(sampleContact.HomePhone)) { props.Add(KnownContactProperties.Telephone, sampleContact.HomePhone); } if (!string.IsNullOrEmpty(sampleContact.WorkPhone)) { props.Add(KnownContactProperties.CompanyTelephone, sampleContact.WorkPhone); } if (!string.IsNullOrEmpty(sampleContact.MobilePhone)) { props.Add(KnownContactProperties.MobileTelephone, sampleContact.MobilePhone); } await contact.SaveAsync(); } }
private async void GetContact(string id) { //通过联系人的Id获取联系人的信息 //创建联系人存储 conStore = await ContactStore.CreateOrOpenAsync(); //查找联系人 storCon = await conStore.FindContactByIdAsync(id); //获取联系人信息 properties = await storCon.GetPropertiesAsync(); name.Text = storCon.GivenName; telphone.Text = properties[KnownContactProperties.Telephone ].ToString(); }
public static async void Save(string givenName, string familyName, string mobile) { ContactStore store = await ContactStore.CreateOrOpenAsync(); StoredContact contact = new StoredContact(store); contact.GivenName = givenName; contact.FamilyName = familyName; IDictionary <string, object> props = await contact.GetPropertiesAsync(); props.Add(KnownContactProperties.MobileTelephone, mobile); await contact.SaveAsync(); }
private async void GetContact(string id) { //通过联系人的Id获取联系人的信息 //创建联系人存储 conStore = await ContactStore.CreateOrOpenAsync(); //查找联系人 storCon = await conStore.FindContactByIdAsync(id); //获取联系人信息 properties = await storCon.GetPropertiesAsync(); name.Text = storCon.GivenName; telphone.Text = properties[KnownContactProperties.Telephone].ToString(); }
async Task <Tuple <string, string> > GetSearchParamAndType(string id) { Tuple <string, string> result = null; ContactStore contactStore = await ContactStore.CreateOrOpenAsync( ContactStoreSystemAccessMode.ReadOnly, ContactStoreApplicationAccessMode.ReadOnly); StoredContact contact = await contactStore.FindContactByIdAsync(id); if (contact != null) { result = await SearchContactInUserDataAsync(contact.DisplayName); } return(result); }
private async void Button_Click_1(object sender, RoutedEventArgs e) { ContactStore contactStore = await ContactStore.CreateOrOpenAsync(ContactStoreSystemAccessMode.ReadWrite, ContactStoreApplicationAccessMode.ReadOnly); ContactInformation contactInformation=new ContactInformation(); var properties = await contactInformation.GetPropertiesAsync(); properties.Add(KnownContactProperties.FamilyName, name.Text); properties.Add(KnownContactProperties.Telephone, tel.Text); StoredContact storedContact = new StoredContact(contactStore, contactInformation); if (stream != null) { await storedContact.SetDisplayPictureAsync(stream); } await storedContact.SaveAsync(); NavigationService.GoBack(); }
async void SearchCompleted(object sender, ContactsSearchEventArgs e) { foreach (Contact c in e.Results) { StoredContact a = new StoredContact(contacts); var props = await a.GetPropertiesAsync(); var extprops =await a.GetExtendedPropertiesAsync(); props.Add(KnownContactProperties.DisplayName, c.DisplayName); props.Add(KnownContactProperties.Telephone, c.PhoneNumbers); extprops.Add("MoneyOwed", 0); extprops.Add("MoneyLent", 0); extprops.Add("DateAdded", 0); extprops.Add("Group", 0); await a.SaveAsync(); } }
public async Task AddContact(string remoteId, string givenName, string familyName, string phone) { logger.debug("adding contact id={0} {1} {2} {3}", remoteId, givenName, familyName, phone); ContactStore store = await ContactStore.CreateOrOpenAsync(); StoredContact contact = new StoredContact(store); contact.RemoteId = remoteId; contact.GivenName = givenName; contact.FamilyName = familyName; // TODO: picture sync IDictionary <string, object> props = await contact.GetPropertiesAsync(); props.Add(KnownContactProperties.MobileTelephone, phone); await contact.SaveAsync(); }
private async void Save_Click(object sender, EventArgs e) { if (contact == null) { contact = new StoredContact(store); } IDictionary <string, object> properties = await contact.GetPropertiesAsync(); contact.GivenName = firstNameInput.Text; contact.FamilyName = lastNameInput.Text; properties[KnownContactProperties.Email] = emailInput.Text; properties[KnownContactProperties.Telephone] = phoneInput.Text; await contact.SaveAsync(); NavigationService.GoBack(); }
public async void GenerateContacts() { var contactsStore = await ContactManager.RequestStoreAsync(Windows.ApplicationModel.Contacts.ContactStoreAccessType.AllContactsReadOnly); var allContacts = await contactsStore.FindContactsAsync(); var contactAsList = allContacts.ToList(); if (contactAsList.Count == 0) { for (int i = 0; i < 10; i++) { var contactStore = await Windows.Phone.PersonalInformation.ContactStore.CreateOrOpenAsync( ContactStoreSystemAccessMode.ReadWrite, ContactStoreApplicationAccessMode.ReadOnly); var contact = new StoredContact(contactStore); var contactDetails = await contact.GetPropertiesAsync(); var newContact = new Helpers.Contact(Generator.GenerateRandomName(3, 10), Generator.GenerateRandomTelephoneNumber().ToString(), string.Format("iamhappy{0}@happy.com", i)); if (!string.IsNullOrEmpty(newContact.Name)) { contactDetails.Add(KnownContactProperties.GivenName, newContact.Name); } if (!string.IsNullOrEmpty(newContact.PhoneNumber)) { contactDetails.Add(KnownContactProperties.WorkTelephone, newContact.PhoneNumber); } if (!string.IsNullOrEmpty(newContact.PhoneNumber)) { contactDetails.Add(KnownContactProperties.Email, newContact.Email); } await contact.SaveAsync(); } contactsStore = await ContactManager.RequestStoreAsync(Windows.ApplicationModel.Contacts.ContactStoreAccessType.AllContactsReadOnly); allContacts = await contactsStore.FindContactsAsync(); contactAsList = allContacts.ToList(); } }
private async Task EnsureProvisioned(ContactStore store) { if (AppGlobalStateManager.Current.LoggedInUserId != 0L) { bool flag = true; string text = ContactsManager.GetRemoteId(AppGlobalStateManager.Current.GlobalState.LoggedInUser); try { if (await store.FindContactByRemoteIdAsync(text) == null) { flag = false; } } catch (Exception) { flag = false; } if (!flag) { try { StoredContact arg_159_0 = await store.CreateMeContactAsync(text); arg_159_0.DisplayName = (AppGlobalStateManager.Current.GlobalState.LoggedInUser.Name); await arg_159_0.SaveAsync(); } catch { } try { await SocialManager.ProvisionAsync(); } catch { } } text = null; } }
protected async override void OnNavigatedTo(NavigationEventArgs e) { if (NavigationContext.QueryString.Keys.Contains("id")) { id = NavigationContext.QueryString["id"]; } contactStore = await ContactStore.CreateOrOpenAsync(ContactStoreSystemAccessMode.ReadWrite, ContactStoreApplicationAccessMode.ReadOnly); storedContact = await contactStore.FindContactByIdAsync(id); if (storedContact != null) { var properties = await storedContact.GetPropertiesAsync(); if (properties.Keys.Contains(KnownContactProperties.FamilyName)) { name.Text = properties[KnownContactProperties.FamilyName].ToString(); } if (properties.Keys.Contains(KnownContactProperties.Telephone)) { tel.Text = properties[KnownContactProperties.Telephone].ToString(); } } base.OnNavigatedTo(e); }
private async Task EnsureProvisioned(ContactStore store) { if (AppGlobalStateManager.Current.LoggedInUserId == 0L) { return; } bool ok = true; string meRemoteId = ContactsManager.GetRemoteId(AppGlobalStateManager.Current.GlobalState.LoggedInUser); try { if (await store.FindContactByRemoteIdAsync(meRemoteId) == null) { ok = false; } } catch { ok = false; } if (!ok) { StoredContact meContactAsync = await store.CreateMeContactAsync(meRemoteId); string name = AppGlobalStateManager.Current.GlobalState.LoggedInUser.Name; meContactAsync.DisplayName = name; await meContactAsync.SaveAsync(); try { await SocialManager.ProvisionAsync(); } catch { } } meRemoteId = null; }
private async void Save_Click(object sender, RoutedEventArgs e) { string message = ""; if (name.Text != "" && telphone.Text != "") { try { //创建一个联系人的信息对象 ContactInformation conInfo = new ContactInformation(); //获取联系人的属性字典 var properties = await conInfo.GetPropertiesAsync(); //添加联系人的属性 properties.Add(KnownContactProperties.GivenName, name.Text); properties.Add(KnownContactProperties.Telephone, telphone.Text); //创建或者打开联系人存储 ContactStore conStore = await ContactStore.CreateOrOpenAsync(); StoredContact storedContact = new StoredContact(conStore, conInfo); //保存联系人 await storedContact.SaveAsync(); message = "保存成功"; } catch (Exception ex) { message = "保存失败,错误信息:" + ex.Message; } } else { message = "名字或电话不能为空"; } await new MessageDialog(message).ShowAsync(); (Window.Current.Content as Frame).Navigate(typeof(ContactsList)); }
/// <summary> /// Update Contact Information /// </summary> /// <param name="remoteId"></param> /// <param name="givenName"></param> /// <param name="familyName"></param> /// <param name="email"></param> /// <param name="codeName"></param> async private void UpdateContact(string remoteId, string givenName, string familyName, string email, string codeName) { store = await ContactStore.CreateOrOpenAsync(ContactStoreSystemAccessMode.ReadWrite, ContactStoreApplicationAccessMode.ReadOnly); string taggedRemoteId = await GetTaggedRemoteId(store, remoteId); StoredContact contact = await store.FindContactByRemoteIdAsync(taggedRemoteId); if (contact != null) { contact.GivenName = givenName; contact.FamilyName = familyName; IDictionary <string, object> props = await contact.GetPropertiesAsync(); props[KnownContactProperties.Email] = email; IDictionary <string, object> extprops = await contact.GetExtendedPropertiesAsync(); extprops["Codename"] = codeName; await contact.SaveAsync(); } }
private async Task SetContactProperties(StoredContact contact, User user, User originalUser = null) { if (contact != null) { contact.RemoteId = ContactsManager.GetRemoteId(user); contact.GivenName = user.first_name; contact.FamilyName = user.last_name; if (!string.IsNullOrWhiteSpace(user.photo_max) && !user.photo_max.EndsWith(".gif")) { Stream responseStreamAsync = await HttpExtensions.TryGetResponseStreamAsync(user.photo_max); if (responseStreamAsync == null) { throw new Exception("failed to download contact pic " + user.photo_max); } await contact.SetDisplayPictureAsync(responseStreamAsync.AsInputStream()); } IDictionary <string, object> propertiesAsync = await contact.GetPropertiesAsync(); if (!string.IsNullOrWhiteSpace(user.site)) { propertiesAsync[KnownContactProperties.Url] = (object)user.site; } if (!string.IsNullOrWhiteSpace(user.mobile_phone) && this.IsPhoneNumber(user.mobile_phone)) { List <string> phoneNumbers = BaseFormatterHelper.ParsePhoneNumbers(user.mobile_phone); if (phoneNumbers.Count >= 1) { propertiesAsync[KnownContactProperties.MobileTelephone] = (object)phoneNumbers[0]; } if (phoneNumbers.Count >= 2) { propertiesAsync[KnownContactProperties.AlternateMobileTelephone] = (object)phoneNumbers[1]; } } if (!string.IsNullOrWhiteSpace(user.home_phone) && this.IsPhoneNumber(user.home_phone)) { List <string> phoneNumbers = BaseFormatterHelper.ParsePhoneNumbers(user.home_phone); if (phoneNumbers.Count >= 1) { propertiesAsync[KnownContactProperties.Telephone] = (object)phoneNumbers[0]; } if (phoneNumbers.Count >= 2) { propertiesAsync[KnownContactProperties.AlternateTelephone] = (object)phoneNumbers[1]; } } DateTime dateTime; if (!string.IsNullOrWhiteSpace(user.bdate) && ContactsManager.TryParseDateTimeFromString(user.bdate, out dateTime)) { TimeSpan timeSpan = DateTime.Now - DateTime.UtcNow; dateTime = dateTime.Add(timeSpan); DateTimeOffset dateTimeOffset = new DateTimeOffset(dateTime.Year, dateTime.Month, dateTime.Day, 0, 0, 0, 0, TimeSpan.Zero); propertiesAsync[KnownContactProperties.Birthdate] = (object)new DateTimeOffset(dateTime); } } if (originalUser == null) { return; } originalUser.first_name = user.first_name; originalUser.last_name = user.last_name; originalUser.site = user.site; originalUser.mobile_phone = user.mobile_phone; originalUser.home_phone = user.home_phone; originalUser.photo_max = user.photo_max; originalUser.bdate = user.bdate; }
public async Task SyncContactsAsync(List <User> friendsList) { if (this._synching || this._deleting) { return; } this._synching = true; friendsList = friendsList.Take <User>(ContactsManager.MAX_FRIENDS_TO_SYNC).ToList <User>(); long initiallyLoggedInUser = AppGlobalStateManager.Current.LoggedInUserId; try { SavedContacts savedContacts = await this.GetSavedList(); List <User> savedList = savedContacts.SavedUsers; Func <User, string> getKey = (Func <User, string>)(u => u.uid.ToString()); List <Tuple <User, User> > updatedUsersTuples; List <User> createdUsers; List <User> deletedUsers; ListUtils.GetListChanges <User>(savedList, friendsList, getKey, (Func <User, User, bool>)((u1, u2) => { if (ContactsManager.AreStringsEqualOrNullEmpty(u1.first_name, u2.first_name) && ContactsManager.AreStringsEqualOrNullEmpty(u1.last_name, u2.last_name) && (ContactsManager.AreStringsEqualOrNullEmpty(u1.mobile_phone, u2.mobile_phone) && ContactsManager.AreStringsEqualOrNullEmpty(u1.home_phone, u2.home_phone)) && (ContactsManager.AreStringsEqualOrNullEmpty(u1.site, u2.site) && ContactsManager.AreStringsEqualOrNullEmpty(u1.bdate, u2.bdate))) { return(ContactsManager.AreStringsEqualOrNullEmpty(u1.photo_max, u2.photo_max)); } return(false); }), out updatedUsersTuples, out createdUsers, out deletedUsers); Logger.Instance.Info("ContactsManager got {0} updated users, {1} new users, {2} deleted users", updatedUsersTuples.Count, createdUsers.Count, deletedUsers.Count); int totalCountToSync = createdUsers.Count; int currentSyncing = 0; if (initiallyLoggedInUser != AppGlobalStateManager.Current.LoggedInUserId || !AppGlobalStateManager.Current.GlobalState.SyncContacts) { await this.DoDeleteAllContactsAsync(); } else { ContactStore contactStore = await ContactStore.CreateOrOpenAsync(); await this.EnsureProvisioned(contactStore); StoredContact meContact = await contactStore.FindContactByRemoteIdAsync(ContactsManager.GetRemoteId(AppGlobalStateManager.Current.GlobalState.LoggedInUser)); if (meContact != null) { await this.SetContactProperties(meContact, AppGlobalStateManager.Current.GlobalState.LoggedInUser, (User)null); await meContact.SaveAsync(); } contactStore.CreateContactQuery(); foreach (Tuple <User, User> tuple in updatedUsersTuples) { User updUser = tuple.Item2; User originalUser = tuple.Item1; if (initiallyLoggedInUser != AppGlobalStateManager.Current.LoggedInUserId || !AppGlobalStateManager.Current.GlobalState.SyncContacts) { await this.DoDeleteAllContactsAsync(); return; } try { StoredContact contact = await contactStore.FindContactByRemoteIdAsync(ContactsManager.GetRemoteId(updUser)); await this.SetContactProperties(contact, updUser, originalUser); if (contact != null) { await contact.SaveAsync(); } contact = null; } catch (Exception ex) { Logger.Instance.Error("Failed to update contact for user " + updUser.Name, ex); } updUser = (User)null; originalUser = (User)null; } //List<Tuple<User, User>>.Enumerator enumerator1 = new List<Tuple<User, User>>.Enumerator(); foreach (User user in createdUsers) { User newUser = user; ++currentSyncing; if (initiallyLoggedInUser != AppGlobalStateManager.Current.LoggedInUserId || !AppGlobalStateManager.Current.GlobalState.SyncContacts) { await this.DoDeleteAllContactsAsync(); return; } try { if (await contactStore.FindContactByRemoteIdAsync(ContactsManager.GetRemoteId(newUser)) == null) { Stopwatch sw = Stopwatch.StartNew(); this.FireSyncStatusChanged(currentSyncing, totalCountToSync); Logger.Instance.Info("ContactsManager begin creating user"); StoredContact contact = new StoredContact(contactStore); await this.SetContactProperties(contact, newUser, null); await contact.SaveAsync(); Logger.Instance.Info("ContactsManager end creating user"); sw.Stop(); long num = 500L - sw.ElapsedMilliseconds; if (num > 0L) { await Task.Delay((int)num); } sw = null; contact = null; } savedList.Add(newUser); } catch (Exception ex) { Logger.Instance.Error("Failed to create contact for user " + newUser.Name, ex); } newUser = null; } //List<User>.Enumerator enumerator2 = new List<User>.Enumerator(); foreach (User user in deletedUsers) { User deletedUser = user; if (initiallyLoggedInUser != AppGlobalStateManager.Current.LoggedInUserId || !AppGlobalStateManager.Current.GlobalState.SyncContacts) { await this.DoDeleteAllContactsAsync(); return; } try { StoredContact contactByRemoteIdAsync = await contactStore.FindContactByRemoteIdAsync(ContactsManager.GetRemoteId(deletedUser)); if (contactByRemoteIdAsync != null) { await contactStore.DeleteContactAsync(contactByRemoteIdAsync.Id); } savedList.Remove(deletedUser); } catch (Exception ex) { Logger.Instance.Error("Failed to delete contact for user " + deletedUser.Name, ex); } deletedUser = null; } //enumerator2 = new List<User>.Enumerator(); savedContacts.SyncedDate = DateTime.UtcNow; await this.EnsurePersistSavedContactsAsync(); savedContacts = null; savedList = null; deletedUsers = null; createdUsers = null; updatedUsersTuples = null; contactStore = null; meContact = null; } } catch (Exception ex) { Logger.Instance.Error("Failed to sync contacts. ", ex); } finally { this._synching = false; this.FireSyncStatusChanged(0, 0); } }
public async Task AddContact(string remoteId, string givenName, string familyName, string phone) { logger.debug("adding contact id={0} {1} {2} {3}", remoteId, givenName, familyName, phone); ContactStore store = await ContactStore.CreateOrOpenAsync(); StoredContact contact = new StoredContact(store); contact.RemoteId = remoteId; contact.GivenName = givenName; contact.FamilyName = familyName; // TODO: picture sync IDictionary<string, object> props = await contact.GetPropertiesAsync(); props.Add(KnownContactProperties.MobileTelephone, phone); await contact.SaveAsync(); }
/// <summary> /// Adds a contact to the contact store using data supplied in the MyRemoteContact helper object. /// </summary> /// <param name="remoteContact">The MyRemoteContact helper object representing the contact to be added.</param> /// <returns></returns> public async Task AddContact(XElement el, uint id) { try { StoredContact contact = new StoredContact(contactStore); contact.RemoteId = await remoteIdHelper.GetTaggedRemoteId(contactStore, id.ToString()); contact.GivenName = el.Element("GivenName").Value; contact.FamilyName = el.Element("FamilyName").Value; contact.DisplayName = el.Element("DisplayName").Value; IDictionary <string, object> props = await contact.GetPropertiesAsync(); if (el.Element("AdditionalName") != null) { props.Add(KnownContactProperties.AdditionalName, el.Element("AdditionalName").Value); } if (el.Element("Address") != null) { props.Add(KnownContactProperties.Address, el.Element("Address").Value); } if (el.Element("AlternateMobileTelephone") != null) { props.Add(KnownContactProperties.AlternateMobileTelephone, el.Element("AlternateMobileTelephone").Value); } if (el.Element("Anniversary") != null) { props.Add(KnownContactProperties.Anniversary, el.Element("Anniversary").Value); } if (el.Element("Birthdate") != null) { props.Add(KnownContactProperties.Birthdate, el.Element("Birthdate").Value); } if (el.Element("Children") != null) { props.Add(KnownContactProperties.Children, el.Element("Children").Value); } if (el.Element("CompanyName") != null) { props.Add(KnownContactProperties.CompanyName, el.Element("CompanyName").Value); } if (el.Element("CompanyTelephone") != null) { props.Add(KnownContactProperties.CompanyTelephone, el.Element("CompanyTelephone").Value); } // if (el.Element("DisplayName") != null) props.Add(KnownContactProperties.DisplayName, el.Element("DisplayName").Value); if (el.Element("Email") != null) { props.Add(KnownContactProperties.Email, el.Element("Email").Value); } // if (el.Element("FamilyName") != null) props.Add(KnownContactProperties.FamilyName, el.Element("FamilyName").Value); // if (el.Element("GivenName") != null) props.Add(KnownContactProperties.GivenName, el.Element("GivenName").Value); if (el.Element("HomeFax") != null) { props.Add(KnownContactProperties.HomeFax, el.Element("HomeFax").Value); } if (el.Element("HonorificPrefix") != null) { props.Add(KnownContactProperties.HonorificPrefix, el.Element("HonorificPrefix").Value); } if (el.Element("HonorificSuffix") != null) { props.Add(KnownContactProperties.HonorificSuffix, el.Element("HonorificSuffix").Value); } if (el.Element("JobTitle") != null) { props.Add(KnownContactProperties.JobTitle, el.Element("JobTitle").Value); } if (el.Element("Manager") != null) { props.Add(KnownContactProperties.Manager, el.Element("Manager").Value); } if (el.Element("MobileTelephone") != null) { props.Add(KnownContactProperties.MobileTelephone, el.Element("MobileTelephone").Value); } if (el.Element("Nickname") != null) { props.Add(KnownContactProperties.Nickname, el.Element("Nickname").Value); } if (el.Element("Notes") != null) { props.Add(KnownContactProperties.Notes, el.Element("Notes").Value); } if (el.Element("OfficeLocation") != null) { props.Add(KnownContactProperties.OfficeLocation, el.Element("OfficeLocation").Value); } if (el.Element("OtherAddress") != null) { props.Add(KnownContactProperties.OtherAddress, el.Element("OtherAddress").Value); } if (el.Element("OtherEmail") != null) { props.Add(KnownContactProperties.OtherEmail, el.Element("OtherEmail").Value); } if (el.Element("SignificantOther") != null) { props.Add(KnownContactProperties.SignificantOther, el.Element("SignificantOther").Value); } if (el.Element("Telephone") != null) { props.Add(KnownContactProperties.Telephone, el.Element("Telephone").Value); } if (el.Element("Url") != null) { props.Add(KnownContactProperties.Url, el.Element("Url").Value); } if (el.Element("WorkAddress") != null) { props.Add(KnownContactProperties.WorkAddress, el.Element("WorkAddress").Value); } if (el.Element("WorkEmail") != null) { props.Add(KnownContactProperties.WorkEmail, el.Element("WorkEmail").Value); } if (el.Element("WorkFax") != null) { props.Add(KnownContactProperties.WorkFax, el.Element("WorkFax").Value); } if (el.Element("WorkTelephone") != null) { props.Add(KnownContactProperties.WorkTelephone, el.Element("WorkTelephone").Value); } if (el.Element("YomiCompanyName") != null) { props.Add(KnownContactProperties.YomiCompanyName, el.Element("YomiCompanyName").Value); } if (el.Element("YomiFamilyName") != null) { props.Add(KnownContactProperties.YomiFamilyName, el.Element("YomiFamilyName").Value); } if (el.Element("YomiGivenName") != null) { props.Add(KnownContactProperties.YomiGivenName, el.Element("YomiGivenName").Value); } await contact.SaveAsync(); } catch (Exception e) { Debug.WriteLine(e.ToString()); StatusTextBlock.Text = e.ToString(); } }
private async Task SetContactProperties(StoredContact contact, User user, User originalUser = null) { if (contact != null) { contact.RemoteId = (ContactsManager.GetRemoteId(user)); contact.GivenName = (user.first_name); contact.FamilyName = (user.last_name); if (!string.IsNullOrWhiteSpace(user.photo_max) && !user.photo_max.EndsWith(".gif")) { Stream stream = await HttpExtensions.TryGetResponseStreamAsync(user.photo_max); if (stream == null) { throw new Exception("failed to download contact pic " + user.photo_max); } await contact.SetDisplayPictureAsync(stream.AsInputStream()); } IDictionary <string, object> dictionary = await contact.GetPropertiesAsync(); if (!string.IsNullOrWhiteSpace(user.site)) { dictionary[KnownContactProperties.Url] = user.site; } if (!string.IsNullOrWhiteSpace(user.mobile_phone) && this.IsPhoneNumber(user.mobile_phone)) { List <string> var_6_262 = BaseFormatterHelper.ParsePhoneNumbers(user.mobile_phone); if (var_6_262.Count >= 1) { dictionary[KnownContactProperties.MobileTelephone] = var_6_262[0]; } if (var_6_262.Count >= 2) { dictionary[KnownContactProperties.AlternateMobileTelephone] = var_6_262[1]; } } if (!string.IsNullOrWhiteSpace(user.home_phone) && this.IsPhoneNumber(user.home_phone)) { List <string> var_7_2D8 = BaseFormatterHelper.ParsePhoneNumbers(user.home_phone); if (var_7_2D8.Count >= 1) { dictionary[KnownContactProperties.Telephone] = var_7_2D8[0]; } if (var_7_2D8.Count >= 2) { dictionary[KnownContactProperties.AlternateTelephone] = var_7_2D8[1]; } } DateTime var_8; if (!string.IsNullOrWhiteSpace(user.bdate) && ContactsManager.TryParseDateTimeFromString(user.bdate, out var_8)) { var_8 = var_8.Add(DateTime.Now - DateTime.UtcNow); new DateTimeOffset(var_8.Year, var_8.Month, var_8.Day, 0, 0, 0, 0, TimeSpan.Zero); dictionary[KnownContactProperties.Birthdate] = new DateTimeOffset(var_8); } } if (originalUser != null) { originalUser.first_name = user.first_name; originalUser.last_name = user.last_name; originalUser.site = user.site; originalUser.mobile_phone = user.mobile_phone; originalUser.home_phone = user.home_phone; originalUser.photo_max = user.photo_max; originalUser.bdate = user.bdate; } }
public async Task AddContact(RemoteContact remoteContact) { try { ContactStore store = await ContactStore.CreateOrOpenAsync(); StoredContact contact = new StoredContact(store); RemoteIdHelper remoteIDHelper = new RemoteIdHelper(); contact.RemoteId = await remoteIDHelper.GetTaggedRemoteId(store, remoteContact.RemoteId); contact.GivenName = remoteContact.GivenName; contact.FamilyName = remoteContact.FamilyName; IDictionary<string, object> props = await contact.GetPropertiesAsync(); props.Add(KnownContactProperties.Email, remoteContact.Email); IDictionary<string, object> extprops = await contact.GetExtendedPropertiesAsync(); extprops.Add("Codename", remoteContact.CodeName); if (remoteContact.DisplayName != null) contact.DisplayName = remoteContact.DisplayName; IInputStream I = remoteContact.photo.AsInputStream(); await contact.SetDisplayPictureAsync(I); Debug.WriteLine(contact.Store); await contact.SaveAsync(); Debug.WriteLine(String.Format("Adding:\n{0}", remoteContact.ToString())); } catch(Exception e) { Debug.WriteLine(e.Message); } }
private void SetTargetContactsColumns() { this.clTargetContacts.dgObjects.Dock = DockStyle.Fill; List <OlvColumn> columns = new List <OlvColumn>(); OlvColumn column = new OlvColumn { AspectName = @"Email", Text = @"email", FillsFreeSpace = false, Groupable = false, Hideable = false, DataType = typeof(string), HeaderTextAlign = HorizontalAlignment.Center, TextAlign = HorizontalAlignment.Left, IsEditable = true, Width = 200, DisplayIndex = 0 }; columns.Add(column); this.clTargetContacts.dgObjects.PrimarySortColumn = column; column = new OlvColumn { AspectName = @"CanBeSender", Text = LocalizibleStrings.ColumnCanSend, FillsFreeSpace = false, Groupable = true, Hideable = true, CheckBoxes = true, DataType = typeof(bool), HeaderTextAlign = HorizontalAlignment.Center, TextAlign = HorizontalAlignment.Center, TriStateCheckBoxes = false, Width = 100, IsEditable = true }; columns.Add(column); column = new OlvColumn { AspectName = @"CanBeRecipient", Text = LocalizibleStrings.ColumnCanReceive, FillsFreeSpace = false, Groupable = true, Hideable = true, CheckBoxes = true, DataType = typeof(bool), HeaderTextAlign = HorizontalAlignment.Center, TextAlign = HorizontalAlignment.Center, Width = 100, TriStateCheckBoxes = false, IsEditable = true, AspectPutter = (obj, boolValue) => { StoredContact contact = obj as StoredContact; if (contact == null) { return; } if (!contact.IsEwsContact) { return; } contact.CanBeRecipient = (bool)boolValue; } }; columns.Add(column); this.clTargetContacts.dgObjects.AllColumns.AddRange(columns); this.clTargetContacts.dgObjects.RebuildColumns(); this.clTargetContacts.dgObjects.Sorting = SortOrder.Ascending; this.clTargetContacts.dgObjects.Sort(); }
private void MainFormLoad(object sender, EventArgs e) { Form.CheckForIllegalCrossThreadCalls = false; Action <string> action = str => this.lbLog.Items.Add(str); Logger.AddAlgorithm(new ComponentLogWriteAlgorithm(action)); this.panel1.Enabled = false; this.generateToolStripMenuItem.Enabled = false; this.saveSettingsToolStripMenuItem.Enabled = false; this.splitContainer4.SplitterWidth = 10; this.splitContainer1.SplitterWidth = 10; this.RearrangeCountControls(); ToolStripButton tsbtnMove = new ToolStripButton(LocalizibleStrings.BtnAddSelectedToMailList) { DisplayStyle = ToolStripItemDisplayStyle.Image, Image = LocalizibleStrings.ArrowRight }; tsbtnMove.Click += (o, args) => { IEnumerable <StoredContact> storedContacts = this.clTargetContacts.dgObjects.Objects.Cast <StoredContact>().ToList(); foreach (Contact obj in from Contact obj in this.clEwsContacts.dgObjects.SelectedObjects let existed = storedContacts.FirstOrDefault(s => s.UniqId == obj.Id.UniqueId) where existed == null select obj) { this.clTargetContacts.dgObjects.AddObject(new StoredContact(obj)); } }; this.clEwsContacts._barTools.Items.Insert(2, tsbtnMove); string mailTemplateFolder; string eventTemplateFolder; switch (Thread.CurrentThread.CurrentUICulture.LCID) { case LocalizationHelper.EnInt: this.englishToolStripMenuItem.Checked = true; this.russianToolStripMenuItem.Checked = false; mailTemplateFolder = Config.EmailTemplateFolderEn; eventTemplateFolder = Config.EventTemplateFolderEn; break; case LocalizationHelper.RuInt: this.russianToolStripMenuItem.Checked = true; this.englishToolStripMenuItem.Checked = false; mailTemplateFolder = Config.EmailTemplateFolderRu; eventTemplateFolder = Config.EventTemplateFolderRu; break; default: this.englishToolStripMenuItem.Checked = true; this.russianToolStripMenuItem.Checked = false; mailTemplateFolder = Config.EmailTemplateFolderEn; eventTemplateFolder = Config.EventTemplateFolderEn; break; } this.SetEwsContactsColumns(); this.SetMailTemplatesColumns(); this.SetEventTemplatesColumns(); this.SetTargetContactsColumns(); this.clEwsContacts.tsbtnFilteredProperties.Visible = false; this.clEwsContacts.tsbtnCreate.Visible = false; this.clEwsContacts.tsbtnEdit.Visible = false; this.clEwsContacts.tsbtnDelete.Visible = false; this.clEwsContacts.tsbtnFilterSettings.Visible = false; this.clEwsContacts.tsbtnFilteredProperties.Visible = false; this.clEwsContacts.tsbtnRefresh.Text = LocalizibleStrings.BtnRefresh; this.clEwsContacts.tsbtnClearFilter.Text = LocalizibleStrings.BtnClear; this.clEwsContacts.tsbtnSearch.Text = LocalizibleStrings.BtnSearch; this.clEwsContacts.tslbSearch.Text = LocalizibleStrings.LbSearch; this.clEwsContacts.tslbCount.Text = LocalizibleStrings.LbCount; this.clEwsContacts.tsbtnRefresh.Click += (s, args) => { try { Folder contactsFolder; if (!TryGetFolder(Config.ContactFolder, out contactsFolder)) { Logger.Message(LocalizibleStrings.TryLoadFromDefault); contactsFolder = ContactsFolder.Bind(_service, WellKnownFolderName.Contacts); } SearchFilter sf = new SearchFilter.IsEqualTo(ItemSchema.ItemClass, @"IPM.Contact"); FindItemsResults <Item> items = contactsFolder.FindItems(sf, new ItemView(int.MaxValue)); this.clEwsContacts.dgObjects.SetObjects(items.ToList()); } catch (Exception exc) { Logger.Error(LocalizibleStrings.CannotGetContactList, exc); } }; this.clMailTemplates.tsbtnFilteredProperties.Visible = false; this.clMailTemplates.tsbtnCreate.Visible = false; this.clMailTemplates.tsbtnEdit.Visible = false; this.clMailTemplates.tsbtnDelete.Visible = false; this.clMailTemplates.tsbtnFilterSettings.Visible = false; this.clMailTemplates.tsbtnFilteredProperties.Visible = false; this.clMailTemplates.tsbtnRefresh.Text = LocalizibleStrings.BtnRefresh; this.clMailTemplates.tsbtnClearFilter.Text = LocalizibleStrings.BtnClear; this.clMailTemplates.tsbtnSearch.Text = LocalizibleStrings.BtnSearch; this.clMailTemplates.tslbSearch.Text = LocalizibleStrings.LbSearch; this.clMailTemplates.tslbCount.Text = LocalizibleStrings.LbCount; this.clMailTemplates.tsbtnRefresh.Click += (s, args) => { try { /*Folder templatesFolder; * if (!TryGetFolder(mailTemplateFolder, out templatesFolder)) * return; * * FindItemsResults<Item> items = * templatesFolder.FindItems(new ItemView(int.MaxValue));*/ IList <Storage.Message> items = new List <Storage.Message>(); // ReSharper disable once LoopCanBeConvertedToQuery // под отладчиком всякая фигня происходит если linq foreach (string path in Directory.GetFiles(Config.GetParam(mailTemplateFolder))) { items.Add(new Storage.Message(path)); } this.clMailTemplates.dgObjects.SetObjects(items.ToList()); } catch (Exception exc) { Logger.Error(LocalizibleStrings.CannotGetMailTemplateList, exc); } }; this.clEventTemplates.tsbtnCreate.Visible = false; this.clEventTemplates.tsbtnEdit.Visible = false; this.clEventTemplates.tsbtnDelete.Visible = false; this.clEventTemplates.tsbtnFilterSettings.Visible = false; this.clEventTemplates.tsbtnFilteredProperties.Visible = false; this.clEventTemplates.tsbtnRefresh.Text = LocalizibleStrings.BtnRefresh; this.clEventTemplates.tsbtnClearFilter.Text = LocalizibleStrings.BtnClear; this.clEventTemplates.tsbtnSearch.Text = LocalizibleStrings.BtnSearch; this.clEventTemplates.tslbSearch.Text = LocalizibleStrings.LbSearch; this.clEventTemplates.tslbCount.Text = LocalizibleStrings.LbCount; this.clEventTemplates.tsbtnRefresh.Click += (s, args) => { try { /*Folder templatesFolder; * if (!TryGetFolder(eventTemplateFolder, out templatesFolder)) * return; * * FindItemsResults<Item> items = * templatesFolder.FindItems(new ItemView(int.MaxValue));*/ List <Storage.Message> tasks = Directory.GetFiles(Config.GetParam(eventTemplateFolder)) .Select(t => new Storage.Message(t)) .ToList(); this.clEventTemplates.dgObjects.SetObjects(tasks); } catch (Exception exc) { Logger.Error(LocalizibleStrings.CannotGetEventTemplateList, exc); } }; this.clTargetContacts.tsbtnCreate.Text = LocalizibleStrings.BtnCreate; this.clTargetContacts.tsbtnDelete.Text = LocalizibleStrings.BtnDelete; this.clTargetContacts.tsbtnRefresh.Text = LocalizibleStrings.BtnRefresh; this.clTargetContacts.tsbtnClearFilter.Text = LocalizibleStrings.BtnClear; this.clTargetContacts.tsbtnSearch.Text = LocalizibleStrings.BtnSearch; this.clTargetContacts.tslbSearch.Text = LocalizibleStrings.LbSearch; this.clTargetContacts.tslbCount.Text = LocalizibleStrings.LbCount; this.clTargetContacts.tsbtnCreate.Visible = true; this.clTargetContacts.tsbtnEdit.Visible = false; this.clTargetContacts.tsbtnDelete.Visible = true; this.clTargetContacts.tsbtnFilterSettings.Visible = false; this.clTargetContacts.tsbtnFilteredProperties.Visible = false; this.clTargetContacts.dgObjects.TriStateCheckBoxes = false; this.clTargetContacts.dgObjects.RenderNonEditableCheckboxesAsDisabled = false; this.clTargetContacts.dgObjects.UseSubItemCheckBoxes = true; ToolStripButton tsbtnSave = new ToolStripButton(LocalizibleStrings.BtnSaveAll) { DisplayStyle = ToolStripItemDisplayStyle.Image, Image = LocalizibleStrings.Save }; tsbtnSave.Click += (o, args) => { IEnumerable <StoredContact> contacts = this.clTargetContacts.dgObjects.Objects.Cast <StoredContact>(); foreach (StoredContact contact in contacts) { contact.Save(); } }; this.clTargetContacts._barTools.Items.Insert(1, tsbtnSave); this.clTargetContacts.tsbtnRefresh.Click += (s, args) => { try { this.clTargetContacts.dgObjects.SetObjects(StoredContact.GetAll()); } catch (Exception exc) { Logger.Error(LocalizibleStrings.CannotGetStoredContacts, exc); } }; this.clTargetContacts.tsbtnCreate.Click += (o, args) => this.clTargetContacts.dgObjects.AddObject(new StoredContact()); this.clTargetContacts.tsbtnDelete.Click += (o, args) => { DialogResult res = MessageBox.Show( LocalizibleStrings.DeleteConfirmation, LocalizibleStrings.Warning, MessageBoxButtons.YesNo, MessageBoxIcon.Warning, MessageBoxDefaultButton.Button2); if (res == DialogResult.No) { return; } foreach (StoredContact cont in this.clTargetContacts.dgObjects.SelectedObjects) { try { this.clTargetContacts.dgObjects.RemoveObject(cont); cont.Delete(); } catch (Exception exc) { Logger.Error(LocalizibleStrings.CannotDeleteContact + cont.FileName, exc); } } }; }
public async Task <StoredContact> ToStoredContact() { StoredContact contact = new StoredContact(App.ContactStore); contact.RemoteId = this.GenerateLocalId(); contact.RemoteId = await App.RemoteIdHelper.GetTaggedRemoteId(App.ContactStore, contact.RemoteId); if (String.IsNullOrEmpty(this.GivenName) == false) { contact.GivenName = this.GivenName; } if (String.IsNullOrEmpty(this.FamilyName) == false) { contact.FamilyName = this.FamilyName; } #region Set Picture ; Test = not yet if (this.Thumbnail != null) { using (IInputStream inStream = await this.Thumbnail.OpenSequentialReadAsync()) { await contact.SetDisplayPictureAsync(inStream); } } #endregion var props = await contact.GetPropertiesAsync(); if (String.IsNullOrEmpty(this.Nickname) == false) { props.Add(KnownContactProperties.Nickname, this.Nickname); } if (String.IsNullOrEmpty(this.Mobilephone) == false) { props.Add(KnownContactProperties.MobileTelephone, this.Mobilephone); } if (String.IsNullOrEmpty(this.AlternateMobilePhone) == false) { props.Add(KnownContactProperties.AlternateMobileTelephone, this.AlternateMobilePhone); } if (String.IsNullOrEmpty(this.Telephone) == false) { props.Add(KnownContactProperties.Telephone, this.Telephone); } if (string.IsNullOrEmpty(this.Email) == false) { props.Add(KnownContactProperties.Email, this.Email); } if (String.IsNullOrEmpty(this.Address) == false) { props.Add(KnownContactProperties.Address, new ContactAddress() { Locality = this.Address, StreetAddress = (this.Street == null) ? "":this.Street, Region = (this.Region == null) ? "" : this.Region, Country = (this.Country == null) ? "" : this.Country } ); } if (this.Birthday != null) { props.Add( KnownContactProperties.Birthdate, new DateTimeOffset( new DateTime(this.Birthday.Year, this.Birthday.Month, this.Birthday.Day), new TimeSpan(1, 0, 0))); } return(contact); }
private async Task <StoredContact> ToStoredContact(StoredContact contact) { if (contact == null) { ContactStore contactStore = await ContactStore.CreateOrOpenAsync( ContactStoreSystemAccessMode.ReadWrite, ContactStoreApplicationAccessMode.ReadOnly); contact = new StoredContact(contactStore); } IDictionary <string, object> properties = await contact.GetPropertiesAsync(); // Address if (Addresses != null && Addresses.Count > 0) { Addresses.ForEach(address => address.AsStoredContactProperties(ref properties)); } // Birthday if (W3ContactBirthday != null) { W3ContactBirthday.AsStoredContactProperties(ref properties); } // Emails if (Emails != null && Emails.Count > 0) { Emails.ForEach(email => email.AsStoredContactProperties(ref properties)); } // Name if (Name != null) { Name.AsStoredContactProperties(ref properties); } // NickName if (W3ContactNickName != null) { W3ContactNickName.AsStoredContactProperties(ref properties); } // Note if (W3ContactNotes != null) { W3ContactNotes.AsStoredContactProperties(ref properties); } // Organization if (Organization != null) { Organization.AsStoredContactProperties(ref properties); } // Phones if (Phones != null && Phones.Count > 0) { Phones.ForEach(phone => phone.AsStoredContactProperties(ref properties)); } // Photos if (Photos != null && Photos.Count > 0) { W3ContactPhoto firstPhoto = Photos.FirstOrDefault(); if (firstPhoto != null) { await firstPhoto.SetPictureOnStoredContactAsync(contact); } } // Urls if (Urls != null && Urls.Count > 0) { Urls.ForEach(url => url.AsStoredContactProperties(ref properties)); } return(contact); }