与众不同 windows phone (39) - 8.0 联系人和日历

[源码下载]


与众不同 windows phone (39) - 8.0 联系人和日历



作者:webabcd


介绍
与众不同 windows phone 8.0 之 联系人和日历

  • 自定义联系人存储的增删改查
  • 获取 Windows Phone 的联系人数据
  • 获取 Windows Phone 的日历数据



示例
1、演示如何操作自定义联系人存储(自定义联系人的增删改查)
ContactsAndCalendar/CustomContacts.xaml

<phone:PhoneApplicationPage
    x:Class="Demo.ContactsAndCalendar.CustomContacts"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:phone="clr-namespace:Microsoft.Phone.Controls;assembly=Microsoft.Phone"
    xmlns:shell="clr-namespace:Microsoft.Phone.Shell;assembly=Microsoft.Phone"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    FontFamily="{StaticResource PhoneFontFamilyNormal}"
    FontSize="{StaticResource PhoneFontSizeNormal}"
    Foreground="{StaticResource PhoneForegroundBrush}"
    SupportedOrientations="Portrait" Orientation="Portrait"
    mc:Ignorable="d"
    shell:SystemTray.IsVisible="True">
    
    <Grid Background="Transparent">
        <StackPanel Orientation="Vertical">

            <TextBlock x:Name="lblMsg" />

            <Button x:Name="btnAdd" Content="添加联系人" Click="btnAdd_Click" />

            <Button x:Name="btnUpdate" Content="更新联系人" Click="btnUpdate_Click" />

            <Button x:Name="btnDelete" Content="删除联系人" Click="btnDelete_Click" />

            <Button x:Name="btnQuery" Content="查询联系人" Click="btnQuery_Click" />

        </StackPanel>
    </Grid>
    
</phone:PhoneApplicationPage>

ContactsAndCalendar/CustomContacts.xaml.cs

/*
 * 演示如何操作自定义联系人存储(自定义联系人的增删改查)
 * 
 * 
 * ContactStore - 自定义联系人存储
 *     CreateOrOpenAsync(ContactStoreSystemAccessMode access, ContactStoreApplicationAccessMode sharing) - 创建或打开本 app 的自定义联系人存储
 *         ContactStoreSystemAccessMode - 操作系统对本 app 的自定义联系人存储的访问模式
 *             ReadOnly - 只能读
 *             ReadWrite - 除了读外,还可以修改
 *         ContactStoreApplicationAccessMode - 其他 app 对本 app 的自定义联系人存储的访问模式
 *             LimitedReadOnly - 只能读联系人的说明和显示图片
 *             ReadOnly - 可以读任何属性
 *     FindContactByIdAsync(), FindContactByRemoteIdAsync - 根据 Id 或 RemoteId 查找指定的联系人,返回 StoredContact 类型的对象
 *     DeleteContactAsync(), DeleteAsync() - 根据 Id 删除联系人,或者删除全部联系人
 *     CreateContactQuery(ContactQueryOptions options) - 创建一个联系人查询,返回 ContactQueryResult 类型的对象
 *         ContactQueryOptions - 查询参数
 *             DesiredFields - 需要返回的属性列表
 *             OrderBy - 排序字段(ContactQueryResultOrdering 枚举)
 *                 SystemDefault - 默认排序
 *                 GivenNameFamilyName - 先按名排序,再按姓排序
 *                 FamilyNameGivenName - 先按姓排序,再按名排序
 *     RevisionNumber - ContactStore 的修订号,只读
 *     GetChangesAsync(ulong baseRevisionNumber) - 返回与指定修订号关联的每次更改的 ContactChangeRecord 对象
 *     LoadExtendedPropertiesAsync() - 获取 ContactStore 的扩展属性集合
 *     SaveExtendedPropertiesAsync() - 保存 ContactStore 的扩展属性集合
 * 
 * StoredContact - 联系人对象
 *     FamilyName - 姓
 *     GivenName - 名
 *     HonorificPrefix - 前缀尊称
 *     HonorificSuffix - 后缀尊称
 *     DisplayName - 显示名称
 *     DisplayPicture - 显示图片
 *     Id - 联系人的本地标识(只读)
 *     RemoteId - 联系人的远程标识,应确保其在手机上的所有应用中都是唯一的
 *     Store - 对应的 ContactStore 对象
 *     KnownContactProperties() - 异步方式获取显示图片
 *     SetDisplayPictureAsync() - 异步方式设置显示图片
 *     GetPropertiesAsync() - 获取已知属性(key 的值为 Windows.Phone.PersonalInformation.KnownContactProperties 类中的字段)
 *     GetExtendedPropertiesAsync() - 获取扩展属性(key 的值任意)
 *     SaveAsync() - 保存当前联系人信息
 *     ReplaceExistingContactAsync(string id) - 使用当前联系人替换指定 Id 的联系人
 *     
 * ContactQueryResult - 联系人查询结果对象
 *     GetContactsAsync() - 获取全部联系人
 *     GetContactsAsync(uint startIndex, uint maxNumberOfItems) - 获取指定范围的联系人
 *     GetContactCountAsync() - 获取当前查询的联系人总数
 *     GetCurrentQueryOptions() - 获取对应的 ContactQueryOptions,参见 CreateContactQuery(ContactQueryOptions options)
 * 
 * 
 * 注:
 * 1、需要在 mainfest 中增加 <Capability Name="ID_CAP_CONTACTS" />
 * 2、Id 代表联系人的本地标识(只读)
 * 3、RemoteId 代表联系人的远程标识,应确保其在手机上的所有应用中都是唯一的
 */

