Monday, December 3, 2012

Backup and Restore SharePoint Site

Site Collection Backup and Restore

Backup: 
stsadm -o backup -url http://site1.com/sitecoll1 -filename c:\backup\backup1.dat
Restore: 
stsadm -o restore -url http://site2.com/sitecoll1 -filename c:\backup\backup1.dat -overwrite


Export and import a subsite, list, or library

Export:
stsadm -o export –url http://site1.com/sites/portal/Shared%20documents –filename c:\backup\lib.bak -quiet -overwrite 
Import:
stsadm -o import –url http://site2.com/sites/portal/Shared%20documents –filename c:\backup\lib.bak -quiet


Wednesday, September 19, 2012

JQuery: Batch update the list items via Lists.asmx

Quick JQuery script to batch update the list items via Lists.asmx.

I have two lists Projects(Title, ProjectStatus) and Teams(Title, Project, ProjectStatus). Team.Project is a lookup column from Projects.Title and I want to update Teams.ProjectStatus when Projects.ProjectStatus is updated in the Projects list via EditForm.aspx. Now we can link two columns from projects list into the Teams list but can not connect them together in the Teams list, so following script was a great help. It batch updates the Teams.ProjectStatus once Project.ProjectStatus is updated.

Thanks to the this post I found 100% functionality ready to go.


<script type="text/javascript" src="/Scripts/jquery-1.8.1.min.js"></script>

<script type="text/javascript">

var strProject = "";
var strProjectStatus = "";

function PreSaveItem()
{
 strProject = document.getElementById('ctl00_m_g_f2d95e24_befb_49d2_b15f_823d71c9c758_ctl00_ctl04_ctl00_ctl00_ctl00_ctl04_ctl00_ctl00_TextField').value;
 strProjectStatus = document.getElementById('ctl00_m_g_f2d95e24_befb_49d2_b15f_823d71c9c758_ctl00_ctl04_ctl01_ctl00_ctl00_ctl04_ctl00_DropDownChoice').value;
 
 GetProjectID();
  
 return true;
}

function GetProjectID(){

var soapEnv = "<soap:Envelope xmlns:soap='http://schemas.xmlsoap.org/soap/envelope/'> \
<soap:Body> \
    <GetListItems xmlns='http://schemas.microsoft.com/sharepoint/soap/'> \
        <listName>Teams</listName> \
        <query><Query><Where><Eq><FieldRef Name='Project'/><Value Type='Text'>"+ strProject +"</Value> </Eq></Where></Query></query> \
        <viewFields> \
            <ViewFields> \
                <FieldRef Name='ID' /> \
                <FieldRef Name='Title' /> \
            </ViewFields> \
        </viewFields> \
        <rowLimit>99999</rowLimit> \
        <queryOptions xmlns:SOAPSDK9='http://schemas.microsoft.com/sharepoint/soap/' ><QueryOptions/> \
        </queryOptions> \
    </GetListItems> \
</soap:Body> \
</soap:Envelope>";

jQuery.ajax({
url: "/itsglobal/_vti_bin/lists.asmx",
type: "POST",
dataType: "xml",
data: soapEnv,
complete: ResultMethod,
contentType: "text/xml; charset=\"utf-8\""
});

}

function ResultMethod(xData, status) 
{

    if (status=="success")
    {
        var oldbatch = "";
        $(xData.responseXML).find("z\\:row").each(function() 
        {
            oldbatch = AddTobatch(oldbatch, $(this).attr("ows_ID"));
        });
        
        UpdateTeamItem(oldbatch);
    }

}

function AddTobatch(oldbatch, itemId)
{

//Specify the batch query
var _batch = "<Method ID='1' Cmd='Update'><Field Name='ID'>" + itemId +"</Field><Field Name='ProjectStatus'>"+ strProjectStatus +"</Field></Method>";
oldbatch = oldbatch + _batch;

return oldbatch;
}

