Friday, February 18, 2011

How to reorder columns in Sharepoint Lists through Webservice


We have already seen how to reorder list columns through OM in my earlier post.

Let’s see how to achieve it through web service.

We are going to order the fields in the site content type that has been associated in the list through web service. The field ordering is done by the order in which <field> are presents within <Fields> tag. Hence we are going to reorder the fields by deleting the field tag and then adding them in the order we want. 

As we are going to make change in site content type we will use webs.asmx.
The following example will use UpdateContentType method of the webs.asmx to add and delete the fields in the content type.

Xml file

<?xml version="1.0" encoding="utf-8" ?>
<soapEnvelope>
  <soapBody>
    <UpdateContentType>
      <contentTypeId>0x010039AAF2FFAC8C2E468531F5B23B4595F2</contentTypeId>
      <contentTypeProperties>
        <ContentType Group="MyCT"/>
      </contentTypeProperties>
      <newFields>
        <Fields>
          <Method ID="1">
            <Field ID="{9fb22ff8-a1e6-46e5-9ee1-bcc1c95fab35}" Name="ColumeOrgFirst"/>
          </Method>
          <Method ID="2">
            <Field ID="{082f8d40-6f6b-438d-96dd-4a9958c08d8c}" Name="ColumeOrg2"/>
          </Method>
        </Fields>
      </newFields>

      <updateFields>
        <Fields>
        </Fields>
      </updateFields>

      <deleteFields>
        <Fields>
          <Method ID="1">
            <Field ID="{9fb22ff8-a1e6-46e5-9ee1-bcc1c95fab35}" Name="ColumeOrgFirst"/>
          </Method>
          <Method ID="2">
            <Field ID="{082f8d40-6f6b-438d-96dd-4a9958c08d8c}" Name="ColumeOrg2"/>
          </Method>
        </Fields>
      </deleteFields>

    </UpdateContentType>
  </soapBody>
</soapEnvelope>


Code

namespace CTOrder
{
    class Program
    {
        static void Main(string[] args)
        {
            webWS.Webs myWebs = new webWS.Webs();
            myWebs.Credentials = System.Net.CredentialCache.DefaultCredentials;

            myWebs.Url = "http://Site_URL/_vti_bin/webs.asmx";
            XmlReader myXmlReader = new XmlTextReader(@"ct.xml");
            XmlDocument myDoc = new XmlDocument();
            myDoc.Load(myXmlReader);
            XmlNode myProps = myDoc.SelectSingleNode("/soapEnvelope/soapBody/UpdateContentType/contentTypeProperties");
            XmlNode myDel = myDoc.SelectSingleNode("/soapEnvelope/soapBody/UpdateContentType/deleteFields");
            XmlNode myUpdate = myDoc.SelectSingleNode("/soapEnvelope/soapBody/UpdateContentType/updateFields");
            XmlNode myNew = myDoc.SelectSingleNode("/soapEnvelope/soapBody/UpdateContentType/newFields");
            XmlNode res = myWebs.UpdateContentType("0x010039AAF2FFAC8C2E468531F5B23B4595F2", myProps, myNew, myUpdate, myDel);

            myXmlReader.Close();

            Console.WriteLine(res.InnerXml);
            Console.ReadLine();
        }
    }
}


Happy Coding!!!

How to reorder columns in Sharepoint Lists through Object model

Let's first see what are site columns, list columns and content types 

Site columns  
Site columns are those columns created at site level. These columns will be available across the site. We can add these columns to any list within the site. We can create the site columns by navigating to site columns gallery from site settings.

List columns
List columns are the columns to the list they are created. These columns cannot be added to other lists. If we want the same column to be added to some other list, we need to create a site column and then attached it to list or we need a new column to the list.

Content Types
Content types are nothing but group of columns. Content types created at site level are known as site content types. Content types created at list level are known as list content types.
Whenever we create a new Custom list, the content type “Item” gets attached to it. [For Doc library, content type “document” gets associated with it].

Whenever we add list columns to the list, those list columns will gets automatically associated with the existing content type(i.e.)”Item”. We might wonder that we did not explicitly create a content type, but how come it is getting associated. That’s the power of content type. You can see this behavior by enabling “Allow management of content type” in advanced settings of list settings. Then click on the item content type and have a look. Along with Title column you would be able to see the list columns associated with it. 


Now let’s see how we can re-order list columns through OM.
Upon knowing the fact that list columns gets automatically get associated with the content type, we are going to reorder the fields(columns) in the content type of the list. 

