Click here to Skip to main content
15,881,669 members
Articles / Programming Languages / XML
Article

Building SharePoint Web Service Dynamically and Accessing the Documents

Rate me:
Please Sign up or sign in to vote.
4.71/5 (14 votes)
25 Nov 2008CPOL4 min read 67.4K   1.1K   39   11
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.

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

C#
// 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.

C#
// 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.

C#
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.

C#
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.

C#
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.

C#
System.Net.NetworkCredential
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.

Reference:

Microsoft Forums

License

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


Written By
Chief Technology Officer at Zealots
Australia Australia
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions

 
QuestionFailed to get the list of documents and subfolder Pin
Member 99717078-Apr-13 22:44
Member 99717078-Apr-13 22:44 
QuestionGood Effort Pin
vishalMGiri1-Feb-13 4:01
vishalMGiri1-Feb-13 4:01 
Generalerror while trying to run your program Pin
abhinay.potluri16-Sep-09 4:05
abhinay.potluri16-Sep-09 4:05 
GeneralRe: error while trying to run your program Pin
ravistrs3-Mar-10 22:19
ravistrs3-Mar-10 22:19 
I too got the same error message.
Do anyone have solution please?
Ravikumar

GeneralRe: error while trying to run your program Pin
ravistrs3-Mar-10 22:38
ravistrs3-Mar-10 22:38 
GeneralDownloading and uploading documents from/to sharepoint document library entirely and from/to selected folder Pin
surabayavirus25-May-09 17:19
surabayavirus25-May-09 17:19 
QuestionWhat is the benefit? Pin
Sike Mullivan23-Dec-08 10:53
Sike Mullivan23-Dec-08 10:53 
GeneralBuilding Web service ==&gt; Building a client proxy for the web service Pin
Oskar Austegard4-Dec-08 9:10
Oskar Austegard4-Dec-08 9:10 
GeneralRe: Building Web service ==&gt; Building a client proxy for the web service Pin
vivekthangaswamy11-Dec-08 6:29
professionalvivekthangaswamy11-Dec-08 6:29 
Generalis there any ways to download the document Pin
LoveConsultant25-Nov-08 18:53
LoveConsultant25-Nov-08 18:53 
GeneralRe: is there any ways to download the document Pin
cosechador27-Feb-09 8:33
cosechador27-Feb-09 8: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.