Saturday, June 18, 2011

LINQ with SharePoint 2010

Querying SharePoint

When we consider accessing data from SharePoint, there are many data technologies that we can use
according to the given context. Those technologies are Server Object Model, Client Object Model, LINQ,
REST & Web Services API.

If we are using SharePoint 2007, our data querying capability is limited to CAML(Collaborative Application
Markup Language) queries. CAML queries does to work by using SPQuery object.

There are several limitations, we have to face if we stick in to CAML queries.

1] There are no strongly typed objects
2] There is no syntax checking in CAML API (We can see if the query is correct at runtime only)
3] We have to use 3rd party tool like CAML Query Builder
4] It has no IntelliSense support at design time


SharePoint LINQ (SPLINQ)

You can find more information regarding LINQ from here

In order to minimize issues with CAML queries, Microsoft has introduced LINQ capabilities with SharePoint 2010
release. The LINQ provider translates the SPLINQ queries in to CAML and execute that in the server.
There are several advantage of using the LINQ provider for SharePoint

1] Queries are strongly typed
2] Compile time syntax checking
3] IntelliSense support at design time
4] It is easier to join multiple lists

The following section of the article will provide you with a step by step guide of using LINQ with SharePoint.

Step 1 – Add a reference to SharePoint LINQ provider

Make reference to Microsoft.SharePoint.Linq

Step 2 – Generate entity classes with SPMetal

Entity classes will be used as an abstraction layer where we can query in object oriented manner.
We can create entity classes on SharePoint objects (eg: SharePoint lists and other content types) by hand or
generate them by using a command line tool called SPMetal.

To generate entity classes using SPMetal, open the SharePoint Management shell and put following command.

   1: SPMetal.exe /web:http://sitecollection/ namespace:Infosense /code:SPLinq.cs

image_thumb1

After that include that class in to your project in visual studio

image_thumb3

Then add the SPLinq.cs file will be added to your project
image_thumb8

A section of the generated SPLinq.cs class is listed below

   1: public partial class SPLinqDataContext : Microsoft.SharePoint.Linq.DataContext {
   2:         
   3:         #region Extensibility Method Definitions
   4:         partial void OnCreated();
   5:         #endregion
   6:         
   7:         public SPLinqDataContext(string requestUrl) : 
   8:                 base(requestUrl) {
   9:             this.OnCreated();
  10:         }
  11:  
  12: /// <summary>
  13:         /// List to store application page permisions
  14:         /// </summary>
  15:         [Microsoft.SharePoint.Linq.ListAttribute(Name="PagePermissions")]
  16:         public Microsoft.SharePoint.Linq.EntityList<PagePermissionsItem> PagePermissions {
  17:             get {
  18:                 return this.GetList<PagePermissionsItem>("PagePermissions");
  19:             }
  20:         }
  21:  
  22: /// <summary>
  23:     /// Create a new list item.
  24:     /// </summary>
  25:     [Microsoft.SharePoint.Linq.ContentTypeAttribute(Name="Item", Id="0x01", List="PagePermissions")]
  26:     public partial class PagePermissionsItem : Item {
  27:         
  28:         private string _groupName;
  29:         
  30:         private string _pageName;
  31:         
  32:         private System.Nullable<bool> _viewPermission;
  33:         
  34:         private System.Nullable<bool> _fullPermission;
  35:         
  36:         #region Extensibility Method Definitions
  37:         partial void OnLoaded();
  38:         partial void OnValidate();
  39:         partial void OnCreated();
  40:         #endregion
  41:         
  42:         public PagePermissionsItem() {
  43:             this.OnCreated();
  44:         }


Step 3 – Querying SharePoint objects using the DataContext object

To query objects in SharePoint you have to have an instance of the created DataContext object. In this example
the name of the DataContext is SPLinqDataContext.
image_thumb17

You have to create an instance of SPLinqDataContext and use its methods.

You can use a code like following to query a list and filter data by using different where clause

   1: public List<ApplicationPagePermission> GetPagePermissionLevel(SPUser user, string page, List<string> myGroups)
   2:         {
   3:             using (SPLinqDataContext data = new SPLinqDataContext(SPContext.Current.Web.Url))
   4:             {
   5:                 EntityList<PagePermissionsItem> pagePerm = data.GetList<PagePermissionsItem>("PagePermissions");
   6:                 List<ApplicationPagePermission> appPagePermissionList = (from pp in pagePerm
   7:                                                                          where pp.PageName == page &&
   8:                                                                          myGroups.Contains(pp.GroupName)
   9:                                                                          select new ApplicationPagePermission
  10:                                                                          {
  11:                                                                              FullPermission = (bool)pp.FullPermission,
  12:                                                                              GroupName = pp.GroupName,
  13:                                                                              PageName = pp.PageName,
  14:                                                                              ViewPermission = (bool)pp.ViewPermission
  15:                                                                          }).ToList();
  16:  
  17:                 return appPagePermissionList;
  18:             }
  19:         }

Working with SPLINQ is very easy and user friendly . Although CAML query support and the SPQuery objects are
still supported in SharePoint 2010 , I will stick in to SPLINQ for sure Smile

What is LINQ ?

LINQ stands for Language Integrated Query,which was introduced with .Net framework 3.5.It is used to query data sources as strongly typed queries.It defines a set of Standard Query Operators that helps it to get data from different data sources, Query expressions, Lambda expressions and anonymous types.

There are few types of usage


LINQ to Object
LINQ to Objects allows to perform queries against arrays and in-memory data collections.
It is the IEnumerable<T> API for the Standard Query Operations.

LINQ to XML

Is the LINQ API for manipulating XML. Operations are available in System.Xml.Linq namespace.

LINQ to DataSet

Is the LINQ API for DataSets.

LINQ to SQL

Is the IQueryable<T> API that allows LINQ queries to work with Microsoft SQL Server database.
System.Data.Linq namespace will be required

LINQ to Entities

Is the alternate LINQ API used to query a database. It decouples the entity object model from the
physical database by creating a logical mapping between the database and objects.

Saturday, April 9, 2011

InfoPath 2010–resolving “There has been an error while processing the form” error

I got this error message when submitting my InfoPath 2010 form via web browser. But it worked pretty fine when I submit the same form through the InfoPath filler.

image

In my form there were several text box controls and a rich text box. In my SharePoint error logs I found the following entry that lead me to the correct path

There was a form postback error. (User: Domain\spadmin, Form Name:
Cash Advance Chit,IP:,Request: http://domain.com/sites/workflow/Page.aspx,
Form ID: urn:schemas-microsoft-com:office:infopath:Cash-Advance-Chit
:-myXSD-2011-02-18T03-28-33, Type: InvalidCastException, Exception Message:
Unable to cast COM object of type 'HTMLCHECKERLib.XMLPProcessorClass'
to interface type 'HTMLCHECKERLib.IHTMLtoXHTML'. This operation failed
because the QueryInterface call on the COM component for the interface with
IID '{A260B372-BC78-441B-8764-D0B83F4004F4}' failed due to the following
error: No such interface supported (Exception from HRESULT: 0x80004002
(E_NOINTERFACE)).)


It states that the error has occurred due to a form postback. So it should’ve caused by the rich text box, because when moving focus from the rich text box automatically causes a postback to the server. I did some research on that issue where some experts mentioned that this error may have occurred due to issues with the InfoPath installation. This suggestion was reasonable to me because the same form submitted fine when I used in the staging environment. the issue occurred only in the production environment. So I completely uninstalled InfoPath and reinstalled it.. but with no luck !! the error appears in the same way.

Finally I managed to get hold with the problem. A dll required for the operation hasn’t registered in the registry. the culprit was “htmlchkr.dll” (Microsoft Markup Analysis Processor). By executing the following command I managed to resolve the problem.

regsvr32 "C:\Program Files\Common Files\Microsoft Shared\OFFICE14\htmlchkr.dll"

That dll ruined few days of my life Smile

Tuesday, April 5, 2011

ASP.Net Session State in SharePoint 2010

Although we have State Service service application running in our SharePoint farm, it doesn’t mean that it directly support ASP.Net session state. State service is more towards facilitating session information for office internal components such as InfoPath form services, Visio services, etc.…

If we need to maintain ASP.Net session state for SharePoint 2010 pages we have to enable it manually. Recently I wanted to enable ASP.Net sessions in one of my Visual Web Parts.

There are two ways that you can use to enable ASP.Net sessions.

1] Using PowerShell command

Use following command to enable the ASP.Net session state service

Enable-SPSessionStateService –DefaultProvision

After that you can see a new service application “SharePoint Server ASP.Net Session State Service” running in the service application section

image

that’s all !!

2] Session State Managed module using IIS Manager

