Tuesday, August 6, 2013

Show Documents from Sharepoint Document Library in ASP.Net Webpage

How to show list of files from a SharePoint document library remotely to a ASP.Net webpage via Lists.asmx webservice (SPS 2003/ MOSS 2007)


Below a sample c# code for a ASPX page, to show all the list of files from a SharePoint Document Library remotely via Lists.asmx web service. We can use the same code for both SharePoint V2 and V3. Basically the application is consuming Lists.asmx web service which is available in the /_Vti_Bin/ location of the site and we can use GetListItems() method for returning the information about document library items as XML.  
XmlNode ndListItems = objLists.GetListItems("Shared Documents"null, ndQuery, ndViewFields,null, ndQueryOptions, null);
Using XmlNodeReader we can iterate through each nodes of XML tree and can find out the absolute URL and name of each document library items. For seing the whole XML tree we can use one OuterXml Property of the XmlNode (ndListItems.OuterXml), It will show the all nodes and its childs.
objReader ["ows_EncodedAbsUrl"will give the URL and objReader ["ows_LinkFilename"will give the name of the document library item. 

You can download that item to our local machine by using HttpWebRequest HttpWebResponse classes. We will get the response steam by using the method GetResponseStream(), from this stream we can read the content to a byte array and we can write those byte stream to a physical file location using a FileStream Class. 

CODE SNIPPET :

using System;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Data;
using System.Net;
using System.Collections.Generic;
using System.Xml;
 
 
namespace SharepointNavigation
{
    public partial class SpDocs : System.Web.UI.Page
    {
 
        protected void Page_Load(object sender, EventArgs e)
        {
            BindDocList();
        }
 
        private void BindDocList()
        {
            Dictionary<stringstring> fileCollection = GetDocList();
 
            dlScoreCards.DataSource = fileCollection;
            dlScoreCards.DataBind();
        }
 
        private Dictionary<stringstring> GetDocList()
        { 
            Dictionary<stringstring> fileList = new Dictionary<string,string>();
            XmlDocument resdoc = new System.Xml.XmlDocument();
            XmlNode resnode = null;
            string strURL = "";
            string strFileName = "";
 
            try
            {
                com.jnj.teamsna4.Lists objLists = new com.jnj.teamsna4.Lists();
                objLists.UseDefaultCredentials = true;
                objLists.Url = "http://[sharepoint site url]/_vti_bin/Lists.asmx"// change the URL to your sharepoint site
                XmlDocument xmlDoc = new System.Xml.XmlDocument();
                XmlNode ndQuery = xmlDoc.CreateNode(XmlNodeType.Element, "Query""");
                XmlNode ndViewFields = xmlDoc.CreateNode(XmlNodeType.Element, "ViewFields""");
                XmlNode ndQueryOptions = xmlDoc.CreateNode(XmlNodeType.Element, "QueryOptions""");
                ndQueryOptions.InnerXml = "<Folder>Shared Documents/Do it Right (Jacksonville)/DIR Best Practice Scorecards Current</Folder>";
                //ndQueryOptions.InnerXml = "<Folder>Shared Documents/VC Strategy</Folder>";
                //ndQueryOptions.InnerXml = "<IncludeAttachmentUrls>TRUE</IncludeAttachmentUrls><ViewAttributes Scope=\"RecursiveAll\"/><DateInUtc>TRUE</DateInUtc>";
                ndViewFields.InnerXml = "";
                ndQuery.InnerXml = "";
 
                try
                {
                    XmlNode ndListItems = objLists.GetListItems("Shared Documents"null, ndQuery, ndViewFields, null, ndQueryOptions, null); // you can change the document library name to your custom document library name
                    XmlNodeList oNodes = ndListItems.ChildNodes;
                    foreach (XmlNode node in oNodes)
                    {
                        XmlNodeReader objReader = new XmlNodeReader(node);
                        while (objReader.Read())
                        {
                            if (objReader["ows_EncodedAbsUrl"] != null && objReader["ows_LinkFilename"] != null)
                            {
                                strURL = objReader["ows_EncodedAbsUrl"].ToString();
                                strFileName = objReader["ows_LinkFilename"].ToString();
                                if (strFileName.LastIndexOf(".") > 0)
                                {
                                    //Add the document link to dictionary
                                    fileList.Add(strFileName, strURL);
                                }
                            }
                        }
                    }
                    
                }
                catch (System.Web.Services.Protocols.SoapException ex)
                {
                    lblMessage.Text = "Message: " + ex.Message + "<br />Detail: " + ex.Detail.InnerText + "<br />StackTrace: " + ex.StackTrace;
                    
                }
            }
            catch (Exception ex)
            {
                lblMessage.Text = ex.Message;
            }
           
            return fileList;
        }
    }
}

ASPX Page Snippet :

<asp:DataList ID="dlScoreCards" runat="server" CellPadding="4" 
    ForeColor="#333333">
        <AlternatingItemStyle BackColor="White" ForeColor="#284775" />
        <FooterStyle BackColor="#5D7B9D" Font-Bold="True" ForeColor="White" />
        <HeaderStyle BackColor="#5D7B9D" Font-Bold="True" ForeColor="White" />
    <HeaderTemplate>
        Score Cards
    </HeaderTemplate>
        <ItemStyle BackColor="#F7F6F3" ForeColor="#333333" />
    <ItemTemplate>
        <a href='<%# Eval("value")%>' title='Click to download <%# Eval("key")%>' target="_blank"><%# Eval("key")%></a>
    </ItemTemplate>
        <SelectedItemStyle BackColor="#E2DED6" Font-Bold="True" ForeColor="#333333" />
    </asp:DataList>


Web.Config :

<?xml version="1.0"?>
 
<!--
  For more information on how to configure your ASP.NET application, please visit
  http://go.microsoft.com/fwlink/?LinkId=169433
  -->
 
<configuration>
  <configSections>
    <sectionGroup name="applicationSettings" type="System.Configuration.ApplicationSettingsGroup, System, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" >
      <section name="SharepointNavigation.Properties.Settings" type="System.Configuration.ClientSettingsSection, System, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" requirePermission="false" />
    </sectionGroup>
  </configSections>
  <connectionStrings>
    <add name="ApplicationServices"
         connectionString="data source=.\SQLEXPRESS;Integrated Security=SSPI;AttachDBFilename=|DataDirectory|\aspnetdb.mdf;User Instance=true"
         providerName="System.Data.SqlClient" />
  </connectionStrings>
 
  <system.web>
    <compilation debug="true" targetFramework="4.0" />
 
    <authentication mode="Windows"></authentication>
    <!--<authentication mode="Forms">
      <forms loginUrl="http://localhost/TestWeb/Account/Login.aspx" timeout="2880" />
    </authentication>-->
    <identity impersonate="true" />
    <authorization>
      <deny users="?"/>
      <allow users="*"/>
    </authorization>
 
    <membership>
      <providers>
        <clear/>
        <add name="AspNetSqlMembershipProvider" type="System.Web.Security.SqlMembershipProvider" connectionStringName="ApplicationServices"
             enablePasswordRetrieval="false" enablePasswordReset="true" requiresQuestionAndAnswer="false" requiresUniqueEmail="false"
             maxInvalidPasswordAttempts="5" minRequiredPasswordLength="6" minRequiredNonalphanumericCharacters="0" passwordAttemptWindow="10"
             applicationName="/" />
      </providers>
    </membership>
 
    <profile>
      <providers>
        <clear/>
        <add name="AspNetSqlProfileProvider" type="System.Web.Profile.SqlProfileProvider" connectionStringName="ApplicationServices" applicationName="/"/>
      </providers>
    </profile>
 
    <roleManager enabled="false">
      <providers>
        <clear/>
        <add name="AspNetSqlRoleProvider" type="System.Web.Security.SqlRoleProvider" connectionStringName="ApplicationServices" applicationName="/" />
        <add name="AspNetWindowsTokenRoleProvider" type="System.Web.Security.WindowsTokenRoleProvider" applicationName="/" />
      </providers>
    </roleManager>
 
  </system.web>
 
  <system.webServer>
     <modules runAllManagedModulesForAllRequests="true"/>
  </system.webServer>
  <system.serviceModel>
    <bindings />
    <client />
  </system.serviceModel>
  <applicationSettings>
    <SharepointNavigation.Properties.Settings>
      <setting name="SharepointNavigation_Lists" serializeAs="String">
        <value>http://[SharePoint site Url]/_vti_bin/Lists.asmx</value>
      </setting>
    </SharepointNavigation.Properties.Settings>
  </applicationSettings>
</configuration>