function UpdateTeamItem(batch) 
{
var soapEnv = "<?xml version=\'1.0\' encoding=\'utf-8\'?> \
<soap:Envelope xmlns:xsi=\'http://www.w3.org/2001/XMLSchema-instance\' \
xmlns:xsd=\'http://www.w3.org/2001/XMLSchema\' \
xmlns:soap='http://schemas.xmlsoap.org/soap/envelope/\'> \
<soap:Body> \
<UpdateListItems xmlns='http://schemas.microsoft.com/sharepoint/soap/'> \
<listName>Teams</listName> \
<updates> \
<Batch OnError='Continue'>" + batch + "</Batch> \
</updates> \
</UpdateListItems> \
</soap:Body> \
</soap:Envelope>";

$.ajax({
url: "/itsglobal/_vti_bin/lists.asmx",
beforeSend: function(xhr) { xhr.setRequestHeader("SOAPAction", "http://schemas.microsoft.com/sharepoint/soap/UpdateListItems");
},
type: "POST",
dataType: "xml",
data: soapEnv,
complete: updateResult,
contentType: "text/xml; charset=\"utf-8\""

});
}

function updateResult(xData, status) {
if (status != 'success' )
    alert("Update Project Status in Teams library failed");
}


</script>

JQuery: Read list Item via Lists.asmx

Following JQuery script is to get list items using Lists.asmx web service in MOSS 2007:
<script type="text/javascript" src="/Scripts/jquery-1.8.1.min.js"></script>
<script type="text/javascript">

//This function will call when OK button will be pressed on a List's default form (e.g. EditItem.aspx).

function PreSaveItem()
{
 var project = "Project A";
 
 GetProjectID(project);
 
 return true;
}

function GetProjectID(project){

var soapEnv = "<soap:Envelope xmlns:soap='http://schemas.xmlsoap.org/soap/envelope/'> \
<soap:Body> \
    <GetListItems xmlns='http://schemas.microsoft.com/sharepoint/soap/'> \
        <listName>Teams</listName> \
        <query><Query><Where><Eq><FieldRef Name='Project'/><Value Type='Text'>"+ project +"</Value> </Eq></Where></Query></query> \
        <viewFields> \
            <ViewFields> \
                <FieldRef Name='ID' /> \
                <FieldRef Name='Title' /> \
            </ViewFields> \
        </viewFields> \
        <rowLimit>99999</rowLimit> \
        <queryOptions xmlns:SOAPSDK9='http://schemas.microsoft.com/sharepoint/soap/' ><QueryOptions/> \
        </queryOptions> \
    </GetListItems> \
</soap:Body> \
</soap:Envelope>";

jQuery.ajax({
url: "/itsglobal/_vti_bin/lists.asmx",
type: "POST",
dataType: "xml",
data: soapEnv,
complete: ResultMethod,
contentType: "text/xml; charset=\"utf-8\""
});

}

function ResultMethod(xData, status) 
{

    if (status=="success")
    {
        alert(status);
        $(xData.responseXML).find("z\\:row").each(function() 
        {
            alert($(this).attr("ows_ID"));
        });
    }

}

</script>
I have copied this script from the internet and have tweaked it a bit to work with JQuery 1.8 version.

Tuesday, August 28, 2012

SharePoint 2007 - Save RSS Feed into List using JQuery

The idea is to fetch the RSS feed from multiple sources and then save into the SharePoint 2007 List so that we can perform search, archive the RSS news, display data nicely in Data View etc etc.



The following JQuery script will fetch the RSS feed from multiple sources and then save the data into the SharePoint 2007 list via lists.asmx:
<script src="/Scripts/jquery-1.8.0.min.js" type="text/javascript"></script>


