Click here to Skip to main content
Click here to Skip to main content
Go to top

Building SharePoint Web Service Dynamically and Accessing the Documents

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

Introduction

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.

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.

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;/?:@&=+$\\.\\-_!~*'()%]+)?" +
   "(#[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============");
        System.Diagnostics.Debug.WriteLine(oops.ErrorText);
    }
    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 =
    netCredential;

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",
args);

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,
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,
                string>(xElm.GetAttribute("Title").ToString(),
                xElm.GetAttribute("ID").ToString() + "~" +
                xElm.GetAttribute("WebId").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<SharePointDataItemsInfo>
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());
        list.Add(cust1);
    }
}

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

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

"URpassword", "URdomain");

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.

Reference:

Microsoft Forums

License

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

Share

About the Author

vivekthangaswamy
Software Developer (Senior) Swordface
Australia Australia
No Biography provided

Comments and Discussions

 
GeneralBuilding Web service ==&gt; Building a client proxy for the web service PinmemberOskar Austegard4-Dec-08 9:10 
GeneralRe: Building Web service ==&gt; Building a client proxy for the web service Pinmembervivekthangaswamy11-Dec-08 6:29 

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

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

| Advertise | Privacy | Mobile
Web01 | 2.8.140926.1 | Last Updated 25 Nov 2008
Article Copyright 2008 by vivekthangaswamy
Everything else Copyright © CodeProject, 1999-2014
Terms of Service
Layout: fixed | fluid