Inserting Multiple Rows in SharePoint list using SharePoint 2007 Web Services

Today at work, I come across a very simple requirement to

Insert Multiple Rows in SharePoint list using SharePoint 2007 Services”.

Although this is very common problem and you might get much information while binging on same topic. But to benefit of my readers, I decided to go ahead blog post solution of above problem.  Smile

For purpose of this post, I have created a SharePoint list as below called TestInsertion,

image

We will insert multiple records from a console application. Create a console application and add a DTO [Data Transfer object] class to represent list. If you notice below class, it got properties name same as columns of target list TestInsertion.


public class Items
   {
       public string FirstName { get; set; }
       public string LastName { get; set; }
       public string EmailAddress { get; set; }
       public string Region { get; set; }
   }

Now go ahead and define two global variables in Program.cs

image

Make sure list TestInsertion resides in Yoursubsite [See the Site URL]

Before start writing code to insert multiple rows, we need to ass Web Service in console program. To do that right click on console application and select Add service Reference. Click on Advanced button and select Add Service Reference .

imageimage

In URL give the URL of the SharePoint Service.

image

Assume you have a function returning List<Items> to insert as below. Below static function GetItemsToInsert() is returning List<items> to insert.


public  static List<Items> GetItemsToInsert()
       {
           List<Items> lstItems = new List<Items>
                                 {
                                     new Items
                                     {
                                         FirstName = "John " ,
                                         LastName ="Papa" ,
                                         EmailAddress= "John.papa@blahblah.com",
                                         Region = "USA"
                                     },
                                     new Items
                                     {
                                         FirstName = "Scott" ,
                                         LastName ="Gui" ,
                                         EmailAddress= "Scott.Gui@blahblah.com",
                                         Region = "USA"
                                     },

                                     new Items
                                     {
                                         FirstName = "Dhananjay" ,
                                         LastName ="Kumar" ,
                                         EmailAddress= "Dhananjay.kumar@blahblah.com",
                                         Region = "India"
                                     },
                                     new Items
                                     {
                                         FirstName = "Pinal" ,
                                         LastName ="dave" ,
                                         EmailAddress= "Pinal.dave@blahblah.com",
                                         Region = "India"
                                     },
                                     new Items
                                     {
                                         FirstName = "Victor" ,
                                         LastName ="Gui" ,
                                         EmailAddress= "Victor.Gui@Blahblah.com",
                                         Region = "USA"
                                     },
                                     new Items
                                     {
                                         FirstName = "Sahil" ,
                                         LastName ="Malik" ,
                                         EmailAddress= "sahil.Malik@blahblah.com",
                                         Region = "USA"
                                     },
                                 };
           return lstItems;

       }

To insert record you need to very first create Proxy of the list web service as below. Pass default credential to access the SharePoint Service.

image

After creation of proxy, we need GUID of list and default view of the list. We can get GUID of list and list default view with below code

image

To insert record we need to create a XML document and send that to SharePoint list service. When setting attribute for View, we are passing Guid of list default view fetched in previously.

image

Now XML document is created and we are due to create XML body representing data to be inserted.

image

In above code snippet points to be noted are as below,

  1. We are making call to GetItemsToInsert() function .
  2. Converting List<Items> to array
  3. Iterating through each element of array and creating Methods.
  4. Since we need to insert or add records so cmd value would be New.

Point here need to understand is about Method. If we need to insert 5 records then we need to create 5 methods. So in above code we are creating Method in array loop such that same number of Method would be created as of array count.

  1. We need to make sure that field names are same as internal name of the SharePoint list columns.

As of now we have created the data to be inserted in the list. To do the actual Insertion assign created data as inner XML of XML document and call the UpdateListItem() method of SharePoint Service

image

For your reference full source code is given below. Feel free to use it and modify it for your requirement  Smile

Program.cs


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
using System.Data;

namespace InsertingIteminSharePointListRemotely
{