You have to use this method if you are using SharePoint Foundation. You can use this for SharePoint 2010 Server versions also. but you will not get a separate service application. For SharePoint 2010 server versions, recommended best practice is to use the 1st method which is to use PowerShell command.

First we have to modify few settings in the web.config file of the respective SharePoint 2010 web application

<pages enableSessionState="true" …… >

Then add session state module within system.web section

<httpModules>
<
add name="Session" type="System.Web.SessionState.SessionStateModule" />
</
httpModules>

After that we have to add the Session state module in IIS7 for the web application.

Go to IIS Manager, select the relevant SharePoint web application and open the Modules section

image

Inside the modules section click on Add managed module link to add the Session State module

image

Input a name for the module and select following for the module type from the dropdown


System.Web.SessionState.SessionStateModule,System.Web,Version=2.0.0.0,
Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a

image

That’s it !!. now you can use ASP.Net Sessions in your SharePoint 2010 pages

Friday, April 1, 2011

Presentation-Introduction to Excel Services 2010

Sri Lanka SharePoint forum March 2011 offline meeting happened on Wednesday 9th of March. Seminda Rajapaksha did the first session on Introduction to SharePoint 2010. He described history,features and carrier opportunities of SharePoint.

SharePoint-Forum-March-2011-Ofline-Session

I did the second session on Introduction to Excel Services 2010. I described about features of Excel Services, architecture of the excel services and presented few demos. from the following links you can access the presentation and a demo that accesses the Excel Web Service (EWS) which is a component of Excel Web Services 2010.

Excel Web Service Demo

Any comment on this session will be greatly appreciated.

Friday, January 28, 2011

Presentation–Lap Around VSTS 2010

Following is a presentation I did at Technology update EPG developers conducted by Microsoft

Friday, January 7, 2011

Presentation – WCF Duplex Services

My first ever .Net Forum session was on 6th of January 2011. I would like to thank all who participated for that session. I appreciate the support given by Prabath and Wellinton for providing me with this opportunity. Finally I like to extend my gratitude to my team mates at IronOne technologies and my batchmates at UCSC for the encouragement.

1

IMG_0166IMG_0167 IMG_0168 IMG_0169

I hope you would encourage me with comments :)