Click here to Skip to main content
14,422,059 members

Building SharePoint Web Service Dynamically and Accessing the Documents

Rate this:
4.71 (14 votes)
Please Sign up or sign in to vote.
4.71 (14 votes)
25 Nov 2008CPOL
This article explains how to create a Windows application solution to access the document inside the SharePoint document library.


Here in this article we are going to create a Windows application solution to access the document inside the SharePoint document library. Normally to access the resources using Windows application SharePoint developers use SharePoint Object models. Here we are going to use the out of the box Web services available in SharePoint to access the documents.

SharePoint Web Services

Web services are loosely coupled, reusable software components that semantically encapsulate discrete functionality, and are distributed and programmatically accessible over standard Internet protocols. Specifically, web services are a stack of emerging standards that describe service-oriented, component-based application architecture. Conceptually, web services represent a model in which discrete tasks within e-business processes are distributed widely throughout a value net. XML Web services are the fundamental building blocks in the move to distributed computing on the Internet. Open standards and the focus on communication and collaboration among people and applications have created an environment where XML Web services are becoming the platform for application integration.

SharePoint supports interoperability and remote operations through a set of web services, WSS 3.0 (Windows SharePoint Services) and MOSS 2007 (Microsoft Office SharePoint Server) Windows SharePoint Services Web services provide methods that you can use to work remotely with a deployment of Windows SharePoint Services. There are a number of approaches for programmatic access to SharePoint, such as the object model, web services, Remote Procedure Call over HTTP, as well as Web-based Distributed Authoring and Versioning, all of which have their benefits and their place depending on what the solution requires. SharePoint web services are built on top of the SharePoint object model and expose a subset of features available in the object model, and allow for remote operations and the use of any programming language and platform that supports the consumption of web services.

The SharePoint web services are implemented in ASP.NET Web Services (ASMX), and you will find the physical files for most of these web services in the "Microsoft Shared" directory under "web server extensions\12\ISAPI" typically located at "C:\Program Files\Common Files\Microsoft Shared\web server extensions\12\ISAPI". IIS does not contain any application or virtual directories for sub webs, they do however contain mapping to the _vti_bin virtual directory through SharePoint metadata and HttpModules.

Image 1

Windows Application for SharePoint Document View

Create a Windows application in the Visual Studio and name the project as you desire. Now add a .cs file to your Windows application project and name it as WebServiceManaged.cs. Here we are going to right the concept for building the web services dynamically and getting the method access at runtime. Now design the user interface for the Windows Application.

Image 2

The user interface works like this, the site URL is to enter the SharePoint site URL. And then when click Load Site button it will manipulate the URL string and reform the Web service URL of the SharePoint site and sends these information to the Web Services call. Where the web service returns the document library names in the drop down list box and when you select the particular document library from the drop down box the corresponding document of the document library will be shown in the Data grid under the data view.

Now validate the URL entered by the user

