Showing posts with label Object Model. Show all posts
Showing posts with label Object Model. Show all posts

Friday, December 10, 2010

Working with SPQuery

As a sharepoint developer most of the people might have used SPQuery and CAML atleast once.

Writing a Basic Query

SPContext ctx = SPContext.Current;
using (SPSite site = new SPSite(ctx.Site.ID))
{
      using (SPWeb web = site.OpenWeb(webid))
      {
         SPList list = web.Lists["MyTestList];
         SPQuery query = new SPQuery();
         //You have to call GetItems function of SPlist to execute the CAML query
         SPListItemCollection items = list.GetItems(query);      
      }
}

Here it will return All the Items.But in real time we need to specify the conditions and attributes to fine tune the Results. We need to have basic understanding of CAML syntax inorder to take full advantage of SPQuery Object.If you have a CAMLBuilder tool then it will be always handy in writing CAML queries.You could douwnload CAML builder from here

Understanding SPQuery Properties

1. SPQuery.RowLimit
   This Property allows you to set how many rows you need in your result.Its quiet common that your Query could return more than 500 rows so its better to limit the number of rows in a result and use paging to retrive the rest of the result.I will explain paging below.

2. spquery.ViewAttributes

View attribute is one of the important attribute which is veryusefull to set how you are going to retrieve the Data.
  Scenario 1: You want retrieve all the items including items in folder and subfolders then set it like the following

 //If you want to return only file
          SPQuery.ViewAttributes = "Scope='Recursive'";   //If you want to return All items
          SPQuery.ViewAttributes = "Scope='RecursiveAll'";

  Scenerio 2 : You want retrive only files
          spquery.ViewAttributes = "Scope=\"FilesOnly\"";

  Scenario 3: Only Approved Items
         spquery.ViewAttributes = "ModerationType='HideUnapproved'"

3. SPQuery.Folder
   This property is usefull when you want to retrieve the data only from specific folder.In real world scenario you need to retrive the items from specific folder rather than retrieving all items in the list.
    SPQuery.Folder = folder; //It should be a SPFolder Object

 4.SPQuery.ViewFields
This property helps to set which are the fields /columns you want in the result.There is no point in returning all the coloumns.So its better practice to specify the fields you want to return.

     //Name is the coloumn name / internal name of the field
     SPQuery.ViewFields = "";

5. SPQuery.Query

This property used to set the real CAML query.Build your CAML string and assign to this property.

SPQuery.Query = String.Format("<Where>
                                                           <Eq>
                                                              <FieldRef Name=\'FileLeafRef\'/>
                                                              <Value Type=\"Text\"></Value>
                                                        </Eq>
                                                  </Where>", searchText);

//searchText is name of the file you want to search

Note : One thing here we have to remember is no need to add query tag in your XML.

If you are using Date time in your query then set includetimevalue = true. See Below

Query = "<Where><Eq><FieldRef Name='Modified'/><Value Type='DateTime' IncludeTimeValue='TRUE'>"+ LastCheckedDate + "</Value></Eq>
</Where>"

CAML Notations


•Eq = equal to
•Neq = not equal to
•BeginsWith = begins with
•Contains = contains
•Lt = less than
•Leq = less than or equal to
•Gt = greater than
•Geq = greater than or equal to
•IsNull = is null
•IsNotNull = is not null


Paging In SPQuery

Using paging with SPQuery is good practice.Its better to write code that will perform efficient way than giving bad user experience.

      using (SPSite site = new SPSite(SiteCollectionURL))
         {
                 
           using (SPWeb web = site.OpenWeb(WebName))
             {

              
               SPQuery query = new SPQuery();
               query.ViewAttributes = "Scope=\"Recursive\"";
               query.Folder = list.RootFolder;


               do
               {

                   SPListItemCollection listItems = list.GetItems(query);
                  
                 
//Perform the operations you want
                   query.ListItemCollectionPosition = listItems.ListItemCollectionPosition;
                 
//If you are showing in a grid view then stor the listItems.ListItemCollectionPosition in
                  viewstate or something like that
               } while (query.ListItemCollectionPosition != null);
             }
         }


Limitation of SPQuery Object
You cannot use the SPquery object to query across multiple site collection instead use SPSiteDataQuery

Friday, December 3, 2010

Minimal Permission required to execute the code in Sharepoint

I always faced the access permission issue in consuming the Sharepoint object model from a exe or webservice or windows service with a user who have limited access.Each time i figured out the permission required then forget blog it so all the time i have to Dig again to find the permission.So let see what should we do in each type of application.

User Permission
SharePoint SiteMinimum Read Permission
Sharepoint ServerAdd to WSS_ADMIN_WPG group
DatabaseSharepoint Content DB (Site collection database) - db_owner permission
Sharepoint Config DB (Config DB of sharepoint installation) - - db_owner permission

Web Service / WCF Service
Most of  sharepoint developers could have created a webservice/wcf service which uses sharepoint object model to do some operation in a sharepoint site.

Error
The Web application at http://localhost/mysite/content could not be found. Verify that you have typed the URL correctly. If the URL should be serving existing content, the system administrator may need to add a new request URL mapping to the intended application.

We are bound to solve the issue within time limit so forced to use the same application pool identity used by the Sharepoint Site and leave the issue behind.But if you want to know more about what should be the permission required for the user look at the table below.Make sure you application pool identity user have following preveleges.

Sharepoint Site
Add the IIS Application Identity user to Sharepoint Read Group in Sharepoint Site (minimal permission).If you need to do write operation or content type changes give the higher permissio to the user (Content Owner).This is to make sure that

SharePoint Server
Add the IIS Application Pool Identity User into WSS_ADMIN_WPG User Group of the physical server where Sharepoint is installed.

Database Server
IIS Application Pool Identity User should have DB_OWNER access in Sharepoint Configuration DataBase (Configuration DB created during the installation of sharepoint farm) and Sharepoint Content DataBase(Sharepoint Site Collection DataBase of the site you are trying to access).

Windows Service
In windows service case, the user account under which Window Service is running should have the similar access to application pool identity user case said above.

Sharepoint Site
Add the Window Service user account to Sharepoint Read Group in Sharepoint Site (minimal permission).If you need to do write operation or content type changes give the higher permissio to the user (Content Owner).This is to make sure that

SharePoint Server
Add the Window Service user account into WSS_ADMIN_WPG User Group of the physical server where Sharepoint is installed.

Database Server
Window Service user account should have DB_OWNER access in Sharepoint Configuration DataBase (Configuration DB created during the installation of sharepoint farm) and Sharepoint Content DataBase(Sharepoint Site Collection DataBase of the site you are trying to access).