天天看點

Windows store 應用調用 SharePoint Service

本人之前并沒有開發SharePoint 的相關經驗不夠最近做了一個 Windows store 和 SharePoint  Service的小工程多虧朋友們幫忙,在這裡總結一下經驗供大家參考。

首先SharePoint每個Page或者WebSite都有自身強大的WebService或WCF。 隻需要在URL 站點目錄後面加上 /_vti_bin/Lists.asmx

Windows store 應用調用 SharePoint Service
Windows store 應用調用 SharePoint Service

這裡有一個重要的問題就是, Windows store 應用在自動生成引用代碼的時候會錯誤生成一些http://******/_vti_bin/Lists.asmx,而實際我們添加的位址是: http://******/sites/*******/_vti_bin/Lists.asmx是以我需要在項目中使用VS的替換功能把錯誤的位址替換掉。

引用完成後不要忘記在 appxmanifest 檔案中勾選 Private Network 和 Enterprise Authentication選項 因為我這個工程是在公司域中可以使用windows 內建驗證方法登陸.

Windows store 應用調用 SharePoint Service

另外我提供一下調用service的方法 其中System.ServiceModel.Security.MessageSecurityException 這個異常是使用者沒有加入域需要使用者名密碼驗證的錯誤,System.ServiceModel.EndpointNotFoundException 是網絡連接配接錯誤。

其次擷取一張表單的内容是調用 GetListItemsAsync 方法.

private async Task<XElement> GetDataFromService(string serviceName, string userName = null, string password = null, string domain = null)
{
    SPService.ListsSoapClient client = new SPService.ListsSoapClient();
    var binding = ((BasicHttpBinding)client.Endpoint.Binding);
    binding.Security.Mode = System.ServiceModel.BasicHttpSecurityMode.TransportCredentialOnly;
    binding.Security.Transport.ClientCredentialType = System.ServiceModel.HttpClientCredentialType.Ntlm;
    client.ClientCredentials.Windows.ClientCredential = new NetworkCredential(userName, password, domain);
    GetListItemsResponse lists = null;
    try
    {
        lists = await client.GetListItemsAsync(serviceName, string.Empty, null, null, "1000", null, null);
    }
    catch (System.ServiceModel.Security.MessageSecurityException e)
    {
        throw new MessageSecurityException("Please check your user name and password.");
    }
    catch (System.ServiceModel.EndpointNotFoundException e)
    {
        throw new EndpointNotFoundException("Please check your Microsoft network connection and access permissions.");
    }
    return lists.Body.GetListItemsResult;
}      

前面的方法會傳回一個XElement 需要我們手動解析不過也很簡單.

public async Task<ObservableCollection<DashBoard>> GetDashBoard(string userName = null, string password = null, string domain = null)
{ 
    XElement xml = await GetDataFromService("DashBoardTable", userName, password, domain);
    var items = xml.Elements().Elements().ToList();
    var result = from o in items
                 select new DashBoard() 
                 { 
                     Department = o.Attribute("ows_Department").GetStringFromXMLAttribute(), 
                     Attained = o.Attribute("ows_Attained").GetStringFromXMLAttribute(), 
                     Target = o.Attribute("ows_Target").GetStringFromXMLAttribute(),
                 };
    ObservableCollection<DashBoard> List = new ObservableCollection<DashBoard>(result);
    return List;
}      

繼續閱讀