    class Program
    {

         static string SiteUrl = "http://yourserver:12345/Yoursite/Yoursubsite/ /_vti_bin/Lists.asmx";
static string ListName = "TestInsertion";

        static void Main(string[] args)
        {

                #region Creating Proxy for List Web Service

                    webServiceProxy.Lists listService  = new webServiceProxy.Lists();
                    listService.Credentials = System.Net.CredentialCache.DefaultCredentials;
                    listService.Url = SiteUrl;

                #endregion

                #region Getting GUID of List and View

                System.Xml.XmlNode ndListView = listService.GetListAndView(ListName, "");
                 string strListID = ndListView.ChildNodes[0].Attributes["Name"].Value;
                 string strViewID = ndListView.ChildNodes[1].Attributes["Name"].Value;

                #endregion

                #region Creating XML Document

                      XmlDocument docToUpdate = new XmlDocument();
                      XmlElement docToElemnt = docToUpdate.CreateElement("Batch");
                      docToElemnt.SetAttribute("OnError", "Continue");
                      docToElemnt.SetAttribute("ListVersion", "1");
                      docToElemnt.SetAttribute("ViewName", strViewID);

                 #endregion

                #region Creating Data to Insert

                      var result = GetItemsToInsert ().ToArray();
                      string dataToInsert = string.Empty;
                      int id = 0;
                      for (int i = 0; i < result.Length; i++)
                      {
                          id = i + 1;
                          dataToInsert = dataToInsert + "<Method ID='"+id+"' Cmd='New'>";
                          dataToInsert = dataToInsert + "<Field Name=\"FirstName\">"+result[i].FirstName+"</Field>";
                          dataToInsert = dataToInsert + "<Field Name=\"LastName\">"+result[i].LastName+"</Field>";
                          dataToInsert = dataToInsert + "<Field Name=\"EmailAddress\">"+result[i].EmailAddress+"</Field>";
                          dataToInsert = dataToInsert + "<Field Name=\"Region\">"+result[i].Region+"</Field>";
                          dataToInsert = dataToInsert + "</Method>";

                      }

                #endregion

                #region Inserting Record
                      docToElemnt.InnerXml = dataToInsert;
                      try
                      {
                          listService.UpdateListItems(strListID, docToElemnt);
                          Console.WriteLine("Item Inserted");
                      }
                      catch (Exception ex)
                      {
                          Console.WriteLine(ex.StackTrace + ex.Message);
                      }

                #endregion

                      Console.ReadKey(true);
        }
    }
}

I hope this quick post was useful to you.  Smile

 

Fetching Image from SharePoint 2007 picture library using object model

I thought this is an easy requirement to fetch Image form SharePoint 2007 picture library and bind to a System.Drwaing.Image object. But when I started doing that, I had to give my 3 to 4hrs. So here is the code snippet to fetch images from SharePoint 2007 Picture library.

Namespace Required


clip_image002


Function to return Image as MemoryStream

This function will return Image from Picture Library of SharePoint 2007 using WSS Object model. This function is taking siteUrl and filename to be fetched from the picture library. This function is returning MemoryStream



