Radi Atanassov

SharePoint MCM, MVP, MCT and owner of OneBit Software

Използване на LINQ to XML върху резултатите от SharePoint Web Services

Когато работиме със Silverlight имаме възможност да използваме LINQ to XML за извличане на данни от резултатите от SharePoint Web Services. Тези дни разгледах LINQ to XML и никога повече не бих работил с XmlDocument обектите (:

Ето няколко примера:

GetListItems() – това е метод от Lists.asmx, и ето му отговора:

<listitems xmlns:s="uuid:BDC6E3F0-6DA3-11d1-A2A3-00AA00C14882"
xmlns:dt="uuid:C2F41010-65B3-11d1-A29F-00AA00C14882"
xmlns:rs="urn:schemas-microsoft-com:rowset" xmlns:z="#RowsetSchema"
xmlns="http://schemas.microsoft.com/sharepoint/soap/">
<rs:data ItemCount="13">
   <z:row ... ows_ContentType="Task" ows_Title="New Task 1" ... />
   ... more rows here
</rs:data>
</listitems>

За да извлечем заглавията на list items и да ги подредим в List<string> обект:

private List<string> ProcessListResults(SPListsWS.GetListItemsCompletedEventArgs e)
{
    string result = e.Result.ToString();
 
    XNamespace ns = "#RowsetSchema";
    XElement results = new XElement(e.Result);
 
    var listItems = from x in results.Descendants(ns + "row")
                    where x.Attribute("ows_Title") != null
                    select x;
 
    List<string> itemsList = new List<string>();
 
    foreach (var item in listItems)
    {
        string title = item.Attribute("ows_Title").Value;
        itemsList.Add(title);
    }
    return itemsList;
}

GetUserInfo() – Този метод е от usergroup.asmx и ни дава информация за user в текущия SPSite обект (взима го от скрития user list). Ето отговора:

<GetUserInfo xmlns="http://schemas.microsoft.com/sharepoint/soap/directory/">
  <User ID="7" Sid="S-1-5-21-347908140-582334945-263120918-1111" Name="Radi"
    LoginName="DEV\radi" Email="" Notes="" IsSiteAdmin="False"
    IsDomainGroup="False" />
</GetUserInfo>

 

И как извлиам LoginName:

public static string GetLoginFromServiceResponse(XElement result)
{
    XNamespace ns = "http://schemas.microsoft.com/sharepoint/soap/directory/";
 
    XName xUser = XName.Get("User", ns.NamespaceName);
    XName xUserInfo = XName.Get("GetUserInfo", ns.NamespaceName);
 
    XElement user = result.Element(xUser);
 
    if (user != null) {  return user.Attribute("LoginName").Value; }
 
    return null;
}

Това което подавам на метода е “e.Result.ToString()” от отговора.

Очаквайте още!

Using LINQ to XML to process SharePoint web service responses in Silverlight

Since working with LINQ to XML, I’ve totally fallen in love with it and could never go back to working with the XmlDocument objects.

Here are a few code snippets that can help you out. It is so simple once you get a hang of it.

GetListItems() – this Lists.asmx method returns the following response:

<listitems xmlns:s="uuid:BDC6E3F0-6DA3-11d1-A2A3-00AA00C14882"
xmlns:dt="uuid:C2F41010-65B3-11d1-A29F-00AA00C14882"
xmlns:rs="urn:schemas-microsoft-com:rowset" xmlns:z="#RowsetSchema"
xmlns="http://schemas.microsoft.com/sharepoint/soap/">
<rs:data ItemCount="13">
   <z:row ... ows_ContentType="Task" ows_Title="New Task 1" ... />
   ... more rows here
</rs:data>
</listitems>

To get the value of the title into a List<string> object:

private List<string> ProcessListResults(SPListsWS.GetListItemsCompletedEventArgs e)
{
    string result = e.Result.ToString();
 
    XNamespace ns = "#RowsetSchema";
    XElement results = new XElement(e.Result);
 
    var listItems = from x in results.Descendants(ns + "row")
                    where x.Attribute("ows_Title") != null
                    select x;
 
    List<string> itemsList = new List<string>();
 
    foreach (var item in listItems)
    {
        string title = item.Attribute("ows_Title").Value;
        itemsList.Add(title);
    }
    return itemsList;
}

GetUserInfo() – this method is inside usergroup.asmx and gives us information regarding a user in an SPSite object. The response:

<GetUserInfo xmlns="http://schemas.microsoft.com/sharepoint/soap/directory/">
  <User ID="7" Sid="S-1-5-21-347908140-582334945-263120918-1111" Name="Radi"
    LoginName="DEV\radi" Email="" Notes="" IsSiteAdmin="False"
    IsDomainGroup="False" />
</GetUserInfo>

 

To get the LoginName:

public static string GetLoginFromServiceResponse(XElement result)
{
    XNamespace ns = "http://schemas.microsoft.com/sharepoint/soap/directory/";
 
    XName xUser = XName.Get("User", ns.NamespaceName);
    XName xUserInfo = XName.Get("GetUserInfo", ns.NamespaceName);
 
    XElement user = result.Element(xUser);
 
    if (user != null) {  return user.Attribute("LoginName").Value; }
 
    return null;
}

The passed in “result” is derived from e.Result.ToString().

Hope this helps!

SharePoint meets LINQ to XML: CAML заявки за работа с Lists.asmx

Напоследък ми се налага да работя с LINQ to XML за интеграционни сценарии включващи Silverlight и SharePoint. LINQ to XML е страхотно – сравнително по-добре от създаване на XML чрез обекти като XmlDocument.

Ето пример – повиквам GetListItems() метода на Lists.asmx. Със следният код извличам list items от Task списъка създадени от специфичен user. Този пример би трябвало да работи както за WSS v3, така и за MSF v4.

XElement query = new XElement("Query",
        new XElement("Where",
            new XElement("Eq",
                new XElement("FieldRef", new XAttribute("Name", "Author"), new XAttribute("LookupId", "True")),
                new XElement("Value", new XAttribute("Type", "User"), userID)
)));


XElement queryOptions = new XElement("QueryOptions");
XElement viewFields = new XElement("ViewFields");

_listService.GetListItemsAsync("Tasks", null,
    query, viewFields, "100", queryOptions, null, null);

userID e SharePoint ID-то на потребителя, за който искам да видя резултатите. Можете да получите тази информация от usergroup.asmx.

Успех!

SharePoint meets LINQ to XML: Building a CAML Query and calling Lists.asmx

I’ve been playing around with LINQ to XML and Silverlight recently, and it is absolutely awesome! The amount of code you have to write compared to working with XML DOM objects like XmlDocument is extremely minimised.

Here is an example on calling the GetListItems() method of Lists.asmx. I am returning the top 100 items in a Task list that are created by a particular user. This code example should be compatible for both WSS v3 and MSF v4.

XElement query = new XElement("Query",
        new XElement("Where",
            new XElement("Eq",
                new XElement("FieldRef", new XAttribute("Name", "Author"), new XAttribute("LookupId", "True")),
                new XElement("Value", new XAttribute("Type", "User"), userID)
)));


XElement queryOptions = new XElement("QueryOptions");
XElement viewFields = new XElement("ViewFields");

_listService.GetListItemsAsync("Tasks", null,
    query, viewFields, "100", queryOptions, null, null);

userID is the SharePoint user value within the current SPSite. You can get this with the usergroup.asmx service.

Hope this helps!