SharePoint List – Add/Update/Delete Item from Silverlight 3.0 App using lists.asmx


In this post, I’ll explain how can we use lists.asmx to Insert/Update/Delete items in a SharePoint list from Silverlight 3.0 app. In my next post I’ll show how can we get the data from SharePoint list and display it in grid in Silverlight 3.0 App.

Below are the steps to create a form using Silverlight 3.0 to insert item in the list:

Create a input form using following XAML:

<UserControl x:Class="SilverLightDemo.ListInsertion"

             xmlns:Primitives= "

             clr-namespace:

                System.Windows.Controls.Primitives;

             assembly=System.Windows.Controls"

    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"

    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"

    xmlns:d="http://schemas.microsoft.com/expression/blend/2008" xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"

    mc:Ignorable="d" Width="470" Height="250">


    <Grid x:Name="GridMain" Background="#40E1F0"  Width="450" Height="230" >


        <Grid.RowDefinitions>

            <RowDefinition Height="30"></RowDefinition>

            <RowDefinition Height="200"></RowDefinition>

        </Grid.RowDefinitions>


        <Grid.ColumnDefinitions>

            <ColumnDefinition></ColumnDefinition>

        </Grid.ColumnDefinitions>


        <Border Grid.Row="0" Grid.Column="0" CornerRadius="10" Background="#409DF0" Margin="0,0,0,0">

            <TextBlock Text="Insert record..." Foreground="White" Margin="10,3,0,0"></TextBlock>

        </Border>


        <Grid x:Name="GridInner" Grid.Row="1">


            <Grid.RowDefinitions>

                <RowDefinition></RowDefinition>

                <RowDefinition></RowDefinition>

                <RowDefinition></RowDefinition>

                <RowDefinition></RowDefinition>

            </Grid.RowDefinitions>


            <Grid.ColumnDefinitions>

                <ColumnDefinition Width="100"></ColumnDefinition>

                <ColumnDefinition Width="300"></ColumnDefinition>

            </Grid.ColumnDefinitions>


            <TextBlock Grid.Row="0" Grid.Column="0" Text="Employee Name" Height="25" Foreground="#FF14517B" Margin="10,3,0,0"></TextBlock>

            <TextBox Grid.Row="0" Grid.Column="1" x:Name="TxtEmployeeName" Height="25" Margin="10,3,0,0"></TextBox>

            <TextBlock Grid.Row="1" Grid.Column="0" Text="Designation" Height="25" Foreground="#FF14517B" Margin="10,3,0,0"></TextBlock>

            <TextBox Grid.Row="1" Grid.Column="1" x:Name="TxtDesignation" Height="25" Margin="10,3,0,0"></TextBox>

            <TextBlock Grid.Row="2" Grid.Column="0" Text="Project" Height="25" Foreground="#FF14517B" Margin="10,3,0,0"></TextBlock>

            <TextBox Grid.Row="2" Grid.Column="1" x:Name="TxtProject" Height="25" Margin="10,3,0,0"></TextBox>

            <StackPanel Grid.Row="3" Grid.Column="1" Orientation="Horizontal" HorizontalAlignment="Left">

                <Button Content="Insert" Height="25" Width="60" Margin="10,3,0,0" Click="InsertButton_Click"></Button>

                <Button Grid.Row="3" Grid.Column="1" Content="Clear" Height="25" Width="60" Margin="10,3,0,0" Click="ClearButton_Click"  ></Button>

            </StackPanel>

        </Grid>


    </Grid>

</UserControl>

Form will look like as picture below:

image

Add a service reference to Lists.asmx located at

http://myserver/_vti_bin/lists.asmx

Add following methods to code file:

private void AddDataToList()

       {

           string [] ArrFieldNames = {"Title","Designation","Project"};

           string [] ArrFieldValues = {TxtEmployeeName.Text.Trim(),TxtDesignation.Text.Trim(),TxtProject.Text.Trim()};

           string StrListName = "SilverLightDemoList";


           ListService.ListsSoapClient ListServiceProxy = new ListService.ListsSoapClient();


           ListServiceProxy.UpdateListItemsCompleted += new EventHandler<SilverLightDemo.ListService.UpdateListItemsCompletedEventArgs>(ListServiceProxy_UpdateListItemsCompleted);


           XElement XElementBacth = GetQueryForListItem(ArrFieldNames, ArrFieldValues, "New");


           ListServiceProxy.UpdateListItemsAsync(StrListName, XElementBacth);

           ListServiceProxy.CloseAsync();

       }

