Thursday, March 1, 2012

Get SharePoint List Views using Web Services

Following is an example of displaying Views of a list in a DataGrid Control from SharePoint 2007 using Views.asmx and Lists.asmx Web Services.
public class SharePointManagement
{
    ViewsService.Views objViewsService = new SPViewsService.ViewsService.Views();
    ListsService.Lists objListsService = new SPViewsService.ListsService.Lists();
    string strSiteURL = "http://mySharepointServer:1100";
    string strUserName = "username";
    string strDomain = "us";
    string strPassword = "password";
    string strListName = "Announcements";
    string strQuery = "";
    string strViewFields = "";
    string strQueryOptions = "";

    ArrayList lstViewID = new ArrayList();

    public void GetViewQuery(string strListName)
    {
        try
        {
            #region Source URL
            //get the lists for the Source URL
            this.objViewsService.Url = this.strSiteURL.Trim('/') + "/_vti_bin/views.asmx";

            //get the domain
            if (this.strUserName.IndexOf("\\") > 0)
            {
                this.strDomain = this.strUserName.Split("\\".ToCharArray())[0];
                this.strUserName = this.strUserName.Split("\\".ToCharArray())[1];
            }

            this.objViewsService.Credentials = new System.Net.NetworkCredential(this.strUserName, this.strPassword, this.strDomain);


            #endregion

            System.Xml.XmlNode xnAllView = this.objViewsService.GetViewCollection(strListName);
            foreach (System.Xml.XmlNode node in xnAllView)
            {
                if (node.Name == "View")
                {
                    this.lstViewID.Add(node.Attributes["Name"].Value);
                }
            }

            //Get the First View
            System.Xml.XmlNode xnViewData = this.objViewsService.GetView(this.strListName, lstViewID[0].ToString());

            foreach (System.Xml.XmlNode node in xnViewData)
            {
                if (node.Name == "Query")
                {
                    this.strQuery = node.InnerXml;
                }
                if (node.Name == "ViewFields")
                {
                    this.strViewFields = node.InnerXml;
                }
            }

        }
        catch (System.Exception exp)
        {
            MessageBox.Show(exp.ToString());
        }
    }

    public void GetViewData()
    {
        DataSet ds = new DataSet();
        DataTable dt = new DataTable();

        try
        {
            #region Source URL
            //get the lists for the Source URL
            this.objListsService.Url = this.strSiteURL.Trim('/') + "/_vti_bin/lists.asmx";

            //get the domain
            if (this.strUserName.IndexOf("\\") > 0)
            {
                this.strDomain = this.strUserName.Split("\\".ToCharArray())[0];
                this.strUserName = this.strUserName.Split("\\".ToCharArray())[1];
            }

            this.objListsService.Credentials = new System.Net.NetworkCredential(this.strUserName, this.strPassword, this.strDomain);


            #endregion

            //get the Data from the List
            System.Xml.XmlDocument xdListData = new System.Xml.XmlDocument();
            System.Xml.XmlNode xnQuery = xdListData.CreateElement("Query");
            System.Xml.XmlNode xnViewFields = xdListData.CreateElement("ViewFields");
            System.Xml.XmlNode xnQueryOptions = xdListData.CreateElement("QueryOptions");

            //*Use CAML query*/ 
            xnQuery.InnerXml = this.strQuery;
            xnViewFields.InnerXml = this.strViewFields;
            xnQueryOptions.InnerXml = this.strQueryOptions;

            System.Xml.XmlNode xnListData = this.objListsService.GetListItems(this.strListName, null, xnQuery, xnViewFields, null, xnQueryOptions, null);


            StringReader sr = new StringReader(xnListData.OuterXml.Replace("ows_", ""));
            ds.ReadXml(sr);

            return dt;
        }
        catch (System.Exception exp)
        {
            MessageBox.Show(exp.ToString());
            return dt;
        }
    }
}

Monday, February 27, 2012

Upload a document through Web Services

A quick and easy function to upload documents in a SharePoint 2007 document library:

http://www.intheknow.it/uploaddoclistsws.ashx

Wednesday, February 22, 2012

Query a List via Lists.asmx

A quick .NET function to Query a MOSS List via Lists.asmx web service. I use this function time to time, so thought to post here.
Note: I already have posted similer code in my previous post but this is the full version.

using System;
using System.Collections.Generic;
using System.Text;
using System.Configuration;
using System.Xml;
using System.IO;

namespace ELLP_Content
{
    class Program
    {
        static void Main(string[] args)
        {
            SharePointManagement objSPManagement = new SharePointManagement();
            objSPManagement.GetListContent();
        }
    }

    public class SharePointManagement
    {
        MOSSListsService.Lists objListService = new ELLP_Content.MOSSListsService.Lists();