// Regular expression to validate URL
Regex RgxUrl = new Regex(
   "(([a-zA-Z][0-9a-zA-Z+\\-\\.]*:)?/{0,2}[0-9a-zA-Z;/?:@&=+$\\.\\-_!~*'()%]+)?" +
// Check the URL and assign to the string
if (RgxUrl.IsMatch(txt_site.Text))
    strURLtxt = txt_site.Text.ToString();

// Manipulating the URL and get the site name
Uri uriO = new Uri(strURLtxt);
            string sName =
uriO.AbsoluteUri.Replace(uriO.PathAndQuery, string.Empty);

Here let’s see the process of dynamically building the SharePoint web service in our C# coding.

With the help of reflection and proxy code generation concept we are building the web services dynamically.

// Generate the proxy code
CodeDomProvider provider1 = CodeDomProvider.CreateProvider("CSharp");

// Compile the assembly proxy with the appropriate references
string[] assemblyReferences = new string[5] { "System.dll", "System.Web.Services.dll",
    "System.Web.dll", "System.Xml.dll", "System.Data.dll" };
CompilerParameters parms = new CompilerParameters(assemblyReferences);
CompilerResults results = provider1.CompileAssemblyFromDom(parms, unit1);

// Check For Errors
if (results.Errors.Count > 0)
    foreach (CompilerError oops in results.Errors)
        System.Diagnostics.Debug.WriteLine("========Compiler error============");
    throw new System.Exception(
        "Compile Error Occured calling webservice. Check Debug ouput window.");

// Finally, Invoke the web service method
object wsvcClass = results.CompiledAssembly.CreateInstance(serviceName);
MethodInfo mi = wsvcClass.GetType().GetMethod(methodName);
((System.Web.Services.Protocols.WebClientProtocol)(wsvcClass)).Credentials =

Here we call the function to build the web service dynamically and get the SharePoint resource to be displayed in the UI.

object args1 = WSprocess.CallWebService(
sName + "/_vti_bin/Lists.asmx", "Lists", "GetListCollection",

The web service returned XML data will be manipulated and populated in the drop down control.

System.Collections.Generic.List<KeyValuePair<string, string>>
ComBoData = new List<KeyValuePair<string,
foreach (System.Xml.XmlElement xElm in xDoc.DocumentElement.ChildNodes)
    if (xElm.Name.ToLower() == "list")
        // check for the document library
        if (xElm.GetAttribute("ServerTemplate").ToString() == "101")
            ComBoData.Add(new KeyValuePair<string,
                xElm.GetAttribute("ID").ToString() + "~" +

Based on the document library name selected from the drop down control the data grid will be populated with the document information correspondingly.

XmlNamespaceManager nsDocLib = new XmlNamespaceManager(xDocdetails.NameTable);
nsDocLib.AddNamespace("z", "#RowsetSchema");
XmlNodeList rows = xDocdetails.SelectNodes("//z:row", nsDocLib);
list = new List<SharePointDataItemsInfo>();
foreach (XmlNode row in rows)
    string[] strfg = row.Attributes["ows_FileRef"].Value.ToString().Split('#');
    if (row.Attributes["ows_DocIcon"].Value == "docx" ||
        row.Attributes["ows_DocIcon"].Value == "doc")
        SharePointDataItemsInfo cust1 = new SharePointDataItemsInfo(strfg[1].ToString(),
            strfg[1].ToString(), strfg[0].ToString());

Most importantly first you change the credential in the code before you run the application.

netCredential = new System.Net.NetworkCredential("URusername",

"URpassword", "URdomain");

Image 3

The Lists web service in the SharePoint are used to retrieve the list information "/_vti_bin/Lists.asmx". GetListItems is the webmethod used to fetch the List items from the list of the SharePoint. This is the output for the solution we build.

Hope this article will be helpful for SharePoint developers. Thanks for your support.


Microsoft Forums


This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


About the Author

Chief Technology Officer at Zealots
Australia Australia
No Biography provided

Comments and Discussions

QuestionFailed to get the list of documents and subfolder Pin
Member 99717078-Apr-13 23:44
MemberMember 99717078-Apr-13 23:44 
QuestionGood Effort Pin
vishalMGiri1-Feb-13 5:01
MembervishalMGiri1-Feb-13 5:01 
Generalerror while trying to run your program Pin
abhinay.potluri16-Sep-09 5:05
Memberabhinay.potluri16-Sep-09 5:05 
GeneralRe: error while trying to run your program Pin
ravistrs3-Mar-10 23:19
Memberravistrs3-Mar-10 23:19 
GeneralRe: error while trying to run your program Pin
ravistrs3-Mar-10 23:38
Memberravistrs3-Mar-10 23:38 
GeneralDownloading and uploading documents from/to sharepoint document library entirely and from/to selected folder Pin
surabayavirus25-May-09 18:19
Membersurabayavirus25-May-09 18:19 
QuestionWhat is the benefit? Pin
Sike Mullivan23-Dec-08 11:53
MemberSike Mullivan23-Dec-08 11:53 
GeneralBuilding Web service ==&gt; Building a client proxy for the web service Pin
Oskar Austegard4-Dec-08 10:10
MemberOskar Austegard4-Dec-08 10:10 
GeneralRe: Building Web service ==&gt; Building a client proxy for the web service Pin
vivekthangaswamy11-Dec-08 7:29
professionalvivekthangaswamy11-Dec-08 7:29 
Generalis there any ways to download the document Pin
LoveConsultant25-Nov-08 19:53
MemberLoveConsultant25-Nov-08 19:53 
GeneralRe: is there any ways to download the document Pin
cosechador27-Feb-09 9:33
Membercosechador27-Feb-09 9:33 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

Posted 25 Nov 2008

Tagged as


39 bookmarked