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

SharePoint 2010 with Windows 7 Phone

In this article we will retrieve data from SharePoint list and display it Windows 7 phone application.

clip_image001

The expected output is as below,

clip_image002

 

Flow Diagram

clip_image003

Now we will follow the below steps to perform all above operations.

Step 1: Setting up the SharePoint list

We have a custom list

1. Name of the list is Test_Product.

2. Columns of the list is as below ,

clip_image005

3. There are two items in the list

clip_image007

4. URL of the SharePoint site is

http://dhananjay-pc/my/personal/Test1

 

Now we will access the SharePoint site on above URL.

Step 2 Creating WCF Service

 

Now we will create a WCF Service. WCF Service will have four operation contracts for CRUD operation on list.

To create WCF service, open visual studio and from WCF tab select WCF Service application.

clip_image009

Now to make sure that we would able to use SPLinq or LINQ to SharePoint we need to change the target framework and Platform target

So to do those follow as below,

1. Right click and click on Properties of WCF Service

clip_image010

2. Click on the Build tab and change Platform Target to Any CPU.

clip_image012

3. Click on the Application tab and change the Target framework type to .Net Framework 3.5

clip_image014

Now we need to create DataContext class of SharePoint list such that we can perform LINQ against that class to perform CRUD operation. To create context class we need to perform below steps.

1. Open the command prompt and change directory to

C:\Program Files\Common Files\Microsoft Shared\Web Server Extensions\14\BIN

Type command CD C:\Program Files\Common Files\Microsoft Shared\Web Server Extensions\14\BIN

clip_image016

2. Now we need to create the class for corresponding list definitions.

C:\Program Files\Common Files\Microsoft Shared\Web Server Extensions\14\BIN> spme

tal.exe /web:http://dhananjay-pc/my/personal/Test1 /namespace:nwind /code:Product.cs

In above command we are passing few parameters to spmetal.exe, they are as below

a. /web:Url

Here we need to provide URL of SharePoint site

/web:http://dhananjay-pc/my/personal/Test1 /

://dhananjay-pc/my/personal/Test1 / is URL of SharePoint site, I created for myself. You need to provide your SharePoint site URL here.

b. /namespace:nwind

This would be the namespace under which class of the list will get created. In my case name of the namespace would be nwind.

c. /code:Product.cs

This is the file name of the generated class. Since we are giving name Product for the file then class generated will be ProductDataContext

The classes default gets saved in the same folder with SPMetal.exe. So to see where the class got created we need to navigate to folder

C:\Program Files\Common Files\Microsoft Shared\Web Server Extensions\14\BIN

Add created class to the WCF Service project

Now add this class to the project. To do this, right click on the WCF Service project and select Add existing item. Then browse to above path and select Product.cs

Host the WCF Service in IIS

To work with SPLInq in WCF service, we need to host the service in IIS with the same application pool SharePoint is running.

See the below link for step by step explanation on how to host WCF 4.0 Service in IIS 7.5

http://dhananjaykumar.net/2010/09/07/walkthrough-on-creating-wcf-4-0-service-and-hosting-in-iis-7-5/

Only we need to make sure that,

Hosted WCF service is sharing the same application pool with SharePoint.

clip_image017

Select the Application pool to SharePoint-80

Create Contracts

We need to create DataContract or Data Transfer object. This class will represent the Product Data context class (We generated this class in previous step) 0

Create Data Contract,


[DataContract]
 public class ProductDTO
 {
 [DataMember]
 public string ProductName;
 [DataMember]
 public string ProductId;
 [DataMember]
 public string ProductPrice;
 }

 

Add References to work with LINQ to SharePoint

Microsoft.SharePoint

Microsoft.SharePoint.Linq

Right click on Reference and select Add Reference. To locate Microsoft.SharePoint and Microsoft.SharePoint.Linq dll browse to C:\Program Files\Common Files\Microsoft Shared\Web Server Extensions\14\ISAPI. All the SharePoint dll are here in this location.

Add the namespace

clip_image018

Nwind is the name of the namespace of the data context class we created in previous steps. We need to make sure that we have added Product class to the WCF Service application project as Add an Existing item.

Create Service Contract

We need to create Service contract. There would be four operation contracts each for one operation on Sharepoint list.

IService1.cs


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.ServiceModel;
using System.Runtime.Serialization;
using System.ServiceModel.Description;