        public void GetListContent()
        {
            try
            {
                string strSiteURL = ConfigurationSettings.AppSettings["SiteURL"];
                string strUserName = ConfigurationSettings.AppSettings["Login"];
                string strDomain = string.Empty;
                string strPassword = ConfigurationSettings.AppSettings["Password"];
                string strListName = ConfigurationSettings.AppSettings["List"];

                #region Source URL
                //get the lists for the Source URL
                objListService.Url = strSiteURL.Trim('/') + "/_vti_bin/lists.asmx";

                //get the domain
                if (strUserName.IndexOf("\\") > 0)
                {
                    strDomain = strUserName.Split("\\".ToCharArray())[0];
                    strUserName = strUserName.Split("\\".ToCharArray())[1];
                }

                objListService.Credentials = new System.Net.NetworkCredential(strUserName, strPassword, strDomain);

                #endregion


                //get the Data from the List
                System.Xml.XmlDocument xdListData = new System.Xml.XmlDocument();
                System.Xml.XmlNode xnQuery = xdListData.CreateElement("Query");
                System.Xml.XmlNode xnViewFields = xdListData.CreateElement("ViewFields");
                System.Xml.XmlNode xnQueryOptions = xdListData.CreateElement("QueryOptions");

                //*Use CAML query*/ 
                xnQuery.InnerXml = "<Where><Neq><FieldRef Name=\"Exclude_x0020_From_x0020_Country\" /><Value Type=\"Boolean\">0</Value></Neq></Where>";

                xnQueryOptions.InnerXml = "<IncludeMandatoryColumns>FALSE</IncludeMandatoryColumns><DateInUtc>TRUE</DateInUtc>";

                System.Xml.XmlNode xnListData = objListService.GetListItems(strListName, null, xnQuery, xnViewFields, null, xnQueryOptions, null);


                foreach (System.Xml.XmlNode node in xnListData)
                {
                    if (node.Name == "rs:data")
                    {
                        for (int i = 0; i < node.ChildNodes.Count; i++)
                        {
                            if (node.ChildNodes[i].Name == "z:row")
                            {
                                Console.WriteLine(node.ChildNodes[i].Attributes["ows_Title"].Value);
                            }
                        }
                    }
                }

                Console.ReadKey();
            }
            catch (System.Web.Services.Protocols.SoapException ex)
            {
                this.WriteLog("Message:\n" + ex.Message + "\nDetail:\n" + ex.Detail.InnerText + "\nStackTrace:\n" + ex.StackTrace);
            }
        }

        private void WriteLog(string strLine)
        {

            string FilePath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, ConfigurationSettings.AppSettings["InputLog"]);
            StreamWriter objFile;

            if (!File.Exists(FilePath))
            {
                objFile = new StreamWriter(FilePath);
            }
            else
            {
                objFile = File.AppendText(FilePath);
            }

            objFile.WriteLine(DateTime.Now + "\\t" + strLine);
            objFile.WriteLine();
            objFile.Close();

        }
    }
}

SharePoint Navigation List Limitation

Today, one of the developers from Ireland team faced a problem while adding a link to the MOSS Navigation list. The item was simply not showing up on the left navigation. After doing some research we found out that in SharePoint 2007 only 50 items can be added to the navigation list.

Tuesday, January 31, 2012

SharePoint 15 Technical Preview SDK

Today I came to know about Office 15 will be available in the summer 2012 so my obvious reaction was "So will there be new version of SharePoint on its way?" and it was interesting to see that SharePoint 15's Technical Preview SDK is also available on Microsoft's site.

See the link below:
http://www.microsoft.com/download/en/confirmation.aspx?id=28768

Tuesday, January 10, 2012

SharePoint 2007 Web Service: Delete An Item Versions

Scenario:
We recently had a performance issue in our environment at client side and after some investigation we found out that there are many versions( Up to 500 No kidding) of documents(specially he ASPX) sit in the Content Database which are not even required.

Solution:
We developed a small .NET WinForm (MS Visual Studio 2005) based utility that uses SharePoint Webservice Versions.asmx to cleanup(delete all versions of an item and leave the latest one) the lists with non used versions.
Following is the Code to delete an item version (not the whole item):

1. Get the all the lists function:

//Class Level Variables 
//You need to add the web reference to the project 

public static string strVersionWebServiceURL;
WSLists.Lists _listService;
WSVersion.Versions _versionService;