public static MemoryStream GetImageforCharts(string siteUrl, string fileName)
        {
            Byte[] fileContentsArray=null; 
            MemoryStream imageStream = null; 

            try
            {
                using (SPSite site = new SPSite(siteUrl))
                // using (SPSite site = SPContext.Current.Site)
                {
                    using (SPWeb web = site.OpenWeb())
                    {

                     SPPictureLibrary chartPictureLibrary = 
                                      (SPPictureLibrary)web.Lists["UrPictureLibraryName"];
                        SPQuery query = new SPQuery();
                query.Query = @"<Where><Eq>
                                 <FieldRef Name ='Title'/>
                               <Value Type='Text'>" + fileName + "</Value></Eq></Where>";
                    SPListItemCollection lstImages = chartPictureLibrary.GetItems(query);
                        foreach (SPListItem r in lstImages)
                        {
                            SPFile file = r.File;
                            using (Stream fileContents = file.OpenBinaryStream())
                            {
                                long  length = fileContents.Length ;
                                fileContentsArray = new Byte[length]; 
                          fileContents.Read(fileContentsArray, 0,Convert.ToInt32(length));
                            }
                            
                        }

                        

                    }

                }

                imageStream = new MemoryStream(fileContentsArray);
                return imageStream; 
              

            }
            catch (Exception ex)
            {
                return null; 
            }



Using the Function

Now we can call the function as below, and save the Image in System.Drawing.Image object.

clip_image004

Fetching lists from SharePoint 2010 site using client object model

Creating the UI

1. Add a label

2. Add a textbox. Give any meaningful name I am leaving default name here.

3. A button. On click event of the button list names will be fetched.

4. A listbox control to bind the lists from SharePoint site.

Setting up the environment

Right click on the project .Click on the Application tab and change the Target framework type to .Net Framework 3.5

clip_image002

Add the references of below dll in the project.

Microsoft.SharePont.Client

Microsoft.SharePoint.Client.Runtime

clip_image004

After adding the dll, add below namespace

clip_image006

Now on the click event of btnGetLists write the below code

Code to Retrieve the Lists of SharePoint site

On click event of the button, write the below code

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

using SharePointclientObj = Microsoft.SharePoint.Client;

namespace WindowsFormsApplication1
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void btnGetLists_Click(object sender, EventArgs e)
        {
             listBox1.Items.Clear();
            //Get a context
             using (SharePointclientObj.ClientContext ctx = new SharePointclientObj.ClientContext(textBox1.Text))
             {
                 //Get the site
                 SharePointclientObj.Web site = ctx.Web;
                 ctx.Load(site);
                 //Get Lists
                 ctx.Load(site.Lists);
                 //Query
                 ctx.ExecuteQuery();
                 //Fill List
                 foreach (SharePointclientObj.List list in site.Lists)
                 {
                     listBox1.Items.Add(list.Title);
                 }

             }
        }
    }
}

Output

clip_image008

Content Editor Web Part in SharePoint 2010

Target Audience : Begineers

This articles is targeted to beginners of SharePoint 2010.

In this article we will walkthrough

1. Adding a Web part Page

2. Content Editor Web Part on the page.

Follow the steps as below,

Step1

Open SharePoint site and click on Site Action . From Site Action drop down select more option

clip_image002

Step 2

Select Page option and then select Web Part page. And click on Create

clip_image004

Step 3

Give a name of your choice to the page. Select a layout template. Select Share Document as place to save this page and click on Create.

clip_image005

You will get page template as below, if you have selected the same layout as of mine.

clip_image007

Step 4

Click on Add a Web Part and select Media and Content from categories

clip_image009

clip_image011

Step 5

Now in Content Editor type the text.

clip_image013

Step 6

Click on Home page. And from Share Document Library click on MyMediaWebPart page to see the Web part added .

Silverlight WebPart in Share Point2010 using Client object model

In this article we will walkthrough to create Silverlight WebPart and deploy to SharePoint 2010 sites. We will fetching list items using client object model and bind to the Silverlight datagrid.

Step1

Open Visual Studio 2010 and create a new Silverlight project by choosing Silverlight project template from Silverlight tab.

clip_image001

clip_image002

Step 2

Add the reference of SharePoint client object model.

1. Microsoft.SharePoint.Client.Silverlight.dll

2. Microsoft.SharePoint.Client.Silverlight.Runtime.dll

To add the reference browse to the folder C:\Program Files\Common Files\Microsoft Shared\Web Server Extensions\14\TEMPLATE\LAYOUTS\ClientBin

clip_image003

Step3

Open designer of Silverlight page (xaml file) and drag and drop the DataGrid on the page.

clip_image004

