Click here to Skip to main content
Click here to Skip to main content

Pushing data into a SharePoint server

By , 25 Jan 2004
 

Introduction

Windows 2003 comes standard with something called Windows SharePoint™ Services, found here. This provides some pretty impressive Intranet functionality right out of the box (well, with one additional download).

Once set up, it provides a database driven website with content that is controlled by the users. Users can add various types of content, using predesigned "web parts", which are basically ASP.NET web controls. In addition, it provides a Web Service API which developers can use to push data right onto the website.

This article shows how to implement a simple user feedback web form, with results that display on an intranet site. We'll use part of the API to do that. (Development of custom "web parts" is also worthy of an article, but I'll leave that to someone else).

Preparation

Before you can use the sample code, you need to have a Windows 2003 server set up with SharePoint Services. You can find the download at the URL mentioned previously. Once installed, you will need to create a website, using the provided admin tools. On the website, you will need to set up a "List", which will contain the feedback in a format that the intranet users will like. You can and should customize the fields of your list, as follows:

  • Name (rename title)
  • Comment (rename description)
  • Email address (new field)

I won't go into how to set up SharePoint Services. If you have problems, post a question below, and I will answer as best I can.

Using the code

First, we create a simple ASP.NET form, containing fields for Name, Comment and Email address. Add validation controls if you need. Add a web reference to the Lists web service, found at http://YourSharepointServerName/_vti_bin/Lists.asmx.

The web service provides an UpdateListItems method, which takes some XML as a parameter. The XML is of a format:

<Batch><Method><Field>FieldValue</Field></Method></Batch>

Error handling is primitive, so you should be sure to use the correct case for everything (XML is case-sensitive), and the correct names for all of your fields.

The following snippet of code can be added behind your form's submit button:

private void btnSubmit_Click(object sender, System.EventArgs e)
{
    Lists listService = new Lists();
    listService.Credentials = GetCredentials();
    //we need to login as a user of sharepoint

    Page.Validate();    //force the validation, for non-IE browsers
    if (Page.IsValid)
    {
        XmlDocument doc = new XmlDocument();
        XmlElement updates = doc.CreateElement("Batch");
    
        updates.InnerXml = string.Format(
            "<Method id=1 Cmd="New">" +
            "<Field Name='ID'>New</Field>" +
            "<Field Name='Title'>{0}</Field>" +
            "<Field Name='Body'>{1}</Field>" +
            "<Field Name='Email'>{2}</Field>" +
            "</Method>", 
            txtName.Text, 
            txtComment.Text, 
            txtEmail.Text);

        XmlNode node = null;
        try
        {
            node = listService.UpdateListItems(
             System.Configuration.ConfigurationSettings.AppSettings["listName"], 
             updates);

            //TODO: Really, we should parse the returned 
            //XmlNode object to check for success code.
            Response.Redirect("thanks.aspx");
        } 
        catch (WebException err)
        {
            if (err.Message.StartsWith("The underlying connection was closed"))
                lblError.Text = "The feedback service is currently" +
                                " unavailable.  Please try again later";
            else
                lblError.Text = err.Message;
        }
        catch (Exception err)
        {
            lblError.Text = err.Message;
        }
    } 
    else
    {
        //do nothing.  The validation controls 
        //will kick in on the postback.
    }
}

Notice that, when setting updates.innerXML, we specify the original list field names for those that we renamed. SharePoint remembers the original name separately. You can see the actual field name when editing the field in SharePoint, as part of the URL (something like &Field=Title near the end).

For this code to work, you need to add an appsetting for listName to your web.config file. The setting should contain the name that you gave to your particular list.

The SharePoint Lists Web Service requires that you authenticate. You can do this using a Windows username and password that has access to the SharePoint website. I stored these credentials inside of the web.config file, and then created the following code to return the credentials:

private NetworkCredential GetCredentials()
{
    try
    {
        return new NetworkCredential(
            System.Configuration.ConfigurationSettings.AppSettings["userName"], 
            System.Configuration.ConfigurationSettings.AppSettings["password"], 
            System.Configuration.ConfigurationSettings.AppSettings["domain"]);
    } 
    catch (Exception err)
    {
        throw new ApplicationException(
            "Service failed to login to the network.", 
            err);
    }
}

And that's about all there is to it. I hope this article helps in getting started with SharePoint services.

Points of Interest

When using the sample code, be sure to edit the web.config file first, to contain appropriate settings for your environment.

License

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

About the Author

Steven Campbell
Web Developer
United States United States
Member
Steve is a software developer working in Minneapolis, MN.

Sign Up to vote   Poor Excellent
Add a reason or comment to your vote: x
Votes of 3 or less require a comment

Comments and Discussions

 
Hint: For improved responsiveness ensure Javascript is enabled and choose 'Normal' from the Layout dropdown and hit 'Update'.
You must Sign In to use this message board.
Search this forum  
    Spacing  Noise  Layout  Per page   
QuestionI cannot see the items in the list of SharePointmembermixons2 Dec '09 - 8:01 
GeneralGood Postmemberbanchana6 Feb '09 - 17:11 
QuestionHow to add a HyperLink/PicturememberJorge Da Silva23 May '07 - 6:02 
GeneralI cannot find Lists.asmx urlmemberC.R.Parameshwaran30 Apr '07 - 12:01 
GeneralRe: I cannot find Lists.asmx urlmemberbanchana6 Feb '09 - 17:06 
GeneralUnauthorized errormemberjeremy_dbrown6 Jul '06 - 0:16 
GeneralRe: Unauthorized errormemberTechzorcism11 Aug '06 - 6:06 
GeneralCute kid.memberKen Hadden28 May '06 - 19:36 
GeneralView GUIDmemberarash_6 Feb '06 - 23:24 
GeneralError - List does not existmembernzdunic14 Sep '05 - 22:54 
I get this error when running my code through UpdateListItems
 
List does not exist The page you selected contains a list that does not exist. It may have been deleted by another user. Click "Home" at the top of the page to return to your Web site. 0x82000006
 
This is the call: node = listService.UpdateListItems("Training Bookings", updates);
 
This is the XML:
 
XmlDocument doc = new XmlDocument();
XmlElement updates = doc.CreateElement("Batch");

updates.InnerXml = string.Format("" +
"{0}" +
"{1}" +
"{2}" +
"{3}" +
"{4}" +
"{5}" +
"{6} {7:00}::{8:00}" +
"{9}" +
"{10}" +
"{11}" +
"{12}" +
"{13}" +
"
",
txtCourseCode.Text,
txtFirstName.Text,
cboFranchise.SelectedValue,
txtEmailAddress.Text,
txtLastName.Text,
"Free",
txtCourseDate.Text,
cboHours.SelectedValue,
cboMinutes.SelectedValue,
txtCourseVenue.Text, "Test", "Pass",
"Requested", "Optional");
 
Everything else is the same.
 
Any ideas why I'm getting this error?
 

Questionlogging information on Lists.asmx file on SharePointmemberVandanap2 Sep '05 - 8:28 
GeneralDoubt in SharePoint Portal Server 2003memberMounikab20 May '05 - 1:27 
GeneralRe: Doubt in SharePoint Portal Server 2003memberSteven Campbell20 May '05 - 1:55 
Generalre: How to post form and edit web service parameterssussossentoo8 Jun '04 - 7:12 
GeneralRe: re: How to post form and edit web service parameterssussossentoo9 Jun '04 - 19:56 
GeneralRe: re: How to post form and edit web service parameterssussossentoo10 Jun '04 - 3:33 

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

Permalink | Advertise | Privacy | Mobile
Web04 | 2.6.130516.1 | Last Updated 26 Jan 2004
Article Copyright 2004 by Steven Campbell
Everything else Copyright © CodeProject, 1999-2013
Terms of Use
Layout: fixed | fluid