<script type="text/javascript">
  
    function LoadFeed() 
    {
        var varFeedURL = new Array();
            varFeedURL[0] = "http://feeds.bbci.co.uk/news/business/rss.xml";
            varFeedURL[1] = "http://www.ft.com/rss/home/uk";
            varFeedURL[2] = "http://www.ft.com/rss/home/us";

            for (i = 0; i < varFeedURL.length; i++)
            {

                $.get(varFeedURL[i], function(data) {
                    var $xml = $(data);
                    $xml.find("item").each(function() {
                        var $this = $(this),
                            item = {
                                title: $this.find("title").text(),
                                link: $this.find("link").text(),
                                description: $this.find("description").text(),
                                pubDate: $this.find("pubDate").text()
                        }
                        
                        
                        //Show only Today's Items
                        var a = new Date(item.pubDate);
                        var b = new Date(); //Today's Date
                        
                        var msDateA = Date.UTC(a.getFullYear(), a.getMonth()+1, a.getDate());
                           var msDateB = Date.UTC(b.getFullYear(), b.getMonth()+1, b.getDate());
                                                   
                        if (parseFloat(msDateA) == parseFloat(msDateB))
                        {
                        
                            var content = document.getElementById('content');
                            content.appendChild(document.createTextNode(item.title)); 
                            content.appendChild(document.createElement('br'));
                            content.appendChild(document.createTextNode(item.description));
                            content.appendChild(document.createElement('br'));
                            content.appendChild(document.createTextNode(item.link));
                            content.appendChild(document.createElement('br'));
                            content.appendChild(document.createElement('hr'));
                            
                            CreateNewItem(item.title, item.description, item.link);
                        }
                        
                    });
                });
            }
        alert('Done');
    }        
        
        
        function CreateNewItem(varTitle, varDescription, varLink) 
        {
                    var batch =
                        "<Batch OnError=\"Continue\"> \
                            <Method ID=\"1\" Cmd=\"New\"> \
                                <Field Name=\"Title\">" + varTitle + "</Field> \
                                <Field Name=\"Description\">" + varDescription + "</Field> \
                                <Field Name=\"Link\">" + varLink + "</Field> \
                            </Method> \
                        </Batch>";
                
                    var soapEnv =
                        "<?xml version=\"1.0\" encoding=\"utf-8\"?> \
                        <soap:Envelope xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" \
                            xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" \
                            xmlns:soap=\"http://schemas.xmlsoap.org/soap/envelope/\"> \
                          <soap:Body> \
                            <UpdateListItems xmlns=\"http://schemas.microsoft.com/sharepoint/soap/\"> \
                              <listName>RSSData</listName> \
                              <updates> \
                                " + batch + "</updates> \
                            </UpdateListItems> \
                          </soap:Body> \
                        </soap:Envelope>";
                
                    $.ajax({
                        url: "http://portalstg.amr.kworld.kpmg.com/_vti_bin/lists.asmx",
                        beforeSend: function(xhr) {
                            xhr.setRequestHeader("SOAPAction",
                            "http://schemas.microsoft.com/sharepoint/soap/UpdateListItems");
                        },
                        type: "POST",
                        dataType: "xml",
                        data: soapEnv,
                        complete: processResult,
                        contentType: "text/xml; charset=utf-8"
                    });
                }
                
                function processResult(xData, status) {
                    //alert(status);
                }
        
  
    </script>

<input id="btnGo" onclick="LoadFeed()" type="button" value="Get RSS Data" />


Ref: http://weblogs.asp.net/jan/archive/2009/04/10/creating-list-items-with-jquery-and-the-sharepoint-web-services.aspx


Thursday, August 9, 2012

SharePoint 2013 - Facebook style Discussion with Like Button

This post has also been published at NothingButSharePoint.

The famous Facebook Like is one of the features that everybody want these days so that they can like/unlike everything they can read and see over the internet. I was exploring SharePoint 2013 Technical Preview's new features and how to use them in real world scenarios when I came across the amazing new Discussion Board list and its configuration settings so that users can like/unlike a discussion, comment and a reply. 