MainPage.xaml

<UserControl 
xmlns:data="clr-namespace:System.Windows.Controls;
assembly=System.Windows.Controls.Data" 
xmlns:sdk="http://schemas.microsoft.com/winfx/2006/xaml/presentation/sdk"
x:Class="SilverlightApplication1.MainPage"
    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"
    d:DesignHeight="300" d:DesignWidth="400">
    <Grid x:Name="LayoutRoot" Background="White">
 
        <StackPanel Orientation="Vertical" >
            <data:DataGrid
                      x:Name="MyDataGRid" 
                      Height="auto" 
                     Width="auto" AutoGenerateColumns="True"  />            
        </StackPanel>          
 
    </Grid>
</UserControl>
 

Step4

Now add a class called Product. This class will represent SharePoint list, we are going to display in DataGrid.

Product.cs

 
namespace SilverlightApplication1
{
    public class Product
    {
 
        public string ProductId { get; set; }
        public string ProductName { get; set; }
        public string ProductPrice { get; set; }
 
 
    }
}
 

Step5

1. Open MainPage.xaml.cs file and add the reference

clip_image005

2. In the Page constructor connect to the ClientContext

clip_image007

3. Load the current web or root site of the web application where you are going to deploy the Silverlight webpart.

clip_image008

4. Get the list to be queried in the context

clip_image010

Here Test1_Product is name of the SharePoint list we want to query.

5. Load the list in the client context

clip_image011

6. Create instance of CAML query class to query the list

clip_image012

Here we are retrieving all the items from the list.

7. Now retrieve the items from the list

clip_image013

8. Now load the returned items of the list in context

clip_image014

9. Now need to execute the query asynchronously

clip_image016

10. We need to create onRequestSucceeded

clip_image018

11. Now we need to create BindData action and in this we will fetch the items of the list and create list of ProductClass . and then Bind the list to DataGrid

clip_image020

Here MyDataGrid is name of the DataGrid . Make sure you are giving internal names of the list columns.

MainPage.xaml.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using Microsoft.SharePoint.Client;
namespace SilverlightApplication1
{
    public partial class MainPage : UserControl
    {
       ListItemCollection ProductsCollection;      
        public MainPage()
        {
            InitializeComponent();
            var context = new ClientContext(ApplicationContext.Current.Url);
            context.Load(context.Web);
             var productsList = context.Web.Lists.GetByTitle("Test1_Product");
             context.Load(productsList);
             var query = CamlQuery.CreateAllItemsQuery();
             ProductsCollection = productsList.GetItems(query);
             context.Load(ProductsCollection);
             context.ExecuteQueryAsync(OnRequestSucceeded, null);
 
        }
        private void OnRequestSucceeded(Object sender, ClientRequestSucceededEventArgs args)
        {
            Dispatcher.BeginInvoke(BindData);
        }
        private void BindData()
        {
            var list = new List<Product>();
            foreach (var i in ProductsCollection)
            {
                list.Add(new Product
                          {
                              ProductName = i["ProductName"].ToString(),
                              ProductId = i["ProductId"].ToString(),
                              ProductPrice = i["ProductPrice"].ToString()
                          }
                          );
 
            }
 
              MyDataGRid.DataContext = list;
              MyDataGRid.ItemsSource = list;            
        }
    }
}
 

Step 6

Now before building the project, right click on the project and

clip_image021

Navigate to Build tab and set the output path to below folder.

C:\Program Files\Common Files\Microsoft Shared\Web Server Extensions\14\TEMPLATE\LAYOUTS\ClientBin

clip_image023

And build the project

Step7

Open the SharePoint site and Edit the page

clip_image024

Then click on Insert

clip_image025

Then add Web Part .

clip_image026

Click on Add button

/_layouts/ClientBin/SilverlightApplication1.xap

clip_image027

And press OK,

Now you can see Silverlight WebPart being added to SharePoint site.

clip_image029