using System;
using System.Collections.Generic;
using System.Windows;
using Microsoft.Phone.Controls;
using Windows.Phone.PersonalInformation;

namespace Demo.ContactsAndCalendar
{
    public partial class CustomContacts : PhoneApplicationPage
    {
        private Random _random = new Random();

        public CustomContacts()
        {
            InitializeComponent();
        }

        // 添加联系人
        private async void btnAdd_Click(object sender, RoutedEventArgs e)
        {
            ContactStore contactStore = await ContactStore.CreateOrOpenAsync();

            StoredContact storedContact = new StoredContact(contactStore);

            storedContact.RemoteId = Guid.Empty.ToString();

            storedContact.GivenName = _random.Next(1000, 10000).ToString();
            storedContact.FamilyName = "wang";

            // 设置已知属性
            IDictionary<string, object> props = await storedContact.GetPropertiesAsync();
            props.Add(KnownContactProperties.Email, "xxx@xxx.xxx");

            // 设置扩展属性
            IDictionary<string, object> extprops = await storedContact.GetExtendedPropertiesAsync();
            extprops.Add("ext1", "ext1");

            // 保存当前联系人
            await storedContact.SaveAsync();
        }

        // 更新联系人
        private async void btnUpdate_Click(object sender, RoutedEventArgs e)
        {
            ContactStore contactStore = await ContactStore.CreateOrOpenAsync();

            string remoteId = Guid.Empty.ToString();
            StoredContact storedContact = await contactStore.FindContactByRemoteIdAsync(remoteId);

            if (storedContact != null)
            {
                storedContact.GivenName = _random.Next(1000, 10000).ToString();
                storedContact.FamilyName = "wang";

                // 设置已知属性
                IDictionary<string, object> props = await storedContact.GetPropertiesAsync();
                props[KnownContactProperties.Email] = "xxx@xxx.xxx";

                // 设置扩展属性
                IDictionary<string, object> extprops = await storedContact.GetExtendedPropertiesAsync();
                extprops["ext1"] = "ext1";

                // 保存当前联系人
                await storedContact.SaveAsync();
            }
        }

        // 删除联系人
        private async void btnDelete_Click(object sender, RoutedEventArgs e)
        {
            ContactStore contactStore = await ContactStore.CreateOrOpenAsync();

            string remoteId = Guid.Empty.ToString();
            StoredContact storedContact = await contactStore.FindContactByRemoteIdAsync(remoteId);

            // 根据本地标识删除联系人
            await contactStore.DeleteContactAsync(storedContact.Id);
        }

        // 查询联系人
        private async void btnQuery_Click(object sender, RoutedEventArgs e)
        {
            ContactStore contactStore = await ContactStore.CreateOrOpenAsync();
            ContactQueryResult result = contactStore.CreateContactQuery();
            IReadOnlyList<StoredContact> storedContacts = await result.GetContactsAsync();

            lblMsg.Text = "本 app 的自定义联系人总数: " + storedContacts.Count.ToString();
        }      
    }
}


2、演示如何获取 Windows Phone 的联系人数据
ContactsAndCalendar/AccessContacts.xaml

