Top Menu

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;
        }

Tuesday, December 6, 2011

Monday, October 10, 2011

SharePoint 2010 Correlation ID in Error Messages

This morning one of my colleague in another team was having problem in creating a SharePoint 2010 site with an imported Site Template. This site template was created in a different SharePoint 2010 environment. He was getting the famous SharePoint error "Error: An unexpected error has occurred." with no details but it has Correlation ID.

I was trying to explain him how to look into the logs using the Correlation ID and found this MSDN article which explain how to search the error in the SharePoint logs in detail: SharePoint 2010 Correlation ID in error messages

SharePoint 2010 Book (Update)

Hello SharePointers!

Quick Update on the SharePoint 2010 Book:
The book
Expert SharePoint 2010 Practices is slightly delayed and the new launch date is 24th October, 2011.

Thursday, September 15, 2011

SharePoint 2010 Book

Hello SharePointers!

No post since ages, I know. I actually was busy with my book on SharePoint 2010 with a team of authors...surprrrrrise :o). The title of the book is Expert SharePoint 2010 Practices and it has been published by APress.

This book is available for pre-order for now and will be finally launched on Oct 15, 2011. This book is a great source of knowledge for Architects and Developers who are keen about SharePoint 2010. Don't forget to leave the feedback.



Happy Reading.

Friday, May 6, 2011

Replacing URL in HTML using JQuery

Scenario:
Sometimes if a list is currupted, Allitems.aspx's HTML starts acting weird and we dont want to spend too much time to dig deep into the problem but want a quick fix and endup fixing the HTML. Same goes here.

Solution:
Following code change the URLs in a page to a predefined URL.
<script type="text/javascript">

 if(typeof jQuery=="undefined")
 {
  var jQsrc="http://ajax.microsoft.com/ajax/jquery/jquery-1.4.4.min.js";
  document.write(unescape("%3Cscript src='"+jQsrc+"' type='text/javascript'%3E%3C/script%3E"));
 }
</script>

<script type="text/javascript">

$(document).ready(function() {
  //find all hyperlinks in the table holding calendar links and
  //change them to point at the display page instead of the edit page
  $("table[id^='CalViewTable']").find("a[href*='OldForm.aspx']").each(function(){
  var originalUrl = $(this).attr("href");
  var newUrl = originalUrl.replace("OldForm.aspx", "NewForm.aspx");
$(this).attr("href", newUrl);
});
});

</script>
Ref: http://social.msdn.microsoft.com/Forums/en-US/sharepointcustomization/thread/ee519099-e685-4560-9c18-70e4aa62eb39

Official SharePoint Documentation

I have recently contributed to the official SharePoint documentation for developement. Check it out here: https://docs.microsoft.com/en-us...