The code given below reorders the columns of a custom list.

Note: This changes the column order in new and edit form of the items in List. It does not change the order in display form. To achieve the column reordering in display form, you need to reorder columns in views.

using (SPSite site = new SPSite("http://SiteURL/"))
            {
                using (SPWeb web = site.OpenWeb())
                {
                    SPContentType ct = web.Lists["List_Name"].ContentTypes["Item"];
                    SPFieldLinkCollection flinks = ct.FieldLinks;

                    string[] fields = new string[3] { "firstCol", "Title", "secondCol" };
                    flinks.Reorder(fields);
                    ct.Update();
                }
            }


Monday, December 27, 2010

ProcessBatchData in Sharepoint

Sometimes we need to update more than one item in a list, so looping through all items in sharepoint list would not be good practice, as it degrades performance.  


The better way to do this, is through ProcessBatchData. In this we construct a CAML string  contains a batch of commands to perform the updates. Then we should execute the commands by using the ProcessBatchData command of an SPWeb object.


Each command includes a Method element with SetVar subelements. 
The SetVar elements define 

  • Type of command e.g. <SetVar Name=\"Cmd\">
  • ID of the item e.g. <SetVar Name=\"ID\">
  • Fields to update. The fields are defined in the format <schema>#<internal_field_name> e.g. <SetVar Name=\"urn:schemas-microsoft-com:office:office#PersonID\">

The Guid of the List must be specified in <SetList> tag.


After all the commands are created, they are placed in an ows:Batch element. This element contains an OnError attribute that defines what happens if an exception occurs while the commands are executed


Thats it, here is the snippet 


Batch command to add a new item to Sharepoint list

As we are going to add a new item, just specify "New" in place of ID <SetVar Name \"ID\">. I have highlighted in the below code snippet.

 using (SPSite site = new SPSite("http://sitecollectionURL"))
            {
                using (SPWeb web = site.OpenWeb())
                {
                        SPList list = web.Lists["ListName"];
                        string listGuid = list.ID.ToString();
                        string _xmlData = "";
                   
                        SPUser theUser = web.SiteUsers[_userID];
                        SPListItem item = list.Items.Add();
                        string _personID = theUser.ID.ToString() + ";#" + theUser.Name;

                        batch = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>" +
                            "<ows:Batch OnError=\"Return\">{0}</ows:Batch>" + "<Method ID=\"{0}\">" +
                            "<SetList>" + listGuid + "</SetList>" +
                            "<SetVar Name=\"Cmd\">Save</SetVar>" +
                            "<SetVar Name=\"ID\">New</SetVar>" +
                            "<SetVar Name=\"urn:schemas-microsoft-com:office:office#PersonID\">" + _personID + "</SetVar>" +
                            "<SetVar Name=\"urn:schemas-microsoft-com:office:office#XmlData\">" + _xmlData + "</SetVar>" +
                            "</Method>";
                    
                    string batchReturn = web.ProcessBatchData(batch);
                }
            }




Batch command to update an item in the Sharepoint list

To update an item in the sharepoint list, we just need to put the item id to update in the tag <SetVar Name \"ID\">. I have highlighted in the below code snippet.


        using (SPSite site = new SPSite("http://sitecollectionURL"))
            {
                using (SPWeb web = site.OpenWeb())
                {
                        SPList list = web.Lists["ListName"];
                        string listGuid = list.ID.ToString();
                        string _xmlData = "";
                   
                        SPUser theUser = web.SiteUsers[_userID];
                        SPListItem item = list.Items.Add();
                        string _personID = theUser.ID.ToString() + ";#" + theUser.Name;

                        batch = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>" +
                            "<ows:Batch OnError=\"Return\">{0}</ows:Batch>" + "<Method ID=\"{0}\">" +
                            "<SetList>" + listGuid + "</SetList>" +
                            "<SetVar Name=\"Cmd\">Save</SetVar>" +
                            "<SetVar Name=\"ID\">ItemID</SetVar>" +
                            "<SetVar Name=\"urn:schemas-microsoft-com:office:office#PersonID\">" + _personID + "</SetVar>" +
                            "<SetVar Name=\"urn:schemas-microsoft-com:office:office#XmlData\">" + _xmlData + "</SetVar>" +
                            "</Method>";
                    
                    string batchReturn = web.ProcessBatchData(batch);
                }
            }