<phone:PhoneApplicationPage
    x:Class="Demo.ContactsAndCalendar.AccessContacts"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:phone="clr-namespace:Microsoft.Phone.Controls;assembly=Microsoft.Phone"
    xmlns:shell="clr-namespace:Microsoft.Phone.Shell;assembly=Microsoft.Phone"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    FontFamily="{StaticResource PhoneFontFamilyNormal}"
    FontSize="{StaticResource PhoneFontSizeNormal}"
    Foreground="{StaticResource PhoneForegroundBrush}"
    SupportedOrientations="Portrait" Orientation="Portrait"
    mc:Ignorable="d"
    shell:SystemTray.IsVisible="True">

    <Grid Background="Transparent">
        <StackPanel Orientation="Vertical">

            <TextBlock x:Name="lblMsg" />
            
            <Image Name="img" Width="100" Height="100" />
            <Image Name="img2" Width="100" Height="100" Margin="0 10 0 0" />
            
            <Button x:Name="btnGet" Content="获取联系人数据" Click="btnGet_Click" />

        </StackPanel>
    </Grid>

</phone:PhoneApplicationPage>

ContactsAndCalendar/AccessContacts.xaml.cs

/*
 * 演示如何获取 Windows Phone 的联系人数据
 * 
 * 
 * 注:
 * 1、需要在 mainfest 中增加 <Capability Name="ID_CAP_CONTACTS" />
 * 2、获取联系人数据之前,应提供隐私策略并得到用户的允许。参见:http://msdn.microsoft.com/zh-cn/library/windowsphone/develop/hh184841(v=vs.105).aspx 的 2.11
 * 3、关于获取联系人和日历数据请参见:http://www.cnblogs.com/webabcd/archive/2012/08/29/2661418.html
 */

using System;
using System.Linq;
using System.Windows;
using Microsoft.Phone.Controls;
using Microsoft.Phone.UserData;
using System.Collections.Generic;
using System.Windows.Media.Imaging;

namespace Demo.ContactsAndCalendar
{
    public partial class AccessContacts : PhoneApplicationPage
    {
        public AccessContacts()
        {
            InitializeComponent();
        }

        private void btnGet_Click(object sender, RoutedEventArgs e)
        {
            // Contacts - 用于获取联系人数据
            Contacts contacts = new Contacts();

            // Contacts.SearchCompleted - 当搜索联系人数据完成时所触发的事件
            contacts.SearchCompleted += contacts_SearchCompleted;

            /*
             * Contacts.SearchAsync(string filter, FilterKind filterKind, object state) - 按指定参数搜索联系人
             *     string filter - 搜索关键字
             *     FilterKind filterKind - 搜索范围
             *         None - 全部联系人
             *         PinnedToStart - 在固定到开始屏幕的联系人中搜索
             *         EmailAddress - 按电子邮件地址搜索
             *         PhoneNumber - 按电话号码搜索
             *         DisplayName - 按显示名称搜索
             *         Identifier - 按本地标识搜索
             *     object state - 异步处理的上下文对象
             */
            contacts.SearchAsync(string.Empty, FilterKind.None, null);
        }

        void contacts_SearchCompleted(object sender, ContactsSearchEventArgs e)
        {
            /*
             * ContactsSearchEventArgs - 事件参数
             *     Filter, FilterKind, State - 对应 Contacts.SearchAsync() 方法中的参数
             *     Results - 搜索结果
             * 
             * Contact - 某个联系人的相关信息
             *     详细说明见文档,以下就部分属性和方法做说明
             */
            IEnumerable<Contact> contacts = e.Results;

            lblMsg.Text = "联系人数量:" + contacts.Count().ToString();
            lblMsg.Text += Environment.NewLine;

            lblMsg.Text += "第一个联系人的所属数据源数量:" + contacts.First().Accounts.Count();
            lblMsg.Text += Environment.NewLine;

            // StorageKind 枚举:Phone, WindowsLive, Outlook, Facebook, Other(自定义联系人存储属于 Other)
            lblMsg.Text += "第一个联系人的所属的第一个数据源:" + contacts.First().Accounts.First().Kind.ToString();
            lblMsg.Text += Environment.NewLine;

            lblMsg.Text += "第一个联系人的显示名称:" + contacts.First().DisplayName;
            lblMsg.Text += Environment.NewLine;

            // 第一个联系人的照片
            BitmapImage bitmapImage = new BitmapImage();
            bitmapImage.SetSource(contacts.First().GetPicture());
            img.Source = bitmapImage; // 第一种显示 Stream 图片的方法

            img2.Source = Microsoft.Phone.PictureDecoder.DecodeJpeg(contacts.First().GetPicture()); // 第二种显示 Stream 图片的方法
        }
    }
}