// Actual Function
private void btnGetListCollection_Click(object sender, EventArgs e)
        {

            // List and Version web service declaration and initialization
            strListWebServiceURL = txtSiteURL.Text + "/_vti_bin/lists.asmx";
            strVersionWebServiceURL = txtSiteURL.Text + "/_vti_bin/versions.asmx";
            System.Net.NetworkCredential nt = new System.Net.NetworkCredential(txtUserName.Text, txtPassword.Text);

            _listService = new WSLists.Lists();
            _listService.Credentials = nt;
            _listService.Url = strListWebServiceURL;

            _versionService = new WSVersion.Versions();
            _versionService.Credentials = nt;
            _versionService.Url = strVersionWebServiceURL;

            // end declaration

            if (txtSiteURL.Text != string.Empty && txtUserName.Text != string.Empty && txtPassword.Text != string.Empty)
            {
                lsListCollection.Items.Clear();
                XmlNode _xmlListCollection = _listService.GetListCollection();
                for (int i = 0; i < _xmlListCollection.ChildNodes.Count; i++)
                {
                    string strListName = _xmlListCollection.ChildNodes[i].Attributes["Title"].Value.ToLower();
                    lsListCollection.Items.Add(strListName);
                }// End For Loop
            }
            else
            {
                MessageBox.Show("Site URL, User Name and Password must be entered");
            }
        }
2. Delete all the versions of all the items from the selected list function:
private void btnDeleteAllVersionofList_Click(object sender, EventArgs e)
        {
            string strndQuery = "<OrderBy><FieldRef Name=\"Modified\" Ascending=\"FALSE\" /></OrderBy>";
            /*string strndQuery = "<Where><Eq><FieldRef Name='ID' /><Value Type='Integer'>" + "76" + "</Value></Eq></Where>" +
                       "<OrderBy><FieldRef Name=\"Modified\" Ascending=\"FALSE\" /></OrderBy>";
            **/
            XmlNodeList _nodelist = GetListItems(strndQuery);
            if (_nodelist != null)
            {
                for (int i = 0; i < _nodelist.Count; i++)
                {
                    try
                    {
                        XmlNode _node = _nodelist[i];
                        string strItemURL = _node.Attributes["ows_EncodedAbsUrl"].Value;
 //                       MessageBox.Show(strItemURL);
                        XmlNode xmlVersionCollection = _versionService.DeleteAllVersions(strItemURL);
                    }
                    catch  {}
                }
                MessageBox.Show("Done!!!");
            }
        }
private XmlNodeList GetListItems(string strndQuery)
        {
            XmlNodeList _nodelist = null;

            string strListName = lsListCollection.SelectedItem.ToString();

            XmlDocument xmlDoc = new XmlDocument();

            XmlNode ndQuery = xmlDoc.CreateNode(XmlNodeType.Element, "Query", "");
            XmlNode ndViewFields =
                    xmlDoc.CreateNode(XmlNodeType.Element, "ViewFields", "");
            XmlNode ndQueryOptions =
                    xmlDoc.CreateNode(XmlNodeType.Element, "QueryOptions", "");

            ndQueryOptions.InnerXml =
                "<IncludeMandatoryColumns>FALSE</IncludeMandatoryColumns>" +
                "<DateInUtc>TRUE</DateInUtc>" + "<ViewAttributes Scope='Recursive'/>";

            ndQuery.InnerXml = strndQuery;
            //add view fields to fix
            ndViewFields.InnerXml =
                    "<FieldRef Name='Title' />" +
                    "<FieldRef Name='Abstract' />" +
                    "<FieldRef Name='ContentURL' />" +
                    "<FieldRef Name='LinkFilename' />" +
                    "<FieldRef Name='Last_x0020_Modified' />" +
                    "<FieldRef Name='DocIcon' />" +
                    "<FieldRef Name='DaysNew' />" +
                    "<FieldRef Name='RiskManagementLevel' />" +
                    "<FieldRef Name='File_x0020_Size' />" +
                    "<FieldRef Name='CategoryFilter_x002F_USDocumentType' />" +
                    "<FieldRef Name='ID' />" +
                    "<FieldRef Name='MediaType' />" +
                    "<FieldRef Name='EncodedAbsUrl' />" +
                    "<FieldRef Name='USPrimaryServiceLine_x002F_USPrimarySubService' />" +
                    "<FieldRef Name='USSecondaryServiceLine_x002F_USSecondarySubService' />" +
                    "<FieldRef Name='USIndustry_x002F_USSector' />" +
                    "<FieldRef Name='USServiceLine_x002F_ServiceOffering' /><FieldRef Name='ServerUrl' /><FieldRef Name='Modified' />";

            try
            {
                XmlDocument _xmlDocument = new XmlDocument();
                XmlNamespaceManager _xmlNameSpaceMngr = new XmlNamespaceManager(_xmlDocument.NameTable);

                _xmlNameSpaceMngr.AddNamespace("rs", "urn:schemas-microsoft-com:rowset");
                _xmlNameSpaceMngr.AddNamespace("z", "#RowsetSchema");

                XmlNode ndListItems = null;

                ndListItems =
                        _listService.GetListItems(strListName, null, ndQuery,
                        ndViewFields, "2500", ndQueryOptions, null);

                _nodelist = ndListItems.SelectNodes("/rs:data/z:row", _xmlNameSpaceMngr);
            }
            catch
            {

            }

            return _nodelist;
        }