First I am going to show the new features (displayed in the image below) and then I will show you how to configure the like/unlike button (in the video below). 

New Discussion Board list has following cool features:
  1. Display Picture - Now users can see the person who has started the discussion and who is replying. 
  2. Rich text - Users can reply with rich text to highlight the important parts of the conversation in their comments. 
  3. Reply to Reply - Users can now reply to an existing reply just like the discussion topic. 
  4. Multimedia Reply - Users can attach picture, video or a simple link with in their reply to provide a reference etc. 
  5. Like a reply - Users can rate a post by liking it.
  6. Best Reply - A reply can be marked as Best reply in order to avoid other users to dig for an answer in the thread.
Following video shows how to configure the Discussion Board list for Facebook style Like Button on posts:


Tuesday, July 17, 2012

SharePoint 2013 is here

Yup...SharePoint 2013 Technical Preview has launched today. Woohoo.

Here is the documentation for SharePoint developers:
http://msdn.microsoft.com/en-us/library/jj162979(office.15).aspx



SharePoint 2010 - Join Two Lists (Child Parent Relation)

This article has also been published at NothingButSharePoint.

Description: This tutorial explains how to join two lists based on child parent relation without writing any code.

This post explains how to implement the child parent relationship between two lists/tables. Two lists will have one common field ID from Category list. Category.ID will act as primary key in Category list and will be used in Products list as a foreign key to match the items. Below diagram illustrate the relationship that has been implemented in the video.
Child Parent Relation



This technique can also be used in SharePoint 2007 via SharePoint Designer 2007 as explained in one of my previous posts. However the Data Source and Data View web part's menu options are little different.

Thursday, July 12, 2012

SharePoint 2010 - Implementing Search in a List (No Code)

This article has also been published at the NothingButSharePoint.

Description: This tutorial explains how to implement search functionality in a list without any code.