3、演示如何获取 Windows Phone 的日历数据
ContactsAndCalendar/AccessCalendar.xaml

<phone:PhoneApplicationPage
    x:Class="Demo.ContactsAndCalendar.AccessCalendar"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:phone="clr-namespace:Microsoft.Phone.Controls;assembly=Microsoft.Phone"
    xmlns:shell="clr-namespace:Microsoft.Phone.Shell;assembly=Microsoft.Phone"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    FontFamily="{StaticResource PhoneFontFamilyNormal}"
    FontSize="{StaticResource PhoneFontSizeNormal}"
    Foreground="{StaticResource PhoneForegroundBrush}"
    SupportedOrientations="Portrait" Orientation="Portrait"
    mc:Ignorable="d"
    shell:SystemTray.IsVisible="True">

    <Grid Background="Transparent">
        <StackPanel Orientation="Vertical">

            <TextBlock x:Name="lblMsg" />

            <Button x:Name="btnGet" Content="获取日历数据" Click="btnGet_Click" />

        </StackPanel>
    </Grid>

</phone:PhoneApplicationPage>

ContactsAndCalendar/AccessCalendar.xaml.cs

/*
 * 演示如何获取 Windows Phone 的日历数据
 * 
 * 
 * 注:
 * 1、需要在 mainfest 中增加 <Capability Name="ID_CAP_APPOINTMENTS" />
 * 2、获取日历数据之前,应提供隐私策略并得到用户的允许。参见:http://msdn.microsoft.com/zh-cn/library/windowsphone/develop/hh184841(v=vs.105).aspx 的 2.11
 * 3、关于获取联系人和日历数据请参见:http://www.cnblogs.com/webabcd/archive/2012/08/29/2661418.html
 */

using System;
using System.Linq;
using System.Windows;
using Microsoft.Phone.Controls;
using Microsoft.Phone.UserData;
using System.Collections.Generic;

namespace Demo.ContactsAndCalendar
{
    public partial class AccessCalendar : PhoneApplicationPage
    {
        public AccessCalendar()
        {
            InitializeComponent();
        }

        private void btnGet_Click(object sender, RoutedEventArgs e)
        {
            // Appointments - 用于获取日历数据
            Appointments appointments = new Appointments();

            // Appointments.SearchCompleted - 当搜索日历数据完成时所触发的事件
            appointments.SearchCompleted += appointments_SearchCompleted;

            DateTime start = DateTime.Now;
            DateTime end = start.AddDays(7);
            int max = 20;

            /*
             * Appointments.SearchAsync(DateTime startTimeInclusive, DateTime endTimeInclusive, int maximumItems, Account account, object state) - 按指定参数搜索日历数据
             *     DateTime startTimeInclusive - 约会的开始时间
             *     DateTime endTimeInclusive - 约会的结束时间
             *     int maximumItems - 返回约会的最大数量
             *     Account account - 要搜索的约会的数据源
             *     object state - 异步处理的上下文对象
             */
            appointments.SearchAsync(start, end, max, "Appointments Test #1");
        }

        void appointments_SearchCompleted(object sender, AppointmentsSearchEventArgs e)
        {
            /*
             * AppointmentsSearchEventArgs - 事件参数
             *     StartTimeInclusive, EndTimeInclusive, State - 对应 Appointments.SearchAsync() 方法中的参数
             *     Results - 搜索结果
             * 
             * Appointment - 某个约会的相关信息
             *     详细说明见文档,以下就部分属性和方法做说明
             */
            IEnumerable<Appointment> appointments = e.Results;

            lblMsg.Text = "获取到的约会数量:" + appointments.Count().ToString();
            lblMsg.Text += Environment.NewLine;

            lblMsg.Text += "第一个约会所属数据源的账户名称:" + appointments.First().Account.Name;
            lblMsg.Text += Environment.NewLine;

            // StorageKind 枚举:Phone, WindowsLive, Outlook, Facebook, Other
            lblMsg.Text += "第一个约会所属数据源的种类:" + appointments.First().Account.Kind.ToString();
            lblMsg.Text += Environment.NewLine;

            lblMsg.Text += "第一个约会的主题:" + appointments.First().Subject;
            lblMsg.Text += Environment.NewLine;
        }
    }
}



OK
[源码下载]

posted @ 2013-12-12 10:05  webabcd  阅读(2196)  评论(2编辑  收藏  举报