namespace WcfService1
{
 [ServiceContract ]
 public  interface IService1
 {

[OperationContract]
 List<ProductDTO> GetProduct();
 }

 

Implement the Service

Now we need to implement the service to perform operations


using (ProductDataContext context = new ProductDataContext("<a href="http://dhananjay-pc/my/personal/Test1">http://dhananjay-pc/my/personal/Test1</a>"))
 {

ProductDTO product;
 List<ProductDTO> lstProducts = new List<ProductDTO>();
 var result = from r in context.Test1_Product select r;
 foreach (var r in result)
 {

product = new ProductDTO { ProductId = r.ProductId, ProductName = r.ProductName, ProductPrice = r.ProductPrice.ToString () };

lstProducts.Add(product);
 }

&nbsp;

return lstProducts;
 }

 

Retrieving all the list items

In above code

1. Creating instance of ProductDataContext.

2. Using LINQ to SharePoint retrieving all the list items.

3. Creating instance of ProductDTO class with values fetched from SharePoint list

4. Adding the instance of ProductDTO class in List of ProductDTO.

5. Returning list of ProductDTO

Modify the Web.Config

1. We will put Binding as basicHttpBinding.

2. In ServiceBehavior attribute , we will enable the servicemetadata

3. In ServiceBehavior , we will make IncludeserviceException as false.

4. We will configure MetadataExchnagePoint in the service

So, Now in Web.Config Service configuration will look like


<system.serviceModel>
 <behaviors>
 <serviceBehaviors>
 <behavior name="MyBeh">
 <serviceMetadata httpGetEnabled="true"/>
 <serviceDebug includeExceptionDetailInFaults="false"/>
 </behavior>
 </serviceBehaviors>
 </behaviors>
 <services>
 <service name="WcfService1.Service1"  behaviorConfiguration="MyBeh">
 <endpoint address=""
 binding="basicHttpBinding"
 contract="WcfService1.IService1"/>
 <endpoint address="mex"
 binding="mexHttpBinding"
 contract ="IMetadataExchange" />

 <host>
 <baseAddresses>
 <add baseAddress="<a href="http://localhost:8181/Service1.svc/&quot;/">http://localhost:8181/Service1.svc/"/</a>>
 </baseAddresses>
 </host>
 </service>
 </services>
 </system.serviceModel>

 

Now our service is created. We will be hosting this service in IIS as we discussed in previous step. From IIS we will browse to test whether service is up and running or not.

For reference, full source code for service implementation is as below ,

Service1.svc.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.ServiceModel.Web;
using System.Text;
using Microsoft.SharePoint.Linq;
using Microsoft.SharePoint;
using nwind;
namespace WcfService1
{

 public class Service1 : IService1
 {
 public  List<ProductDTO> GetProduct()
 {
 using (ProductDataContext context = new ProductDataContext("<a href="http://dhananjay-pc/my/personal/Test1">http://dhananjay-pc/my/personal/Test1</a>"))
 {

ProductDTO product;
 List<ProductDTO> lstProducts = new List<ProductDTO>();
 var result = from r in context.Test1_Product select r;
 foreach (var r in result)
 {

product = new ProductDTO { ProductId = r.ProductId, ProductName = r.ProductName, ProductPrice = r.ProductPrice.ToString () };

lstProducts.Add(product);
 }

&nbsp;

return lstProducts;
 }

 }
}
}

 

Creating a Windows 7 Phone application

Open visual studio and create a new Windows Phone application from Silverlight from Windows phone project tab.

clip_image020

Add the service reference. Right click and add the Service reference of the WCF service created in previous step to the phone application.

Create the Product Client class

ProductClient.cs

 public class ProductatClient
 {
 public string ProductId { get; set; }
 public string ProductName { get; set; }
 public string ProductPrice { get; set; }
 }

 

Divide the content grid in two rows and put button in first row and list box in second row. We will create button and on click event of this button we will fetch data from the WCF service

clip_image022

Now we will create a List box to bind the SharePoint list data

clip_image023

So the full XAML is as below,

MainPage.xaml

 <phone:PhoneApplicationPage
 x:Class="WindowsPhoneApplication1.MainPage"
 xmlns="<a href="http://schemas.microsoft.com/winfx/2006/xaml/presentation">http://schemas.microsoft.com/winfx/2006/xaml/presentation</a>"
 xmlns:x="<a href="http://schemas.microsoft.com/winfx/2006/xaml">http://schemas.microsoft.com/winfx/2006/xaml</a>"
 xmlns:phone="clr-namespace:Microsoft.Phone.Controls;assembly=Microsoft.Phone"
 xmlns:shell="clr-namespace:Microsoft.Phone.Shell;assembly=Microsoft.Phone"
 xmlns:d="<a href="http://schemas.microsoft.com/expression/blend/2008">http://schemas.microsoft.com/expression/blend/2008</a>"
 xmlns:mc="<a href="http://schemas.openxmlformats.org/markup-compatibility/2006">http://schemas.openxmlformats.org/markup-compatibility/2006</a>"
 mc:Ignorable="d" d:DesignWidth="480" d:DesignHeight="768"
 FontFamily="{StaticResource PhoneFontFamilyNormal}"
 FontSize="{StaticResource PhoneFontSizeNormal}"
 Foreground="{StaticResource PhoneForegroundBrush}"
 SupportedOrientations="Portrait" Orientation="Portrait"
 shell:SystemTray.IsVisible="True">

<!--LayoutRoot is the root grid where all page content is placed-->
 <Grid x:Name="LayoutRoot" Background="Transparent">
 <Grid.RowDefinitions>
 <RowDefinition Height="Auto"/>
 <RowDefinition Height="*"/>
 </Grid.RowDefinitions>

<!--TitlePanel contains the name of the application and page title-->
 <StackPanel x:Name="TitlePanel" Grid.Row="0" Margin="12,17,0,28">
 <TextBlock x:Name="ApplicationTitle" Text="Windows 7" Style="{StaticResource PhoneTextNormalStyle}"/>
 <TextBlock x:Name="PageTitle" Text="SharePoint List" Margin="9,-7,0,0" Style="{StaticResource PhoneTextTitle1Style}"/>
 </StackPanel>

<!--ContentPanel - place additional content here-->
 <Grid x:Name="ContentPanel" Grid.Row="1" Margin="12,0,12,0">
 <Grid.RowDefinitions>
 <RowDefinition Height="1*"/>
 <RowDefinition Height="4*"/>
 </Grid.RowDefinitions>
 <Button x:Name="btnGetData"
 Content="Get Data from SharePoint list"
 Margin="0,0,19,43" FontWeight="ExtraBold"
 Foreground="#FFFCAEAE" FontStyle="Italic"
 FontStretch="UltraCondensed"
 Cursor="Hand"
 BorderBrush="#FFB76C6C"
 FontSize="18" FontFamily="Arial">
 <Button.Background>
 <LinearGradientBrush EndPoint="1,0.5" StartPoint="0,0.5">
 <GradientStop Color="Black" Offset="0" />
 <GradientStop Color="#FF902727" Offset="1" />
 </LinearGradientBrush>
 </Button.Background>
 </Button>
 <ListBox x:Name="lstBox"
 Grid.Row="1"
 FontSize="18"
 BorderThickness="2,3,2,0"
 DataContext="{Binding ElementName=lstBox}"
 FontStretch="ExtraExpanded"  Background="#FF8996DE">
 <ListBox.ItemTemplate>
 <DataTemplate>
 <StackPanel Orientation="Horizontal" >
 <TextBlock x:Name="txtProductId"
 Margin="15"
 Text="{Binding Path=ProductId, Mode=OneWay}"
 Foreground="White"
 FontWeight="ExtraBold"
 FontSize="24"
 FontFamily="Arial"  />
 <TextBlock x:Name="txtProductName"
 Margin=" 15"
 Text="{Binding ProductName, Mode=OneWay}"
 Foreground="White" FontWeight="ExtraBold"
 FontSize="24"
 FontFamily="Arial" />
 <TextBlock x:Name="txtProductPrice"
 Margin=" 15"
 Text="{Binding ProductPrice, Mode=OneWay}"
 Foreground="White"
 FontWeight="ExtraBold"
 FontSize="24" FontFamily="Arial" />
 </StackPanel>
 </DataTemplate>
 </ListBox.ItemTemplate>
 </ListBox>
 </Grid>

</Grid>

</phone:PhoneApplicationPage>

 

Now at the code behind, we need to fetch the data from WCF service

clip_image025

So the full source code is as below ,

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.Phone.Controls;
using WindowsPhoneApplication1.ServiceReference1;

namespace WindowsPhoneApplication1
{
 public partial class MainPage : PhoneApplicationPage
 {
 // Constructor
 public MainPage()
 {
 InitializeComponent();

btnGetData.Click += new RoutedEventHandler(btnGetData_Click);
 }

void btnGetData_Click(object sender, RoutedEventArgs e)
 {
 // MessageBox.Show("Dhananjay");
 Service1Client proxy = new Service1Client();
 proxy.GetProductCompleted += new EventHandler<GetProductCompletedEventArgs>(proxy_GetProductCompleted);
 proxy.GetProductAsync();
 }

void proxy_GetProductCompleted(object sender, GetProductCompletedEventArgs e)
 {
 List<ProductatClient> lstResults = new List<ProductatClient>();
 ProductatClient p;
 List<ProductDTO> results = e.Result.ToList();
 foreach (var r in results)
 {
 p = new ProductatClient { ProductName = r.ProductName,
 ProductId = r.ProductId,
 ProductPrice = r.ProductPrice };
 lstResults.Add(p);
 }
 lstBox.ItemsSource = lstResults;

}
 }
}

 

Now when we run the application, we will get the output as below,

clip_image002[1]

Enabling JavaScript IntelliSense on Visual Web Part in SharePoint 2010

Open Visual Studio 2010 and create a Visual Web Part project as selecting from SharePoint 2010 tab

clip_image002

Now provide name of the site where you want to deploy the web part

clip_image003

Click on Validate button to validate the site. If you are able to connect and get below message then we are we are good to go.

clip_image004

Open VisualWebPart1UserControl.ascx and add below script

clip_image006

After adding above script add

clip_image007

Now add below script,

clip_image009

Inside script tag , write a function

clip_image011

And now u can see that in this function IntelliSense is working

clip_image001

So in JavaScript function it would be working like below

clip_image013