Jean Paul's Blog

There are 2 types of People in the World, One who Likes SharePoint and..

    Advertisements
  • Microsoft MVP

  • MindCracker MVP

  • CodeProject MVP

  • eBook on SharePoint 2010

  • eBook on Design Patterns

  • eBook on Windows Azure

  • NLayers Framework @ CodePlex

  • MSDN Forums

  • .Net vs. Java

    Due to Public Demand
  • Advertisements

Archive for June, 2012

SharePoint 2010 – Search

Posted by Paul on June 20, 2012

In this article we can explore one of the core features of SharePoint. It is considered to be the Enterprise Feature of SharePoint. SharePoint allows configuration of Search based on different parameters. In short we can configure the breadth and depth of the search.

Search Architecture

Inside SharePoint 2010 Search is built as a service application. The Search Engine can Index SharePoint Sites, External contents, Files, Web sites etc.

Following are the server roles inside the SharePoint Search:

1. Crawler

2. Indexer

3. Query Servers

4. Search Center

Crawlers represent small programs which are scheduled to run on specific intervals. The Crawlers pass through each Content Source and Index the words in one location. These programs will be scanning Documents, Files and other Content Sources. Crawling consists of Full Crawl and Incremental Crawl. We can manually start the crawling process as well as schedule it.

The Indexer will create index files which contains the words and corresponding content source information for easier access. The indexing server can be configured to be a separate machine in a farm.

As the crawler will be encountering lots of file types like Word Document, PDF Document, Excel Document, Web sites, Text Files etc. it will be run out of logic on indexing these. We need to specify external Index Filters to tell how to index those file types. These Index Filters are also known as IFilter. The IFilter reads the contents of the file, creates the index keywords based on the content. Administrators need to configure each file type with an appropriate IFilter.

The Query Server is responsible for handling user search queries. In a farm environment query server can be configured to be a separate machine. The query serve operates on the index files for returning search results.

Search Center is a site inside SharePoint 2010 oriented towards Search. It allows configuring of Results, Advanced Search options, Navigation Elements etc. The user can create his own Search Site by using the Basic Search Center template.

Experimenting with Search

Now we can start experimenting with the Search User Interface and the functionality. The default Search box is available on the site as shown below:

clip_image002

Now we can try searching some text. Enter the address word of a contact and click the search button.

clip_image004

You can see the following results showing the data from Manager List and Edit form.

clip_image006

The search result fetched the contents of all list items inside the site. Now we can try searching with keyword Manager. The result will include the Manager list item name too.

clip_image008

References

http://technet.microsoft.com/en-us/sharepoint/ee518667

http://technet.microsoft.com/en-us/library/cc263144(office.12).aspx

http://msdn.microsoft.com/en-us/library/ms545957(v=office.12).aspx

Summary

In this article we have learnt the Search feature of SharePoint. Although Search is configured by SharePoint Administrators still the Developer can use the extended Search web services, Programmatic retrieval of content using Object Model etc.

Advertisements

Posted in C# | Tagged: , | Leave a Comment »

SharePoint 2010 – Client Object Model – C#, Silverlight, JavaScript supported

Posted by Paul on June 20, 2012

In this article I would like to discuss about the Client Object Model feature of SharePoint 2010.

Overview

Client Object Model is a new feature of SharePoint 2010. It provides programming against SharePoint site using .Net Managed Code or JavaScript.

The Client Object Model provides almost all the Programming features of Server Object Model plus advantages on Deployment. The Client OM (Client Object Model) is being used as the core programming aid for SharePoint 2010 and thus widely used in market.

Advantages

1. Less Deployment Hassles: Using Client OM, you do not need to install the components required by Server Object Model. Thus Client OM provides much ease to the end user.

2. Language Flexibility: We can use the following languages to work with Client OM:

a. Microsoft .Net

b. Silverlight

c. ECMA Script (JavaScript / Jscript)

3. Query Speed Optimizations: In the Client OM, reduced network traffic is attained using Query Optimizations. Thus the user will feel reduced round trips and other advantages like paged results etc.

How it works?

The Client OM works by sending an XML Request. The server will be returning a JSON response which is the converted to the appropriate Object Model.
image

Supported Languages

Following are the programming language/platform supported for Client Object Model.