I recently had a requirement of implementing a search page for a List where user pass a search phrase via Query String (e.g. http://SharePoint2010:1000/Pages/Search.aspx?q=hello) and the search page will display the results from a List, based on that search phrase. I am excited to share the technique where one don't have to write a code to develop such page and everything can be taken care of easily via SharePoint Designer.



This technique can also be used in SharePoint 2007 via SharePoint Designer 2007. However the Data View web part's options are available on Data View context menu instead of the tool bar.



Here is the Page's code with text field and button to pass the search string to the Search.aspx page.
<script type="text/javascript">
function Redirect()
{
    window.location = "http://SharePoint2010:1000/Pages/Search.aspx?q=" + document.getElementById('Text1').value;
}
</script>

<input name="Text1" type="text">
<button name="Abutton1" onclick="Redirect();">button</button>

Monday, June 25, 2012

SharePoint 2010 (Foundation) Out-of-Box Web Parts

List of all the SharePoint 2010 Foundation Edition out-of-box web parts:

List and Libraries
   Announcements
   Calendar
   Links
   Pictures
   Shared Documents
   Site Assets
   Site Pages
   Tasks
   Team Discussions

Content Rollup      
   Relevant Documents
   XML Viewer

Forms
   HTML Form Web Part


Media and Content      
   Content Editor
   Image Viewer
   Page Viewer
   Picture Library Slideshow Web Part
   SilverLight Web Part

Social Collaboration
   Site Users
   User Tasks

SharePoint 2010 (Enterprise) Out-of-Box Web Parts

List of all the SharePoint 2010 Enterprise Edition web parts

List and Libraries:

   Announcements – Use this list to track upcoming events, status updates or other team news
   Calendar – Use the Calendar list to keep informed of upcoming meetings, deadlines, and other important events
   Links - Use the Links list for links to Web pages that your team members will find interesting or useful
   Shared Documents – Share a document with the team by adding it to this document library
   Site Assets – Use this library to store files which are included on pages within this site, such as images on Wiki pages
   Site Pages – Use this library to create and store pages on this site
   Tasks – Use the Tasks list to keep track of work that you or your team needs to complete
   Team Discussions – Use the Team Discussion list to hold newsgroup-style discussions on topics relevant to your team


Business Data:
   Business Data Actions – Displays a list of actions from Business Data Connectivity
   Business Data Connectivity Filter – Filters the contents of Web Parts using a list of values from the Business Data Connectivity
   Business Data Item – Displays one item from a data source in Business Data Connectivity
   Business Data Item Builder – Creates a Business Data item from parameters in the query string and provides it to other Web Parts
   Business Data List – Displays a list of items from a data source in Business Data Connectivity
   Business Data Related List – Displays a list of items related to one or more parent items from a data source in Business Data Connectivity
   Chart Web Part – Helps you to visualize your data on SharePoint sites and portals
   Excel Web Access – Use the Excel Web Access Web Part to interact with an Excel workbook as a Web page
   Indicator Details – Displays the details of a single Status Indicator. Status Indicators display an important measure for an organization and may be obtained from other data sources including SharePoint lists, Excel workbooks, and SQL Server 2005 Analysis Services KPIs.
   Status Lists – Shows a list of Status Indicators. Status Indicators display important measures for your organization, and show how your organization is performing with respect to your goals.
   Visio Web Access – Enables viewing and refreshing of Visio Web Drawings


Content Rollup:
   Categories – Displays categories from the Site Directory
   Content Query – Displays a dynamic view of content from your site
   Relevant Documents – Displays documents that are relevant to the current user
   RSS Viewer – Displays an RSS feed
   Site Aggregator – Displays sites of your choice.
   Sites In Category – Displays sites from the Site Directory within a specific category
   Summary Links – Allows authors to create links that can be grouped and styled
   Table Of Contents – Displays the navigation hierarchy of your site
   Web Analytics web Part – Displays the most viewed content, most frequent search queries from a site, or most frequent search queries from a search center
   WSRP Viewer – Displays portlets from web sites using WSRP 1.1
   XML Viewer – Transforms XML data using XSL and shows the results


Filters:
   Choice Filter – Filters the contents of Web Parts using a list of values entered by the page author
   Current User Filter – Filters the contents of Web Parts by using properties of the current user
   Date Filter – Filter the contents of Web Parts by allowing users to enter or pick a date
   Filter Actions – Use the Filter Actions Web Part when you have two or more filter Web Parts on one     Web Part Page, and you want to synchronize the display of the filter results
   Page Field Filter – Filters the contents of Web Parts using information about the current page
   Query String (URL) Filter – Filters the contents of Web Parts using values passed via the query string
   SharePoint List Filter - Filters the contents of Web Parts by using a list of values
   SQL Server Analysis Services Filter – Filters the contents of Web Parts using a list of values from SQL Server Analysis Services cubes
   Text Filter – Filters the contents of Web Parts by allowing users to enter a text value


Forms:
   HTML Form Web Part – Connects simple form controls to other Web Parts
   InfoPath Form Web Part – Use this Web Part to display an InfoPath browser-enabled form


Media and Content:
   Content Editor – Allows authors to enter rich text content
   Image Viewer – Displays a specified image
   Media Web Part – Use to embed media clips (video and audio) in a web page
   Page Viewer - Displays another Web page on this Web page. The other Web page is presented in an IFrame
   Picture Library Slideshow Web Part – Use to display a slideshow of images and photos from a picture library
   Silverlight Web part – A web part to display a Silverlight application


Outlook Web App:
   My Calendar – Displays your calendar using Outlook Web Access for Microsoft Exchange Server 2003 or later
   My Contacts – Displays your contacts using Outlook Web Access for Microsoft Exchange Server 2003 or later
   My Inbox – Displays your inbox using Outlook Web Access for Microsoft Exchange Server 2003 or later
   My Mail Folder – Displays your mail folder using Outlook Web Access for Microsoft Exchange Server 2000
   My Tasks – Displays your tasks using Outlook Web Access for Microsoft Exchange Server 2003 or later

PerformancePoint:
   PerformancePoint Filter – This web part displays PerformancePoint filters. Filters may be linked to other web parts to provide an interactive dashboard experience. Filter types include lists and trees based on a variety of data sources
   PerformancePoint Report – This web part displays PerformancePoint reports. Reports may be linked to other web parts to create an interactive dashboard experience. Report types include: Analytic charts & grids, Strategy Maps, Excel Services, Reporting Services, Predictive Trend charts, and web pages
   PerformancePoint Scorecard – This web part displays a PerformancePoint scorecard. Scorecards may be linked to other web parts, such as filters and reports, to create an interactive dashboard experience.
   PerformancePoint Stack Selector – This web part displays a PerformancePoint Stack Selector. All PerformancePoint web parts, such as filters and reports, contained in the same zone will be automatically stacked and selectable using this web part.


Search:
   Advanced Search Box – Displays parameterized search options based on properties and combinations of words.
   Dual Chinese Search – Used to search Dual Chinese document and items at the same time.
   Federated Results – Displays search results from a configured location
   People Refinement Panel – This webpart helps the users to refine people search results
   People Search Box – Presents a search box that allows users to search for people
   People Search Core Results – Displays the people search results and the properties associated with them.
   Refinement Panel – This webpart helps the users to refine search results
   Related Queries – This webpart displays related queries to a user query
   Search Action Link – Displays the search action links on the search results page
   Search Best Bet – Displays high-confidence results on a search results page.
   Search Box – Displays a search box that allows users to search for information.
   Search Core Results – Displays the search results and the properties associated with them
   Search Paging – Display links for navigating pages containing search results.
   Search Statistics – Displays the search statistics such as the number of results shown on the current page, total number of results and time taken to perform the search.
   Search Summary – Displays suggestions for current search query
   Search Visual Best Bet – Displays Visual Best Bet
   Top Federated Results – Displays the Top Federated result from the configured location


Social Collaboration:
   Contact Details – Displays details about a contact for this page or site.
   Note Board – Enable users to leave short, publicly-viewable notes about this page.
   Organization Browser – This Web Part displays each person in the reporting chain in an interactive view optimized for browsing organization charts.
   Site Users – Use the Site Users Web Part to see a list of the site users and their online status.
   Tag Cloud – Displays the most popular subjects being tagged inside your organization
   User Tasks – Displays tasks that are assigned to the current user.
   What’s New – This Web part shows new information from specified lists and libraries
   Whereabouts – Use to display Whereabouts information.



Thursday, June 7, 2012

SharePoint 2010 Capacity

I was looking for the limitations for SharePoint 2010 while doing the capacity planning and came across the following article on MSDN which explains the boundaries of SharePoint's 2010 version: SharePoint 2010 Limits

Monday, April 2, 2012

Migrating SharePoint 2007 site to SharePoint 2010

Recently, I had to come up with a strategy to migrate our company's internal SharePoint based website from MOSS 2007 to SharePoint 2010 platform and the following MSDN article made my life so much easy:

URL: http://technet.microsoft.com/hi-in/library/cc263299(en-us).aspx

There were no custom developed components however there were many major customizations in different sections of the site collection, so we planned to followed the below steps:

  1. Prepare the new SharePoint 2010 Farm/Server.
  2. Detach the Content Database from the SharePoint 2007 web application.
  3. Move the Content Database to the new SQL Server.
  4. Create a new Web Application in SharePoint 2010.
  5. Attach the Content Database to the new Web Application.
  6. Verify data and functionality.
  7. Some customizations might/will stop working so you need to fix them or in some cases re-do them.
In short I have to follow the same strategy which I have used for migrating the site from SharePoint 2003 to SharePoint 2007.

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

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

Official SharePoint Documentation

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