/// <summary>

        /// Returns Xelement containg the Data to be added to the List.

        /// </summary>

        /// <param name="ArrFieldNames">Array containg the name of the fields</param>

        /// <param name="ArrFieldValues">Array containing the values for the field</param>

        /// <param name="operationType">Insert/Update</param>

        /// <returns></returns>

        private XElement GetQueryForListItem(string[] ArrFieldNames, string[] ArrFieldValues, string StrOperationType)

        {

            XElement XElementMethod = new XElement(("Method"), new XAttribute("ID", "1"), new XAttribute("Cmd", StrOperationType));


            for (int i = 0; i < ArrFieldNames.Length; i++)

            {

                XElementMethod.Add(new XElement("Field", ArrFieldValues[i], new XAttribute("Name", ArrFieldNames[i])));

            }


            XElement XElementBatch = new XElement(("Batch"), new XAttribute("OnError", "Return"));

            XElementBatch.Add(XElementMethod);


            return XElementBatch;

        }

Call AddDataToList method from Insert Button click event. In AddDataToList method, i have used UpdateListItemsAsync method to update the list. Add an event handler for this asynchronous method. This event handler will get executed when UpdateListItemsAsync method finishes its job. You can use this event handler to notify the user or for some other stuff post insertion.

Below is the code for UpdateListItemsCompleted event handler:

void ListServiceProxy_UpdateListItemsCompleted(object sender, System.ComponentModel.AsyncCompletedEventArgs e)

       {

           MessageBox.Show("Item Added");

       }

Also, Silverlight does not support XmlDocument/XmlElement classes hence i have used XElement class under System.Xml.Linq namespace.

Lastly, add a ClientAccessPolicy.xml file to the application directory of your SharePoint site. Below is the xml for basic ClientAccessPolicy.xml file:

<?xml version="1.0" encoding="utf-8"?>

<access-policy>

    <cross-domain-access>

        <policy>

            <allow-from http-request-headers="*" >

                <domain uri="*"/>

            </allow-from>

            <grant-to>

                <resource path="/" include-subpaths="true"/>

            </grant-to>

        </policy>

    </cross-domain-access>

</access-policy>

For more information on ClientAccessPolicy.xml file, check out the following link:

http://msdn.microsoft.com/en-us/library/cc197955(VS.95).aspx

Run your Silvelight App and enter data in the input form. Click Insert and an item will get created in your list.

To update/delete the list item, we require the id of that particular item. Hence do not forget to add a text box for the Id field in the input form. Following is the code to update and delete the existing list item:

private void UpdateDataInList()

       {

           string[] ArrFieldNames = { "ID","Title", "Designation", "Project" };

           string[] ArrFieldValues = {TxtId.Text.Trim(), TxtEmployeeName.Text.Trim(), TxtDesignation.Text.Trim(), TxtProject.Text.Trim() };

           string StrListName = "SilverLightDemoList";


           ListService.ListsSoapClient ListServiceProxy = new ListService.ListsSoapClient();


           ListServiceProxy.UpdateListItemsCompleted += new EventHandler<SilverLightDemo.ListService.UpdateListItemsCompletedEventArgs>(ListServiceProxy_UpdateListItemsCompleted);


           XElement XElementBacth = GetQueryForListItem(ArrFieldNames, ArrFieldValues, "Update");


           ListServiceProxy.UpdateListItemsAsync(StrListName, XElementBacth);

           ListServiceProxy.CloseAsync();

       }

private void DeleteDataFromList()

       {

           string[] ArrFieldNames = { "ID"};

           string[] ArrFieldValues = {TxtId.Text.Trim()};

           string StrListName = "SilverLightDemoList";


           ListService.ListsSoapClient ListServiceProxy = new ListService.ListsSoapClient();


           ListServiceProxy.UpdateListItemsCompleted += new EventHandler<SilverLightDemo.ListService.UpdateListItemsCompletedEventArgs>(ListServiceProxy_UpdateListItemsCompleted);


           XElement XElementBacth = GetQueryForListItem(ArrFieldNames, ArrFieldValues, "Delete");


           ListServiceProxy.UpdateListItemsAsync(StrListName, XElementBacth);

           ListServiceProxy.CloseAsync();

       }

Tags: , ,

4 Responses to “SharePoint List – Add/Update/Delete Item from Silverlight 3.0 App using lists.asmx”

  1. Gerardo Says:

    I did the sample but only work the Delete Method only with the Administrator user, when I using the InsertInDataList or UpdateDataInList the method is completed but not is the new or updates datas.

    I put the ClientAccesPolicy.xml is my root site:
    Web: http://myserver:200/
    Directory: C:\Inetpub\wwwroot\wss\VirtualDirectories\200

    Can you help me…

    Best regards…

  2. Gerardo Says:

    I has an errors in my code and now the 3 methods function correctly but I cant use it with any user only with administrator.

    Can you what’s happend?, How I specific the credentials from users?

  3. Gerardo Says:

    PROBLEM SOLUTION:
    The SharepointList must be permisions for the user, I did test with full control and works fine.
    The permission has modificated for Insert,Update,Delete and Read.

    If somebody needs help contact to gerardo_mot@hotmail.com

  4. zoran Says:

    hi im trying your samples and they work but i have problem when i want to insert a record in a list where i have lookup fields.

    did u ever tried the similar case?

Leave a reply to zoran Cancel reply