· .Net Languages (C#, VB.NET etc.)

· Silverlight

· Scripting Languages (JavaScript, Jscript)

Core Assemblies

There are 2 assemblies to be referred for working with Client Object Model.

1. Microsoft.SharePoint.Client.dll

2. Microsoft.SharePoint.Client.Runtime.dll

These assemblies can be found in the 14 Hive folder:

%ProgramFiles%Common FilesMicrosoft Sharedweb server extensions14ISAPI

image

Classes inside Client Object Model

In C#, comparing with the classes of Server Object Model we can see that Client Object Model have similar classes with a suffix in the namespace and no SP prefix in the class name.

For example: An SPSite in Server Object Model is represented in Client OM as Site with namespace Microsoft.SharePoint.Client.

Client Object Model

Server Object Model

Microsoft.SharePoint.Client.ClientContext

SPContext

Microsoft.SharePoint.Client.Site

SPSite

Microsoft.SharePoint.Client.Web

SPWeb

Microsoft.SharePoint.Client.List

SPList

Example

Following is the example of retrieving a list from server using Client OM:

ClientContext context = new ClientContext("http://hp");

List list = context.Web.Lists.GetByTitle("Tasks");

context.Load(list);

context.ExecuteQuery();

Console.WriteLine(list.Title);

Console.ReadKey(false);

I should remark something about the above code:

· Even though there are multiple calls, they are send to Server until ExecuteQuery() is called

· Network round trips between client and server is reduced combining multiple calls into one

· Object Identity is used to setup the queries. Object Identities are those which refer to the Server Object Model. Object Identities are valid only for the current client context

More Examples with Client Object Model

Here I would like to list some of the examples using Client Object Model. For starting with the examples please do the following:

1. Create a Windows Application

2. Change the Target Framework to .Net 4.0

3. Add reference to Microsoft.SharePoint.Client, Microsoft.SharePoint.Client.Runtime

Before continuing with the examples please ensure the site have valid data items in the Tasks list. We will be changing the data items during our session.

1. Get List Items

Here we are querying the list items of Tasks list.

ClientContext context = new ClientContext(ServerText.Text);

List list = context.Web.Lists.GetByTitle("Tasks");

CamlQuery query = new CamlQuery();

query.ViewXml = "<View/>";

ListItemCollection items = list.GetItems(query);

context.Load(list);

context.Load(items);

context.ExecuteQuery();

After executing the code, the result can be stored into a DataTable as shown below.

DataTable table = new DataTable();

table.Columns.Add("Id");

table.Columns.Add("Title");

foreach (ListItem item in items)

table.Rows.Add(item.Id, item["Title"]);

datagrid.DataSource = table;

On my machine the data retrieves is shown below:

image

2. Update List Items

Here I would like to show the modification code. All the Title is appended with two asterisks who’s Id are of even number.

ClientContext context = new ClientContext(ServerText.Text);

List list = context.Web.Lists.GetByTitle("Tasks");

CamlQuery query = new CamlQuery();

query.ViewXml = "<View/>";

ListItemCollection items = list.GetItems(query);

context.Load(items);

context.ExecuteQuery();

foreach(ListItem item in items)

if ((item.Id % 2) == 0)

{

item["Title"] += "**";

item.Update();

}

context.ExecuteQuery();

After executing the query, please refresh the data grid using the Get Data button. You can see the following result.

You can see that the Titles are modified for those with Id are an even number.

 

image

3. Get By Row Limit

Here we can experiment with the Row Limit tag inside CAML queries. You can note that while accessing list we are actually using a CAMLQuery class instance. Inside the query it is possible to set the RowLimit tag as well.

The RowLimit tag restricts the number of items retrieved from the server. Thus we can save a lot of bandwidth by reducing the rows while doing search.

ClientContext context = new ClientContext(ServerText.Text);

Web web = context.Web;

List list = web.Lists.GetByTitle("Tasks");

CamlQuery query = new CamlQuery();

query.ViewXml = "<View><RowLimit>3</RowLimit></View>";

ListItemCollection listItems = list.GetItems(query);

context.Load(listItems);

context.ExecuteQuery();

You can see that the RowLimit is set to 3. On executing the query and displaying the results to a data grid you can see 3 items as shown below.

image

4. Get By Search Criteria

Now we can try selecting the list items using search criteria. Here we are trying to get the items of Status as ‘In Progress’.

ClientContext context = new ClientContext(ServerText.Text);

List list = context.Web.Lists.GetByTitle("Tasks");

CamlQuery query = new CamlQuery();

query.ViewXml = @"<View>

<Query>

<Where>

<Eq>

<FieldRef Name=’Status’/>

<Value Type=’Text’>In Progress</Value>

</Eq>

</Where>

</Query>

</View>";

ListItemCollection listItems = list.GetItems(query);

context.Load(listItems, items => items.Include(

item => item["Id"],

item => item["Title"],

item => item["Status"]

));

context.ExecuteQuery();

On executing the code above you will get the results filtered by the Status field.

image

5. Insert an Item

Here we can try with inserting a new item into the Tasks list.

ClientContext context = new ClientContext(ServerText.Text);

Web web = context.Web;

List list = web.Lists.GetByTitle("Tasks");

ListItemCreationInformation newItem = new ListItemCreationInformation();

ListItem listItem = list.AddItem(newItem);

listItem["Title"] = "New Item Created through C#";

listItem.Update();

context.ExecuteQuery();

You can see that we are using a new class named ListItemCreationInformation along with the ListItem class. This information will be recorded and passed to the server once the ExecuteQuery() method is called.

On executing the above code and retrieving the results you can see the output as below:

image

6. Update an Item

The Update operation is next in the series of the CRUD pattern. Already we have seen updating the Title. Here you can see updating the Status.

ClientContext context = new ClientContext(ServerText.Text);

List list = context.Web.Lists.GetByTitle("Tasks");

CamlQuery query = new CamlQuery();

query.ViewXml = "<View/>";

ListItemCollection listItems = list.GetItems(query);

context.Load(listItems);

context.ExecuteQuery();

ListItem item = listItems[listItems.Count – 1];

item["Status"] = "In Progress";

item.Update();

context.ExecuteQuery();

On executing the code you can see that the last item was updated.

image

7. Delete an Item

Now we can try deleting an item from the List. Here is the code to achieve that.

ClientContext context = new ClientContext(ServerText.Text);

List list = context.Web.Lists.GetByTitle("Tasks");

ListItemCollection listItems = list.GetItems(new CamlQuery() { ViewXml = "<View/>" });

context.Load(listItems);

context.ExecuteQuery();

listItems[listItems.Count – 1].DeleteObject();

context.ExecuteQuery();

We need to call the DeleteObject() method of the item followed by the ExecuteQuery().

8. Reducing the Result Size by Specifying Properties

So what if you wanted only 1 property value for an item with 10 properties. There will be unwanted transferring of 9 columns. Here we can see how to specify only the needed columns for an item.

ClientContext context = new ClientContext(ServerText.Text);

Web web = context.Web;

context.Load(web, w => w.Title);

context.ExecuteQuery();

MessageBox.Show("The title is: " + web.Title);

MessageBox.Show("Now trying to access a field not in Result Set (expect exception)");

try

{

MessageBox.Show(web.Description); // You will get Error here

}

catch (Exception ex)

{

MessageBox.Show(ex.ToString());

}

Here we can see that only the Title property has been specified for retrieval. Accessing the Description column throws an exception.

9. Reducing the Result Size in List

In the case of list the problem is worse as there are n number of columns for the list. The result will be multiplied n times. So if we need only 1 column and retrieve 10 columns for a list of 1000 items, we end up in getting 9 x 1000 unwanted column values.

So to specify the list columns in the Result Set the syntax will be slightly different.

ClientContext context = new ClientContext(ServerText.Text);

List list = context.Web.Lists.GetByTitle("Tasks");

CamlQuery query = new CamlQuery();

query.ViewXml = "<View/>";

ListItemCollection listItems = list.GetItems(query);

context.Load(listItems, items => items.Include(item => item["Id"]));

context.ExecuteQuery();

Please note the way Id is specified. While filling the results you should take care that only the Id column value is accessed.

DataTable table = new DataTable();

table.Columns.Add("Id");

foreach (ListItem item in listItems)

table.Rows.Add(item.Id);

datagrid.DataSource = table;

10. Specifying Credentials

You can specify user Credentials while accessing the SharePoint server. The property Credentials is for this purpose.

ClientContext context = new ClientContext(ServerText.Text);

context.Credentials = new NetworkCredential("User", "Password");

Web web = context.Web;

context.Load(web);

context.ExecuteQuery();

MessageBox.Show(web.Title);

Please specify the correct user name and password of your site otherwise Unauthorized Exception will be thrown.

So this concludes the article with Client Object Model examples for the most common scenarios. In the real world you will need much more complicated steps and I believe these will provide a base to achieve it.

When to use Server Object Model?

We can use it on the SharePoint server where the Server Object Model binaries are available. Typical example would be inside Web Parts / Workflows.

When to use Client Object Model?

We can use it from client machines where the entire SharePoint binaries are not available. A typical example would be from Windows Form application in a client machine.

References

MSDN on Client Object Model

Technet Blog on Client Object Model

Summary

In this article we have seen an overview about Client Object Model in SharePoint 2010. The source code attached contains various samples of working with the Client Object Model.

Posted in C# | Tagged: , , | 1 Comment »

SharePoint 2010 – Client Object Model – C#, Silverlight, JavaScript supported

Posted by Paul on June 20, 2012

In this article I would like to discuss about the Client Object Model feature of SharePoint 2010.

Overview

Client Object Model is a new feature of SharePoint 2010. It provides programming against SharePoint site using .Net Managed Code or JavaScript.

The Client Object Model provides almost all the Programming features of Server Object Model plus advantages on Deployment. The Client OM (Client Object Model) is being used as the core programming aid for SharePoint 2010 and thus widely used in market.

Advantages

1. Less Deployment Hassles: Using Client OM, you do not need to install the components required by Server Object Model. Thus Client OM provides much ease to the end user.

2. Language Flexibility: We can use the following languages to work with Client OM:

a. Microsoft .Net

b. Silverlight

c. ECMA Script (JavaScript / Jscript)

3. Query Speed Optimizations: In the Client OM, reduced network traffic is attained using Query Optimizations. Thus the user will feel reduced round trips and other advantages like paged results etc.

How it works?

The Client OM works by sending an XML Request. The server will be returning a JSON response which is the converted to the appropriate Object Model.
image

Supported Languages

Following are the programming language/platform supported for Client Object Model.

· .Net Languages (C#, VB.NET etc.)

· Silverlight

· Scripting Languages (JavaScript, Jscript)

Core Assemblies

There are 2 assemblies to be referred for working with Client Object Model.

1. Microsoft.SharePoint.Client.dll

2. Microsoft.SharePoint.Client.Runtime.dll

These assemblies can be found in the 14 Hive folder:

%ProgramFiles%\Common Files\Microsoft Shared\web server extensions\14\ISAPI

image

Classes inside Client Object Model

In C#, comparing with the classes of Server Object Model we can see that Client Object Model have similar classes with a suffix in the namespace and no SP prefix in the class name.

For example: An SPSite in Server Object Model is represented in Client OM as Site with namespace Microsoft.SharePoint.Client.

Client Object Model

Server Object Model

Microsoft.SharePoint.Client.ClientContext

SPContext

Microsoft.SharePoint.Client.Site

SPSite

Microsoft.SharePoint.Client.Web

SPWeb

Microsoft.SharePoint.Client.List

SPList

Example

Following is the example of retrieving a list from server using Client OM:

ClientContext context = new ClientContext("http://hp&quot;);

List list = context.Web.Lists.GetByTitle("Tasks");

context.Load(list);

context.ExecuteQuery();

Console.WriteLine(list.Title);

Console.ReadKey(false);

I should remark something about the above code:

· Even though there are multiple calls, they are send to Server until ExecuteQuery() is called

· Network round trips between client and server is reduced combining multiple calls into one

· Object Identity is used to setup the queries. Object Identities are those which refer to the Server Object Model. Object Identities are valid only for the current client context

More Examples with Client Object Model

Here I would like to list some of the examples using Client Object Model. For starting with the examples please do the following:

1. Create a Windows Application

2. Change the Target Framework to .Net 4.0

3. Add reference to Microsoft.SharePoint.Client, Microsoft.SharePoint.Client.Runtime

Before continuing with the examples please ensure the site have valid data items in the Tasks list. We will be changing the data items during our session.

1. Get List Items

Here we are querying the list items of Tasks list.

ClientContext context = new ClientContext(ServerText.Text);

List list = context.Web.Lists.GetByTitle("Tasks");

CamlQuery query = new CamlQuery();

query.ViewXml = "<View/>";

ListItemCollection items = list.GetItems(query);

context.Load(list);

context.Load(items);

context.ExecuteQuery();

After executing the code, the result can be stored into a DataTable as shown below.

DataTable table = new DataTable();

table.Columns.Add("Id");

table.Columns.Add("Title");

foreach (ListItem item in items)

table.Rows.Add(item.Id, item["Title"]);

datagrid.DataSource = table;

On my machine the data retrieves is shown below:

image

2. Update List Items

Here I would like to show the modification code. All the Title is appended with two asterisks who’s Id are of even number.

ClientContext context = new ClientContext(ServerText.Text);

List list = context.Web.Lists.GetByTitle("Tasks");

CamlQuery query = new CamlQuery();

query.ViewXml = "<View/>";

ListItemCollection items = list.GetItems(query);

context.Load(items);

context.ExecuteQuery();

foreach(ListItem item in items)

if ((item.Id % 2) == 0)

{

item["Title"] += "**";

item.Update();

}

context.ExecuteQuery();

After executing the query, please refresh the data grid using the Get Data button. You can see the following result.

You can see that the Titles are modified for those with Id are an even number.

 

image

3. Get By Row Limit

Here we can experiment with the Row Limit tag inside CAML queries. You can note that while accessing list we are actually using a CAMLQuery class instance. Inside the query it is possible to set the RowLimit tag as well.

The RowLimit tag restricts the number of items retrieved from the server. Thus we can save a lot of bandwidth by reducing the rows while doing search.

ClientContext context = new ClientContext(ServerText.Text);

Web web = context.Web;

List list = web.Lists.GetByTitle("Tasks");

CamlQuery query = new CamlQuery();

query.ViewXml = "<View><RowLimit>3</RowLimit></View>";

ListItemCollection listItems = list.GetItems(query);

context.Load(listItems);

context.ExecuteQuery();

You can see that the RowLimit is set to 3. On executing the query and displaying the results to a data grid you can see 3 items as shown below.

image

4. Get By Search Criteria

Now we can try selecting the list items using search criteria. Here we are trying to get the items of Status as ‘In Progress’.

ClientContext context = new ClientContext(ServerText.Text);

List list = context.Web.Lists.GetByTitle("Tasks");

CamlQuery query = new CamlQuery();

query.ViewXml = @"<View>

<Query>

<Where>

<Eq>

<FieldRef Name=’Status’/>

<Value Type=’Text’>In Progress</Value>

</Eq>

</Where>

</Query>

</View>";

ListItemCollection listItems = list.GetItems(query);

context.Load(listItems, items => items.Include(

item => item["Id"],

item => item["Title"],

item => item["Status"]

));

context.ExecuteQuery();

On executing the code above you will get the results filtered by the Status field.

image

5. Insert an Item

Here we can try with inserting a new item into the Tasks list.

ClientContext context = new ClientContext(ServerText.Text);

Web web = context.Web;

List list = web.Lists.GetByTitle("Tasks");

ListItemCreationInformation newItem = new ListItemCreationInformation();

ListItem listItem = list.AddItem(newItem);

listItem["Title"] = "New Item Created through C#";

listItem.Update();

context.ExecuteQuery();

You can see that we are using a new class named ListItemCreationInformation along with the ListItem class. This information will be recorded and passed to the server once the ExecuteQuery() method is called.

On executing the above code and retrieving the results you can see the output as below:

image

6. Update an Item

The Update operation is next in the series of the CRUD pattern. Already we have seen updating the Title. Here you can see updating the Status.

ClientContext context = new ClientContext(ServerText.Text);

List list = context.Web.Lists.GetByTitle("Tasks");

CamlQuery query = new CamlQuery();

query.ViewXml = "<View/>";

ListItemCollection listItems = list.GetItems(query);

context.Load(listItems);

context.ExecuteQuery();

ListItem item = listItems[listItems.Count – 1];

item["Status"] = "In Progress";

item.Update();

context.ExecuteQuery();

On executing the code you can see that the last item was updated.

image

7. Delete an Item

Now we can try deleting an item from the List. Here is the code to achieve that.

ClientContext context = new ClientContext(ServerText.Text);

List list = context.Web.Lists.GetByTitle("Tasks");

ListItemCollection listItems = list.GetItems(new CamlQuery() { ViewXml = "<View/>" });

context.Load(listItems);

context.ExecuteQuery();

listItems[listItems.Count – 1].DeleteObject();

context.ExecuteQuery();

We need to call the DeleteObject() method of the item followed by the ExecuteQuery().

8. Reducing the Result Size by Specifying Properties

So what if you wanted only 1 property value for an item with 10 properties. There will be unwanted transferring of 9 columns. Here we can see how to specify only the needed columns for an item.

ClientContext context = new ClientContext(ServerText.Text);

Web web = context.Web;

context.Load(web, w => w.Title);

context.ExecuteQuery();

MessageBox.Show("The title is: " + web.Title);

MessageBox.Show("Now trying to access a field not in Result Set (expect exception)");

try

{

MessageBox.Show(web.Description); // You will get Error here

}

catch (Exception ex)

{

MessageBox.Show(ex.ToString());

}

Here we can see that only the Title property has been specified for retrieval. Accessing the Description column throws an exception.

9. Reducing the Result Size in List

In the case of list the problem is worse as there are n number of columns for the list. The result will be multiplied n times. So if we need only 1 column and retrieve 10 columns for a list of 1000 items, we end up in getting 9 x 1000 unwanted column values.

So to specify the list columns in the Result Set the syntax will be slightly different.

ClientContext context = new ClientContext(ServerText.Text);

List list = context.Web.Lists.GetByTitle("Tasks");

CamlQuery query = new CamlQuery();

query.ViewXml = "<View/>";

ListItemCollection listItems = list.GetItems(query);

context.Load(listItems, items => items.Include(item => item["Id"]));

context.ExecuteQuery();

Please note the way Id is specified. While filling the results you should take care that only the Id column value is accessed.

DataTable table = new DataTable();

table.Columns.Add("Id");

foreach (ListItem item in listItems)

table.Rows.Add(item.Id);

datagrid.DataSource = table;

10. Specifying Credentials

You can specify user Credentials while accessing the SharePoint server. The property Credentials is for this purpose.

ClientContext context = new ClientContext(ServerText.Text);

context.Credentials = new NetworkCredential("User", "Password");

Web web = context.Web;

context.Load(web);

context.ExecuteQuery();

MessageBox.Show(web.Title);

Please specify the correct user name and password of your site otherwise Unauthorized Exception will be thrown.

So this concludes the article with Client Object Model examples for the most common scenarios. In the real world you will need much more complicated steps and I believe these will provide a base to achieve it.

When to use Server Object Model?

We can use it on the SharePoint server where the Server Object Model binaries are available. Typical example would be inside Web Parts / Workflows.

When to use Client Object Model?

We can use it from client machines where the entire SharePoint binaries are not available. A typical example would be from Windows Form application in a client machine.

References

MSDN on Client Object Model

Technet Blog on Client Object Model

Summary

In this article we have seen an overview about Client Object Model in SharePoint 2010. The source code attached contains various samples of working with the Client Object Model.

Posted in C# | Tagged: , , | 1 Comment »

SharePoint 2010 – Web Services

Posted by Paul on June 16, 2012

SharePoint Web Services provides is a good feature that allows us to access or change the SharePoint items remotely. We can use the Web Services to add more power to our application.

Following are the core features of SharePoint Web Services:

· Foundation and Server Web Services

· More Interoperability compared with Server Object Model

· Above 25 Web Services

· Manage Sites, Lists, Libraries, and Picture Libraries etc.

· Run queries against the server

· Custom Web Service creation possible

The following table contains some of the web services inside SharePoint 2010.

Service

Description

ASMX

WebSvcAdmin

Creation and Deletion of sites

Admin.asmx

WebSvcLists

List Management service

Lists.asmx

WebSvcAlerts

List Item Events service

Alerts.asmx

WebSvcAuthentication

Authentication based service

Authentication.asmx

WebSvcsites

Web sites management service

Sites.asmx

WebSvcspsearch

Searching service

Search.asmx

A more detailed list can be found here:

http://msdn.microsoft.com/en-us/library/ee705814.aspx

How to find the url of a Service?

The url of a service can be located inside _vti_bin folder of the site or site collection. Each site or site collection will be having this folder with all the web services inside it with .asmx extension.

Example: To use the search service use the following url:

http://YOURPCNAME/_vti_bin/search.asmx

clip_image002

Using http://appes-pc/_vti_bin/Lists.asmx

clip_image004

Adding Reference to Project

Now we can try adding reference to the service inside Visual Studio application. Create a new Ordinary Console Application (please note that we are not using SharePoint Console Application)

clip_image006

Now we need to Add Web Reference. In Visual Studio 2010 this option is available under the Add Service Reference option as shown below.

clip_image008

In the appearing dialog click the Advanced button.

clip_image010

In the next dialog, choose Add Web Reference option.

clip_image012

You will get the following dialog. This dialog is suitable for adding web service references.

clip_image014

Enter the url of the Lists.asmx as shown above. You need to replace the pc name with yours.

Set a Web reference name in the second highlighted box. This serves as the namespace.

Click the Add Reference button and your proxy class and related classes will be ready within a while. Inside the Program.cs enter the namespace and you can see the classes inside it as shown below:

clip_image016

Invoking the Proxy Class

Our class of interest is the Lists proxy. You can create an instance of it using the following code:

SPReference.Lists client = new SPReference.Lists();

Setting Credentials

Whenever we open a SharePoint site (without anonymous login enabled) the site will be prompting with user credentials. As we are invoking through web service the prompt dialog won’t be working. We need to pass the credentials using the property named Credentials.

client.Credentials = new NetworkCredential("appes", "password"); / // using System.Net;

Getting Reference to a List

We can try getting a reference to the Manager List inside our site. The Managers list contains items with columns:

· Title

· Name

· Address

clip_image018

Use the following code to fetch the data and display it to the console:

SPReference.Lists client = new SPReference.Lists();

client.Credentials = new NetworkCredential("appes", "PWD");

System.Xml.XmlDocument xmlDoc = new System.Xml.XmlDocument();

System.Xml.XmlElement viewFields = xmlDoc.CreateElement("ViewFields");

viewFields.InnerXml = "<FieldRef Name="Title" />" +

"<FieldRef Name="Name" />" +

"<FieldRef Name="Address" />";

XmlNode listItems = client.GetListItems("Manager", null, null, viewFields, null, null, null);

foreach (XmlNode node in listItems)

if (node.Name == "rs:data")

for (int f = 0; f < node.ChildNodes.Count; f++)

{

if (node.ChildNodes[f].Name == "z:row")

{

string title = node.ChildNodes[f].Attributes["ows_Title"].Value;

string name = node.ChildNodes[f].Attributes["ows_Name"].Value;

string address = node.ChildNodes[f].Attributes["ows_Address"].Value;

Console.WriteLine(title + " " + name + " " + address);

}

}

Console.ReadKey(false);

On executing the application we can see the following result:

clip_image020

Following are the steps involved in getting list item data:

1. Create List Proxy client

2. Set Credentials

3. Set the View Columns

4. Invoke GetListItems() method

5. Iterate through the nodes

6. Get value of node having name z:row

Note

Using web services, xml is used to represent the data. For advanced programming using properties please refer to the Server Object Model and SharePoint LINQ articles.

References

http://msdn.microsoft.com/en-us/library/ee705814.aspx

http://msdn.microsoft.com/en-us/library/ms583494.aspx

http://msdn.microsoft.com/en-us/library/lists.lists.getlistitems(v=office.12).aspx

Summary

In this article we have seen the Web Services feature of SharePoint 2010. It provides the flexibility of interoperability compared with the Server Object Model. Developers can access and manage SharePoint site from non .Net platforms like Java. The attached source code contains the example we discussed.

Posted in C# | Tagged: , | 2 Comments »

SharePoint 2010 – Web Services

Posted by Paul on June 16, 2012

SharePoint Web Services provides is a good feature that allows us to access or change the SharePoint items remotely. We can use the Web Services to add more power to our application.

Following are the core features of SharePoint Web Services:

· Foundation and Server Web Services

· More Interoperability compared with Server Object Model

· Above 25 Web Services

· Manage Sites, Lists, Libraries, and Picture Libraries etc.

· Run queries against the server

· Custom Web Service creation possible

The following table contains some of the web services inside SharePoint 2010.

Service

Description

ASMX

WebSvcAdmin

Creation and Deletion of sites

Admin.asmx

WebSvcLists

List Management service

Lists.asmx

WebSvcAlerts

List Item Events service

Alerts.asmx

WebSvcAuthentication

Authentication based service

Authentication.asmx

WebSvcsites

Web sites management service

Sites.asmx

WebSvcspsearch

Searching service

Search.asmx

A more detailed list can be found here:

http://msdn.microsoft.com/en-us/library/ee705814.aspx

How to find the url of a Service?

The url of a service can be located inside _vti_bin folder of the site or site collection. Each site or site collection will be having this folder with all the web services inside it with .asmx extension.

Example: To use the search service use the following url:

http://YOURPCNAME/_vti_bin/search.asmx

clip_image002

Using http://appes-pc/_vti_bin/Lists.asmx

clip_image004

Adding Reference to Project

Now we can try adding reference to the service inside Visual Studio application. Create a new Ordinary Console Application (please note that we are not using SharePoint Console Application)

clip_image006

Now we need to Add Web Reference. In Visual Studio 2010 this option is available under the Add Service Reference option as shown below.

clip_image008

In the appearing dialog click the Advanced button.

clip_image010

In the next dialog, choose Add Web Reference option.

clip_image012

You will get the following dialog. This dialog is suitable for adding web service references.

clip_image014

Enter the url of the Lists.asmx as shown above. You need to replace the pc name with yours.

Set a Web reference name in the second highlighted box. This serves as the namespace.

Click the Add Reference button and your proxy class and related classes will be ready within a while. Inside the Program.cs enter the namespace and you can see the classes inside it as shown below:

clip_image016

Invoking the Proxy Class

Our class of interest is the Lists proxy. You can create an instance of it using the following code:

SPReference.Lists client = new SPReference.Lists();

Setting Credentials

Whenever we open a SharePoint site (without anonymous login enabled) the site will be prompting with user credentials. As we are invoking through web service the prompt dialog won’t be working. We need to pass the credentials using the property named Credentials.

client.Credentials = new NetworkCredential("appes", "password"); / // using System.Net;

Getting Reference to a List

We can try getting a reference to the Manager List inside our site. The Managers list contains items with columns:

· Title

· Name

· Address

clip_image018

Use the following code to fetch the data and display it to the console:

SPReference.Lists client = new SPReference.Lists();

client.Credentials = new NetworkCredential("appes", "PWD");

System.Xml.XmlDocument xmlDoc = new System.Xml.XmlDocument();

System.Xml.XmlElement viewFields = xmlDoc.CreateElement("ViewFields");

viewFields.InnerXml = "<FieldRef Name=\"Title\" />" +

"<FieldRef Name=\"Name\" />" +

"<FieldRef Name=\"Address\" />";

XmlNode listItems = client.GetListItems("Manager", null, null, viewFields, null, null, null);

foreach (XmlNode node in listItems)

if (node.Name == "rs:data")

for (int f = 0; f < node.ChildNodes.Count; f++)

{

if (node.ChildNodes[f].Name == "z:row")

{

string title = node.ChildNodes[f].Attributes["ows_Title"].Value;

string name = node.ChildNodes[f].Attributes["ows_Name"].Value;

string address = node.ChildNodes[f].Attributes["ows_Address"].Value;

Console.WriteLine(title + " " + name + " " + address);

}

}

Console.ReadKey(false);

On executing the application we can see the following result:

clip_image020

Following are the steps involved in getting list item data:

1. Create List Proxy client

2. Set Credentials

3. Set the View Columns

4. Invoke GetListItems() method

5. Iterate through the nodes

6. Get value of node having name z:row

Note

Using web services, xml is used to represent the data. For advanced programming using properties please refer to the Server Object Model and SharePoint LINQ articles.

References

http://msdn.microsoft.com/en-us/library/ee705814.aspx

http://msdn.microsoft.com/en-us/library/ms583494.aspx

http://msdn.microsoft.com/en-us/library/lists.lists.getlistitems(v=office.12).aspx

Summary

In this article we have seen the Web Services feature of SharePoint 2010. It provides the flexibility of interoperability compared with the Server Object Model. Developers can access and manage SharePoint site from non .Net platforms like Java. The attached source code contains the example we discussed.

Posted in C# | Tagged: , | 2 Comments »

SharePoint 2010 – LINQ and SPMetal

Posted by Paul on June 16, 2012

In this article we can explore some of the advanced programming areas.

·         LINQ to SharePoint

·         SPMetal

LINQ to SharePoint is a new feature of SharePoint 2010.  LINQ stands for Language Integrated Query which is a part of .NET Language. The aim of LINQ is to support different data sources using the same Typed Query Syntax.  Presently it supports Objects, Datasets, SQL, Entities, XML etc.

Why we need LINQ?

You might have noted that the previous List Programming examples did not used proper column name access.  LINQ allows us to access the List in a Typed manner.  Adding more clarity we can access the list items based on the column names which we usually do with the databases.

Example: var result = from c in Citizen where c.Name == “John” select c;

What is SPMetal?

As we will be creating custom lists having custom column names, we need to generate the Entity Model.  The SPMetal.exe is the tool which helps in generating the Model classes.

Although we can create the Model classes manually, it will be a tedious job and error prone.  Using SPMetal would be the right approach to model classes.

Activities

Following are the activities performed in this article:

1.      Manager List Creation

2.      Entity Creation

3.      Read using LINQ

4.      Insert Entity

5.      Update Entity

6.      Delete Entity

 

 

Experimenting with LINQ and SPMetal

To start with create a custom list inheriting from Custom List and name it as Manager.  Add the following custom columns and data:

image

Generating the Entity Models

Now we can generate the Entity Model for the above List.

You can get the SPMetal.exe inside the following folder:

            C:Program FilesCommon FilesMicrosoft SharedWeb Server Extensions14BIN

Open a command prompt and go to the specified folder:

image

Now run the following command:

            SPMetal.exe /web:http://YOURSITE /code:SiteEntities.cs

(remember: no spaces before / after the colon(:))

Wait for a while and you will be ready with the new file.  Open the file SiteEntities and you can see the Manager class is contained inside.

image

Create Application

Create a new SharePoint > 2010 > Console Application (targeting .Net 3.5 framework) and add the SiteEntities.cs file into it.

image

Add reference to the following assembly:

image

You can try with the following operations Read, Insert, Update, Delete using LINQ to SharePoint

 

Selecting an Item

Now we are trying to select the managers with country as USA:

using (SiteEntitiesDataContext context = new SiteEntitiesDataContext(http://appes-pc&#8221;))

{

    var result = context.Manager.Where(m => m.Country == “USA”);

 

    foreach (ManagerItem manager in result)

    {

        Console.WriteLine(manager.Name);

    }

}

 

Note: You can use LINQ or Lambda Expression to do the query.  In the above example I have used Lambda.

On executing the application you can see the following results.

image

Inserting an Item

For inserting a new item into the Manager list, use the following code:

using (SiteEntitiesDataContext context = new SiteEntitiesDataContext(http://appes-pc&#8221;))

{

    ManagerItem manager = new ManagerItem();

    manager.Name = “New Manager”;

    manager.Address = “New Address”;

    manager.Country = “New Country”;

 

    context.Manager.InsertOnSubmit(manager);

    context.SubmitChanges();

}

 

After executing the application, open the Manager list inside SharePoint as shown below:

image

Updating an Item

For updating an item inside SharePoint use the following code:

using (SiteEntitiesDataContext context = new SiteEntitiesDataContext(http://appes-pc&#8221;))

{

    ManagerItem manager = context.Manager.Where(m => 

                          string.IsNullOrEmpty(m.Title)).FirstOrDefault();

    if (manager != null)

        manager.Title = “New Title”;

 

    context.SubmitChanges();

}

You can see the updated entity inside SharePoint:

image

Deleting an Item

For deleting an item inside SharePoint use the following code:

using (SiteEntitiesDataContext context = new SiteEntitiesDataContext(http://appes-pc&#8221;))

{

    ManagerItem manager = context.Manager.Where(m => m.Title.Length > 3).FirstOrDefault();

    if (manager != null)

        context.Manager.DeleteOnSubmit(manager);

 

    context.SubmitChanges();

}

 

You can see that the item is deleted inside SharePoint:

image

This concludes our Read, Insert, Update, Delete operations using LINQ to SharePoint.  Hope the topics are understood by the reader.

References

            http://msdn.microsoft.com/en-us/library/ee535491.aspx

            http://msdn.microsoft.com/en-us/library/ee538255.aspx

Summary

In this article we have explored LINQ and SPMetal tool.  This information is necessary in the real world programming scenarios.  The attachment contains the source code we discussed.

Posted in C# | Tagged: , | Leave a Comment »

SharePoint 2010 – LINQ and SPMetal

Posted by Paul on June 16, 2012

In this article we can explore some of the advanced programming areas.

·         LINQ to SharePoint

·         SPMetal

LINQ to SharePoint is a new feature of SharePoint 2010.  LINQ stands for Language Integrated Query which is a part of .NET Language. The aim of LINQ is to support different data sources using the same Typed Query Syntax.  Presently it supports Objects, Datasets, SQL, Entities, XML etc.

Why we need LINQ?

You might have noted that the previous List Programming examples did not used proper column name access.  LINQ allows us to access the List in a Typed manner.  Adding more clarity we can access the list items based on the column names which we usually do with the databases.

Example: var result = from c in Citizen where c.Name == “John” select c;

What is SPMetal?

As we will be creating custom lists having custom column names, we need to generate the Entity Model.  The SPMetal.exe is the tool which helps in generating the Model classes.

Although we can create the Model classes manually, it will be a tedious job and error prone.  Using SPMetal would be the right approach to model classes.

Activities

Following are the activities performed in this article:

1.      Manager List Creation

2.      Entity Creation

3.      Read using LINQ

4.      Insert Entity

5.      Update Entity

6.      Delete Entity

 

 

Experimenting with LINQ and SPMetal

To start with create a custom list inheriting from Custom List and name it as Manager.  Add the following custom columns and data:

image

Generating the Entity Models

Now we can generate the Entity Model for the above List.

You can get the SPMetal.exe inside the following folder:

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

Open a command prompt and go to the specified folder:

image

Now run the following command:

            SPMetal.exe /web:http://YOURSITE /code:SiteEntities.cs

(remember: no spaces before / after the colon(:))

Wait for a while and you will be ready with the new file.  Open the file SiteEntities and you can see the Manager class is contained inside.

image

Create Application

Create a new SharePoint > 2010 > Console Application (targeting .Net 3.5 framework) and add the SiteEntities.cs file into it.

image

Add reference to the following assembly:

image

You can try with the following operations Read, Insert, Update, Delete using LINQ to SharePoint

 

Selecting an Item

Now we are trying to select the managers with country as USA:

using (SiteEntitiesDataContext context = new SiteEntitiesDataContext(http://appes-pc&#8221;))

{

    var result = context.Manager.Where(m => m.Country == “USA”);

 

    foreach (ManagerItem manager in result)

    {

        Console.WriteLine(manager.Name);

    }

}

 

Note: You can use LINQ or Lambda Expression to do the query.  In the above example I have used Lambda.

On executing the application you can see the following results.

image

Inserting an Item

For inserting a new item into the Manager list, use the following code:

using (SiteEntitiesDataContext context = new SiteEntitiesDataContext(http://appes-pc&#8221;))

{

    ManagerItem manager = new ManagerItem();

    manager.Name = “New Manager”;

    manager.Address = “New Address”;

    manager.Country = “New Country”;

 

    context.Manager.InsertOnSubmit(manager);

    context.SubmitChanges();

}

 

After executing the application, open the Manager list inside SharePoint as shown below:

image

Updating an Item

For updating an item inside SharePoint use the following code:

using (SiteEntitiesDataContext context = new SiteEntitiesDataContext(http://appes-pc&#8221;))

{

    ManagerItem manager = context.Manager.Where(m => 

                          string.IsNullOrEmpty(m.Title)).FirstOrDefault();

    if (manager != null)

        manager.Title = “New Title”;

 

    context.SubmitChanges();

}

You can see the updated entity inside SharePoint:

image

Deleting an Item

For deleting an item inside SharePoint use the following code:

using (SiteEntitiesDataContext context = new SiteEntitiesDataContext(http://appes-pc&#8221;))

{

    ManagerItem manager = context.Manager.Where(m => m.Title.Length > 3).FirstOrDefault();

    if (manager != null)

        context.Manager.DeleteOnSubmit(manager);

 

    context.SubmitChanges();

}

 

You can see that the item is deleted inside SharePoint:

image

This concludes our Read, Insert, Update, Delete operations using LINQ to SharePoint.  Hope the topics are understood by the reader.

References

            http://msdn.microsoft.com/en-us/library/ee535491.aspx

            http://msdn.microsoft.com/en-us/library/ee538255.aspx

Summary

In this article we have explored LINQ and SPMetal tool.  This information is necessary in the real world programming scenarios.  The attachment contains the source code we discussed.

Posted in C# | Tagged: , | Leave a Comment »

SharePoint 2010 – Connected WebParts

Posted by Paul on June 14, 2012

In this article we can explore Connected Web Parts which is an advance SharePoint Web Part feature. The connected web parts denote communication between 2 web parts.

clip_image002

The connected web part resolves the following requirements:

· Master Web Part and Slave web part data exchange

· Data Selection and Data Display web part communication

Summary of the application is:

· There are 2 web parts

· Web Part 1 has a drop down list for selecting Car

· Web Part 2 displays the car picture based on selection

Steps Involved

Following are the steps involved in creating connected web parts:

1. Create Project

2. Create Communication Interface

3. Create Web Part 1 (Provider) implementing Interface

4. Create Web Part 2 (Consumer)

5. Build and Deploy

Create Project

We can experiment with a Car showcase application where there are 2 web parts.

· The first web part allows selecting a Car from the drop down list.

· The second web part displays the image of the car.

For starting with create a new Web Part project inside Visual Studio.

clip_image004

Remove the default VisualWebPart1 web part. We will be adding our own web parts.

Create Interface

For communication between the 2 web parts we need to create an interface. Please create the following interface, which returns the selected Car name:

public interface ICar

{

string Car { get; }

}

Create Provider Web Part implementing Interface

Now you can create a new web part named CarSelectionWebPart. Expand the webpart item and Inside the User Control (CarSelectionWebPartUserControl.ascx) class file:

1. Add a drop down list control

2. Place the following code

public partial class CarSelectionWebPartUserControl : UserControl

{

protected void Page_Load(object sender, EventArgs e)

{

if (!this.IsPostBack)

{

DropDownList1.Items.Clear();

DropDownList1.Items.Add("Camry");

DropDownList1.Items.Add("Figo");

DropDownList1.Items.Add("Diablo");

}

}

// Property to expose selected car outside

public string Car

{

get;

set;

}

// Set the Car property

protected void Button1_Click(object sender, EventArgs e)

{

if (DropDownList1.SelectedItem != null)

Car = DropDownList1.SelectedItem.Text;

}

}

Inside the CarSelectionWebPart.cs (web part class file) add the following code:

// Property to return the selected Car

public string Car

{

get

{

return (_control as CarSelectionWebPartUserControl).Car;

}

}

// Special Purpose Attribute to denote ICar interface is provided

[ConnectionProvider("Car")]

public ICar GetCar()

{

return this;

}

The ConnectionProvider attribute and the interface of the method denotes that this web part provides data for ICar interface. The Connection Provider also says that the name is Car (in string).

Create Consumer Web Part

Now we can create the consumer web part which will get the selected Car to display the car picture. Add a new web part and name it as CarDisplayWebPart. Place an image control on the user control of the web part. Inside the class view of user control add the following method.

// Set the image to url

public void SetImage(string car)

{

if (car == "Camry")

Image1.ImageUrl = "/_layouts/images/ConnectedWebParts/Camry.png";

else if (car == "Figo")

Image1.ImageUrl = "/_layouts/images/ConnectedWebParts/Figo.png";

else if (car == "Diablo")

Image1.ImageUrl = "/_layouts/images/ConnectedWebParts/Diablo.png";

}

Now add Images Mapped Folder and place 3 image files (Camry.png, Figo.png, Diablo.png) inside the folder as shown below:

clip_image006

Build and Deploy

Now build the project and use the Deploy command. Open the SharePoint site in edit mode and add the above 2 web parts into it. You are now ready with the following 2 web parts.

clip_image008

Set Connection

Use the context menu of CarDisplayWebPart to set the connection to provider web part.

clip_image010

Testing the Web Parts

Now stop editing the web page and refresh the site. Select a car from the first web part and the car picture is displayed on the second web part.

clip_image012

This concludes our article on Connected Web Parts creation.

Debugging the Web Parts

You can debug the application, by executing the project in Debug mode. Any break points set will get executed.

clip_image014

References

http://msdn.microsoft.com/en-us/library/ms469765.aspx

http://rtmgroupq8.com/en/add-image-to-sharepoint-visual-web-part

Summary

In this article we have explored the Connected Web Parts feature of SharePoint Web Parts. In real world scenarios there could be multiple web parts communicating with each other through connected web parts. SharePoint also supports AJAX enabled web parts which provide a better communication between web parts. The attachment contains the source code of the web parts we discussed.

Posted in C# | Tagged: , , | 4 Comments »

SharePoint 2010 – Connected WebParts

Posted by Paul on June 14, 2012

In this article we can explore Connected Web Parts which is an advance SharePoint Web Part feature. The connected web parts denote communication between 2 web parts.

clip_image002

The connected web part resolves the following requirements:

· Master Web Part and Slave web part data exchange

· Data Selection and Data Display web part communication

Summary of the application is:

· There are 2 web parts

· Web Part 1 has a drop down list for selecting Car

· Web Part 2 displays the car picture based on selection

Steps Involved

Following are the steps involved in creating connected web parts:

1. Create Project

2. Create Communication Interface

3. Create Web Part 1 (Provider) implementing Interface

4. Create Web Part 2 (Consumer)

5. Build and Deploy

Create Project

We can experiment with a Car showcase application where there are 2 web parts.

· The first web part allows selecting a Car from the drop down list.

· The second web part displays the image of the car.

For starting with create a new Web Part project inside Visual Studio.

clip_image004

Remove the default VisualWebPart1 web part. We will be adding our own web parts.

Create Interface

For communication between the 2 web parts we need to create an interface. Please create the following interface, which returns the selected Car name:

public interface ICar

{

string Car { get; }

}

Create Provider Web Part implementing Interface

Now you can create a new web part named CarSelectionWebPart. Expand the webpart item and Inside the User Control (CarSelectionWebPartUserControl.ascx) class file:

1. Add a drop down list control

2. Place the following code

public partial class CarSelectionWebPartUserControl : UserControl

{

protected void Page_Load(object sender, EventArgs e)

{

if (!this.IsPostBack)

{

DropDownList1.Items.Clear();

DropDownList1.Items.Add("Camry");

DropDownList1.Items.Add("Figo");

DropDownList1.Items.Add("Diablo");

}

}

// Property to expose selected car outside

public string Car

{

get;

set;

}

// Set the Car property

protected void Button1_Click(object sender, EventArgs e)

{

if (DropDownList1.SelectedItem != null)

Car = DropDownList1.SelectedItem.Text;

}

}

Inside the CarSelectionWebPart.cs (web part class file) add the following code:

// Property to return the selected Car

public string Car

{

get

{

return (_control as CarSelectionWebPartUserControl).Car;

}

}

// Special Purpose Attribute to denote ICar interface is provided

[ConnectionProvider("Car")]

public ICar GetCar()

{

return this;

}

The ConnectionProvider attribute and the interface of the method denotes that this web part provides data for ICar interface. The Connection Provider also says that the name is Car (in string).

Create Consumer Web Part

Now we can create the consumer web part which will get the selected Car to display the car picture. Add a new web part and name it as CarDisplayWebPart. Place an image control on the user control of the web part. Inside the class view of user control add the following method.

// Set the image to url

public void SetImage(string car)

{

if (car == "Camry")

Image1.ImageUrl = "/_layouts/images/ConnectedWebParts/Camry.png";

else if (car == "Figo")

Image1.ImageUrl = "/_layouts/images/ConnectedWebParts/Figo.png";

else if (car == "Diablo")

Image1.ImageUrl = "/_layouts/images/ConnectedWebParts/Diablo.png";

}

Now add Images Mapped Folder and place 3 image files (Camry.png, Figo.png, Diablo.png) inside the folder as shown below:

clip_image006

Build and Deploy

Now build the project and use the Deploy command. Open the SharePoint site in edit mode and add the above 2 web parts into it. You are now ready with the following 2 web parts.

clip_image008

Set Connection

Use the context menu of CarDisplayWebPart to set the connection to provider web part.

clip_image010

Testing the Web Parts

Now stop editing the web page and refresh the site. Select a car from the first web part and the car picture is displayed on the second web part.

clip_image012

This concludes our article on Connected Web Parts creation.

Debugging the Web Parts

You can debug the application, by executing the project in Debug mode. Any break points set will get executed.

clip_image014

References

http://msdn.microsoft.com/en-us/library/ms469765.aspx

http://rtmgroupq8.com/en/add-image-to-sharepoint-visual-web-part

Summary

In this article we have explored the Connected Web Parts feature of SharePoint Web Parts. In real world scenarios there could be multiple web parts communicating with each other through connected web parts. SharePoint also supports AJAX enabled web parts which provide a better communication between web parts. The attachment contains the source code of the web parts we discussed.

Posted in C# | Tagged: , , | 2 Comments »

SharePoint 2010 – More on Web Parts

Posted by Paul on June 13, 2012

In this article we can explore more features regarding Web Parts programming.

Images Mapped Folder

In real world scenario we need to locate an image file from the server web folder. We can use the Server.MapPath() pointing to the root (~). But this is not that easy with web parts as the web parts are not always deployed into the bin folder.

(While development the web part assembly is not placed inside the inetput folder)

We can deploy web part to Solution Gallery, Global Assembly Cache and the web application bin directory. For simplicity we can use the Images Mapped Folder to place the image files needed by the web part.

Creating Image File Loading Project

Now we can create a web part and experiment the image loading functionality. Create a new SharePoint > 2010 > Visual Web Part project.

clip_image002

Select the SharePoint default web site in the next dialog.

Create Images Mapped Folder

For adding image files we need to use a special mapped folder. Right click on the project and use the SharePoint Images Mapped Folder from the Add menu.

clip_image004

Copy an Image File inside the Folder

Now create an image file and paste inside the folder.

clip_image006

Create Image control to load the Image File

Double click to open the VisualWebPart1UserControl.asx.

clip_image008

Now place a button and image control on the web part user control.

On the button click event place the following code :

protected void Button1_Click(object sender, EventArgs e)

{

Image1.ImageUrl = "/_layouts/images/ImageFileInWebPart/Jellyfish.jpg";

}

Please note that the url starts with _layouts folder.

Execute the Web Part

Now you can execute the web part and it will get deployed to the site. Open a page in edit mode and use the Add Web Part option. Locate our new web part and add it to the page.

Try playing with the button click and you will be getting the image file displayed as shown below:

clip_image010

References

http://rtmgroupq8.com/en/add-image-to-sharepoint-visual-web-part

http://msdn.microsoft.com/en-us/library/cc768621.aspx

Summary

In this article we have explored more features regarding Web Parts. The Images mapping is an essential feature and will take extra time in real world development scenarios if we does not grasp the feature. The source code attached contains the examples we discussed.

Posted in C# | Tagged: , , | Leave a Comment »