Pages

Sunday, December 2, 2012

SharePoint 2013: Use CAML into REST request

You might wonder how to use CAML query in your SharePoint 2013 REST endpoints. Basically you can’t pass CAML into REST request (at least till date, there’s so documented approach published). However, REST by itself provides the querying feature which somehow covers almost all CAML querying features. I’ll try to explain today how you can convert your CAML into REST request.

Generate REST Request Url

First of all let’s play with a tool called LINQPad that will be used for REST request generation later from CAML.Let’s describe the process step by step.

  1. Download LINQPad: The tool that I’m going to use for generating REST request url can be downloaded from LINQPad site. So please download the tool and run it.
  2. Add Connection Provider: Once you run the tool click ‘Add Connection’ and then select ‘WCF Data Services (OData)’ data context provider as shown below:
    image
    Figure 1: Add WCF Data Connection
  3. Connect to SharePoint Server: In the connection page, select the url as http://server/_vti_bin/ListData.svc as shown below:
    image
    Figure 2: ListData WCF Connection
  4. Built-in Query Option: Use built-in template for querying as shown below. Right click on your list/library and use any built-in template you want.
    image
    Figure 3: Use built-in template for generating query
  5. Generate Query: Once you finish the query, execute it and click the ‘Request Log’ button to see the REST request generated as shown below:
     image
    Figure 4: C# query and REST request

For details REST operator you can use for SharePoint 2013 REST endpoint can be found at MSDN link under “Table 3. OData query operators”. For licensed version, LINQPad provides intellisense which really exciting feature.

 

Examples of C# query and corresponding REST URL

I’ve provided few basic examples of using the LINQPad tool to generate queries. For this example, let’s consider we have a product list with the following fields:

image

Figure 5: Sample product list

The following examples explains the C# query and it’s corresponding REST Url:

  • Select all products whose name contains ‘sharepoint’
    C# Qeury
    Product.Where (p => p.ProductName.ToLower().IndexOf("sharepoint")!=-1)
    ListData Url http://server/_vti_bin/ListData.svc/Product()?$filter=indexof(tolower(ProductName),'sharepoint') ne –1
    REST URL http://server/_api/web/lists/getbytitle(‘Product’)?$filter=indexof(tolower(ProductName),'sharepoint') ne –1
    So the summary is that the filter is “$filter=indexof(tolower(ProductName),'sharepoint') ne –1
  • Select all products created on 10-Oct-2012
    C# Qeury
    Product.Where (p => p.Created.Value.Day==10 & p.Created.Value.Month==10 & p.Created.Value.Year==2012) 
    ListData Url http://server/_vti_bin/ListData.svc/Product()?$filter=((day(Created) eq 10) and (month(Created) eq 10)) and (year(Created) eq 2012)
    REST URL http://server/_api/web/lists/getbytitle(‘Product’)?$filter=((day(Created) eq 10) and (month(Created) eq 10)) and (year(Created) eq 2012)
      So the filter is “$filter=((day(Created) eq 10) and (month(Created) eq 10)) and (year(Created) eq 2012)

    As shown above two examples, you can find out more by yourself by using the LinqPad and the MSDN function references.

     

    Convert CAML to REST Url

    Now let’s consider you have an CAML XML as shown below which returns all items from a list whose title contains ‘sharepoint’ and takes first 10 items.

    <Where> 
       <Contains> 
          <FieldRef Name='Title' /> 
          <Value Type='Text'>sharepoint</Value> 
       </Contains> 
    </Where> 
    <QueryOptions> 
       <RowLimit>10</RowLimit> 
    </QueryOptions>

    Now using LINQPad, we can convert the CAML to REST url as described below:

    image

    So the final REST Url will be http://server/_vti_bin/ListData.svc/Product()?$filter=indexof(tolower(ProductName),'sharepoint') ne -1&$top=10

     

    Conclusion

    Using a combination of LINQPad, OData query operators at MSDN link and CAML query at your hand, you can generate proper REST URL to be used. So if you have a CAML query at your hand, with a little time investment you can generate corresponding REST URL with filters and select parameters.

    Tuesday, November 27, 2012

    SharePoint 2013: Debug your SharePoint App

    In SharePoint 2013 app development, you need to run the app from visual studio to debug. However as you debug and you need to make some changes in html or JavaScript, you might wonder that you need to stop debugging, make changes and redeploy the app again. But there’s simplest solution exists.

    Unproductive Approach

    You might be aware of the following steps which might take long time to debug and make changes:

    1. Run the app from Visual Studio in debug mode (with F5).
    2. Debug your JavaScript and you’ve found you need to make changes
    3. Stop the debug and make changes
    4. Rerun the app from Visual Studio with F5

    But there’s simplest approach exists for debugging as described next.

     

    Productive Approach

    You may not know that you don’t need to stop debugging to make changes. You can make changes while the app is running and then refresh the page in the browser. You will get your changes on refreshing/reloading the page. So the new steps are:

    1. Run the app from Visual Studio in debug mode (with F5).
    2. Debug your javascript and you’ve found you need to make changes
    3. Make those changes in Visual Studio without stopping the app.
    4. Refresh the page in Browser, you will get the changes (HTML, JavaScript) immediately.

     

    Conclusion

    Using the second (productive approach) approach, you can develop and debug faster. However, if you make any setting changes like feature changes or appmanifest changes, you need to stop debugging and rerun again.

    Sunday, October 28, 2012

    SharePoint 2013: Start Developing Apps

    SharePoint 2013 introduced new concept of ‘SharePoint apps’. Apart from Server Object Model, you can now user Client Object Model or REST API to develop SharePoint Apps. For developing apps, you don’t need to install SharePoint in your development pc. You can develop SharePoint apps in client Operating System like Windows 7or Windows 8. If you have not already started developing apps for SharePoint, this post might help you in getting started. To develop apps you need combination of two setups.
    • Development Environment: where you install visual studio for developing apps. For your information for developing SharePoint apps you don’t need a SharePoint server. You can develop apps in your windows 7/8 environment.
    • Deployment Environment: where you can run your apps for testing/debugging. Surely this will be a SharePoint system.

    Based on the development and deployment environment integration, there are two ways you can setup your apps development environment:
    On-Premises Development Environment

    In this setup, you install the development and deployment in the same server. This is kind of manual process of setting up your SharePoint server to work as apps hosting server. I would not like to recommend you for this setup unless you have a specific reason. You can find more details on how to setup your on-premises development environment by following the MSDN link on ‘How to: Set up an on-premises development environment for apps for SharePoint’. The concept is shown below:
    image
    Figure 1: On-Premises setup

    Basically in he on-premises setup, you develop your own SharePoint server and then prepare it for publishing hub for SharePoint apps. You will develop apps in your development pc and then deploy in the on-premises SharePoint server.

     

    Office 365 based development Environment
    In this setup the development environment is on-premises but the deployment environment is office 365. You can get your own deployment environment by signing up for office 365 developer site. You can find details on how to sign up for office 365 developer site from MSDN ‘Sign Up for an Office 365 Developer Site’. The concept of this environment is shown below:

     image
    Figure 2: Office 365 developer setup

    In the Office 365 development environment setup, you will develop in your own pc and then deploy in Office 365 developer site to test/debug. Once you are done with your development and want to publish it, you can do so by publishing in the office app market.

     


    Step by Step Instructions on Setting up Office 365 based Development Environment

    You can find more details of how to setup the development environment from the link ‘Get Started developing apps for SharePoint’. But I’ve put the details below, in more precise steps:

    image
    Figure 3: Office 365 admin center
    • Step 4: Now you will be landed to the SharePoint developer site and from the site click the tile ‘Get tools to build apps’ as shown below:
    image
    Figure 4: SharePoint developer site in Office 365 preview
    • Step 5: On the details page install ‘Napa – office 365 developer tools’.
    • Step 6: Once installation is finished, click ‘Site contents’ from left side and then launch the app “Napa – office 365 developer tools’ by clicking as shown below:
    image
    Figure 5: Launch ‘Napa developer tools’ from Site contents
    • Step 7: Once the app launches, you can add the new SharePoint app project by clicking link’ Add New Project’ as shown below:
    image
    Figure 6: Napa apps – home page
    • Step 8: Once the project created you will be provided in-browser IDE like development environment. However you can lunch the project in Visual Studio by clicking the icon ‘Open in Visual Studio’ as shown below. This will install necessary tools to run the project.
    image
    Figure 7: Open in Visual studio link
    Finally Microsoft Web Platform Installer will run and install every required components to run the app. After the installation is done, you can deploy your app in Office 365 developer site. Just run your app from visual Studio by pressing F5, which will install the app before running and as soon as you stop debugging, the app will be uninstalled.

    Conclusion

    Setting up on-premises development environment requires manual configuration and might be time consuming. But setting up Office 365 based development environment is much easier and you can get it ready within 15-30 minutes. So I would recommend you to go for this Office 365 based setup to start learning how to develop apps. Once you are confident with the apps development you can also try to setup on-premises development environment.

    Sunday, October 14, 2012

    SharePoint: Manipulate Audience Programmatically

    Audience is a nice feature in SharePoint but only available in MOSS/SharePoint Server. Generally speaking, Audience is group of users that can be used to target contents. The class ‘Microsoft.Office.Server.Audience.AudienceManager’ is the main entry point for accessing Audience feature in SharePoint. Audience values are of three different types which are separated by ‘;;’:

    • Global audience represented by GUIDs. Multiple global audience values are separated by commas.
    • Distinguished names represented by Fully Qualified Domain Name. Multiple distinguished names are separated by ‘\r\n’.
    • SharePoint Group IDs. Multiple sharepoint groups are separated by commas.

    An example of audience field value is given below:

    A88B9DCB-5B82-41E4-8A19-17672F307B95, B88B9DCB-5B82-41E4-8A19-17672F307B95 ;; cn=all developers,ou=distribution lists,dc=redmond,dc=corp,dc=microsoft,dc=com \r\n cn=all testers,ou=distribution lists,dc=redmond,dc=corp,dc=microsoft,dc=com \r\n ;; 1,12,21,37

    I’ve found many times that people are manipulating these audience field values manually by parsing the text. However there’s SharePoint server object model support to manipulate Audience field programmatically.

    Find Audience Field in List/Library

    Audience field is of type ‘Microsoft.Office.Server.WebControls.FieldTypes.SPFieldTargetTo’. You can find out the field types from list fields’ as shown below (using any of the two described):

    var audienceFields = list.Fields.OfType<Microsoft.Office.Server.WebControls.FieldTypes.SPFieldTargetTo>();

    //Alternatively you can use the following code snippet also:
    foreach (SPField field in list.Fields)
    {
    if (field is SPFieldTargetTo)
    {
    //found audience field
    }
    }

    Code 1: Get Audience fields

     

    Read/Parse Audience Values

    You can manipulate the audience values as shown below. To read value from a list/library audience field, pass the value in the AudienceManager.GetAudienceIDsFromText method. The method will parse the audience field value and populate three out variables: Global Audience, Distinguished Name and SharePoint Group.

    string[] globalAudienceIds;
    string[] distinguisedNames;
    string[] sharepointGroupNames;

    var audienceFieldValue = listItem["AudienceField"] == null ? string.Empty : listItem["AudienceField"].ToString();
    AudienceManager.GetAudienceIDsFromText(audienceFieldValue, out globalAudienceIds, out distinguisedNames, out sharepointGroupNames);

    Code 2: Read Audience Field values

     

    Once you have the global audience values you can get three different types of audience-details as shown below:

    var audienceManager = new AudienceManager(ServerContext.GetContext(SPContext.Current.Site));
    //get global audience
    Audience globalaudience = audienceManager.GetAudience(globalAudienceGuid);
    //get distinguished name audience
    Audience distinguisedNameAudience = audienceManager.GetAudience(distinguisedName);
    //get sharepoint group audience
    SPGroup sharepointGroupAudience = web.SiteGroups.GetByID(sharepointGroupId);

    Code 3: Get audience based on audience id or name

    If you have global audience id (which is valid guid), please convert the guid string to GUID type variable and then pass in the GetAudience method.

     

    Update Audience Field Value

    To update audience field value programmatically you need to use following code snippet. You need pass the global audience IDs, distinguished names and sharepoint group names to Audience Manager’s GetAudienceIDsAsText method which will combine the values as text to save in audience field.

    listItem["AudienceField"] = AudienceManager.GetAudienceIDsAsText(globalAudienceIds, distinguisedNames, sharepointGroupNames);

    Useful links

    The following links might be useful for you to read.

    Saturday, October 6, 2012

    SharePoint 2013: App Concept

    Introduction

    SharePoint 2013 has added a bunch of new concepts for apps. You can think of a SharePoint app just like iPhone app or Android app for time being. If you have not already setup the on-premises development environment for SharePoint 2013 apps development, please follow the link Set up an on-premises development environment for apps for SharePoint to setup your development environment.

     

    Install/Host an App

    You can install the app in a SharePoint web (called host web for the app). When you install an app in the SharePoint web (called host site), the app needs a place to exist  where app’s css, javascripts, pages etc will be placed. The app resources (like pages, css, javascript etc) are not stored/kept inside host web. Where the app’s resources are stored/kept basically depends on app’s hosting type. The app can be hosted in any of the followings:

    • inside SharePoint (called SharePoint hosted)
    • You can host app in Cloud. You have two options for cloud-hosting apps
      • Windows Azure (called AutoHosted)
      • Third-party solution providers can provide setup for apps (called Provider-hosted)

    You can get more details on this hosting options at MSD link.

     

    The app can add some links/actions (like ribbon, ECB menu etc) in the host web. But the app itself doesn’t live inside host site.  When you use SharePoint hosted option for an app and as soon as you install the app in a host web another web (usually subsite to host site) is created (called app web) for the app components to be installed. The relation to host and app web for SharePoint hosted app, is shown below:

    image

    Figure 1: SharePoint hosted Apps are usually installed under subsite of Host web

    For other options (like provider hosted and windows azure hosted app), app web is optional and the actual app web resources are stored in windows azure or third party servers.

    Though app webs are installed under subsite of host web usually, for SharePoint hosted app, it doesn’t mean you can access the app web directly with url. Rather the apps are only accessible from different url. The App web is accessible from different url (not like host-web url). This is to keep the app webs isolated from host web. Usually these two types of webs urls (host and app web) belongs to two different domains. You can find more details on this host web url and app web url from this MSDN link.

     

    App Types (From users’ points of view)

    Now question comes what types of apps we can develop and how they will look like from user’s point of view. You can do the following types of things with apps:

    UI Custom Actions

    An app can add links like ribbon, custom actions or ECB menu to the host web. When user will click on the link, user will be redirected to the app web. Let’s consider a scenario which will explain this UI custom actions in details:

    1. You installed an app (let’s call it SharePoint PDF Converter) in a SharePoint site http://mysite.mydomain.com/businessdocs (called host web). The app will add a ribbon button in the site to convert any word document to pdf. When you will install  the app ‘SharePoint PDF Converter’, a subsite will be created under host web (http://mysite.mydomain.com/businessdocs) and the app contents (like javascript, css, aspx pages etc) will be deployed in the subsite. As mentioned already app webs are not accessible by url (like http://mysite.mydomain.com/businessdocs/appwebname) directly, rather they have different url for isolation. The idea of adding ribbon button in host web shown below:image Figure 2: An app can add ribbon to the host web.
    2. Now what will happen on user will click the ribbon button? Usually user will be redirected to the app web and app developers have the option to pass the current selected item details (like id, url etc) to the app web. The concept of redirecting from host web to app web and having the app web taking control of the full browser page is called ‘Immersive Full Page’ user experience.

    You can get more details on custom action app types on MSDN link Create custom actions to deploy with apps for SharePoint.

     
    App Part

    Apps can also add web-part like stuffs in the host web called Part (or app part). You can think of an ‘app part’ as like web part but it’s provided by app web. You can think of it as just like web part but instead of Farm WSP solution this app part comes from app deployment to your host web. You can find more details on this app part on MSDN link Create app parts to deploy with apps for SharePoint. The following image shows an app part that is available to be added in the host site:

    image

    Figure 3: Add an app-part (just like adding webpart)

    Once you add the app-part the page will look like below which kind of resembles the webpart concept:

    image

    Figure 4: App part added to the page

     
    Immersive Full Page

    All apps have a default page which might take the full page. Apps show custom action or app part in the host web. The app might take the full page by redirecting user from host web url to app web. For example, the host web url is http://www.hostweb.com and an app is installed in the host web which adds a custom action. When user clicks the custom action, the user will be navigated to a new url (say, http://www.appweb.com). So the app takes the full page (so it’s called Immersive Full page). However user will not notice the url changes as the new app site will have the same UI look and feel. The idea of having the app web to have similar look and feel like host web is achieve thorough a new concept in SharePoint 2013 – called Chrome Control. Basically Chrome control is kind of adding few components (js,div element etc) in App web so that when user redirect from host web to app web, the chrome control retrieves css, js from host web and apply it in the app web on the fly. Also the chrome control create a SharePoint 2013 ribbon bar in the app site, so that user can navigate back to the hot web.You can get clear idea of chrome control watching this video.

    Sunday, August 12, 2012

    SharePoint: Too much customization is not good for health

    SharePoint allows developer/architect to customize it’s power in numerous ways. You can write event receivers, timer jobs, webparts, application pages and so on. But what I’ve found with my years of experience in working with SharePoint is that sometimes developers/architects make too much customization which is not good from maintenance point of view.

    If you are senior SharePoint developer or architect or you have the responsibility to design a solution for SharePoint, first focus on out-of-the-box way to solve the problems. If possible, try to compromise features talking to clients.

    Real world Example

    Let’s consider a simple example. You have a database which is used by other LOB systems. SharePoint reads and writes data to the database and then other LOB systems (like SAP or some custom applications) use (only read) the data in the database for it’s own use.

    image

    Now client requirement is to show the data in the database as SharePoint list so that clients get the feelings that the tables in the database are kind of List in the SharePoint. Now what options do you have? I think we have two options:

    • Option 1: Use Business Connectivity Service to show Database tables as SharePoint list
    • Option 2: Create custom SharePoint list and then write event receivers to synchronize data between database and List.

    Different architect/developer under different circumstances, may use first option or second. But the first option is more out-of-the-box way of implementing the requirements. However some situations demand the second option where you need to  write custom code and need to sync data between SharePoint list and table in database manually. So as an architect/developer I would prefer the first option using Business Connectivity Service. If I need to choose second option then I should have explanation why I need to use second option. The explanation might be Business Connectivity Service has some limitations that we need to overcome with second option, or the requirements are too complex to implement with Business Connectivity Service.

     

    But Why?

    Now you may ask why it’s matter if I do more customization (I would prefer to say unnecessary customization). I bet it’s matter. The more customization you do, the more difficult to manage codebase, more time to develop, more possible to generate more bugs, more difficult to upgrade to newer version of SharePoint and many more. SharePoint is a rich application framework and we need to utilize it in best possible ways.

     

    conclusion

    The idea I wanted to share here not to say that you should not do any customization rather make sure your customization really needed. If you do unnecessary customization then you might paving the way for more customizations (maybe for error fixing or features related to customizations). As I read somewhere, “A single bad developer creates job for more developers”. Let’s not create more customizations by an unnecessary customizations.

    Saturday, June 16, 2012

    SharePoint: Package your external dependencies to another solution

    Sometimes we use some third party tools that create external dependencies to our SharePoint projects. For example if you use Pattern and Practice SharePoint Guidance Library in your SharePoint project in visual studio and build WSP, then  WSP package will include these SharePoint Guidance libraries also. However, this might create problems related to deployment. To explain the issue, let’s consider how SharePoint solution retraction/removal might affects other WSP package deployed in the same SharePoint environment.

     

    Scenario: Two WSPs sharing Common Dependency

    Let’s consider you have two Visual studio SharePoint project: SharePoint Project 1 and SharePoint Project 2. Both projects are using (i.e., referencing) a third party dll (i.e., thirdparty.dll). Now if you generate WSP from two different Visual Studio projects, both WSP will include the thirdparty.dll in their WSP package.

    image

    Figure 1: A single thirdparty.dll is shared by two WSP solutions

     

    As shown in the image above, a single third party dll is referenced by two Visual studio SharePoint projects. Now when you 'will build two different WSP solutions the same third party dll will be included to two different WSPs. If these two WSPs are deployed in a single SharePoint server/farm with GAC deployment, then both WSP will deploy the same ThirdParty.dll in the GAC. Everything will work fine till now.

     

    Problem: retracting/removing one solution will fail other WSP to work

    Now consider a scenario. After deploying the two WSPs in the production with GAC deployment, you have found a problem with Project 2 WSP. So you want to remove the Project 2 WSP while you will keep Project 1 WSP. So you will remove the Project 2 WSP. Removing the Project 2 WSP will remove all the assemblies from GAC/BIN related to the WSP. So removing the Project 2 WSP will remove thirdparty.dll from GAC. As soon as you remove the Project 2 WSP from SharePoint server/farm, Project 1 WSP will fail to work as it’ll not find the referenced thirdparty.dll in GAC. So removing Project 1 WSP (or project 2 WSP) will remove the thirdparty.dll from GAC and other WSPs which are using the same dll will fail to work.

     

    Solution: Package your external dependency to new WSP

    The solution to this problem is to exclude thirdparty.dll from both WSPs and create a new WSP dependency/prerequisite solution for thirdparty.dll. You can do it easily with SharePoint 2010 Package editor. As a result the thridparty.dll will not be included in any of the two WSPs.To package a new WSP for the thirdparty.dll you need to create another new Visual Studio SharePoint projects which will just include the thirdparty.dll (or any other prerequisites). The new architecture is shown below:

    image

    Figure 2: Shared thirdparty.dll is included in separate WSP

     

    As shown in the figure 2, now the shared dll (thirdparty.dll) is excluded from Project 1 and Project 2 WSP. Whether you use WSPBuilder or SharePoint 2010 project template in Visual studio, you can exclude one more dlls from the WSP. Then create a new Visual Studio project (WSPBuilder or SharePoint) which will include the thirdparty.dll and the output WSP package will include the shared/external dll. Now you will have three WSPs and the new WSP will be prerequisite WSP for other two WSPs.

    Now with this model, you can remove Project 1 WSP or Project 2 WSP from your server without affecting each other. Even if you remove Project 1 WSP from the Farm/Server, the thirdparty.dll will not be removed from GAC as it’s not deployed as part of Project 1 WSP. Later if you want to redeploy the Project 1 WSP again then you don’t need to redeploy the prerequisite WSP as it’s already deployed in the server. If needed you can package your external dependency in more than one WSP packages.

     

    Conclusion

    If you are developing a SharePoint custom product that will be deployed in some client’s environment, then you should care about creating one or more dependency WSP packages. If your SharePoint solution is developed for a specific client or as an in-house product then you might not face the problem even if you don’t create a prerequisite WSP package. However if you are developing a SharePoint solution as a custom product and you don’t know the client yet, you should create prerequisite WSP package. And then when you will deploy your product in client server, you can deploy the perquisite or not depending on if the client has the prerequisite dlls install or not. If the client has the dlls/prerequisites installed in the farm, you don’t need to deploy the prerequisite WSP. This will make your SharePoint product more independent and will have less impact on other SharePoint solution deployed in the farm.

    Thursday, May 17, 2012

    SharePoint Tips: Iterating through All the webs in the site

    Sometimes we need to process all webs in a site collection, as you want to do some quick fixes in the web. Few weeks back my manager asked me to do some fixes in the list items exists in all the webs in the site collection. There were about 30,000 webs in the site collection and I was looking for some kind of script that will be efficient. The usual way of looping through all webs might be using some recursive way, as shown below.

    //Starting point
    public void ProcessAllWeb(SPSite site)
    {
        using (var web = site.RootWeb)
        {
            ProcessWebRecursive(web);
        }
    
    }
    
    //Recursive method
    private static void ProcessWebRecursive(SPWeb web)
    {
        //do some processing
        //web.Lists["listName"].ItemCount
    
        foreach (SPWeb subWeb in web.Webs)
        {
            using (subWeb)
            {
                ProcessWebRecursive(subWeb);            
            }
        }
    
    }

    Code Snippet 1: Recursive way of processing all webs in the site collection (Not optimized)

    In the recursive way of processing all webs, there will be more than one SPWeb instance alive in memory. In the above code snippet, when the method ProcessAllWeb is invoked it’ll call the recursive method ProcessWebRecursive. The recursive method will keep calling the subwebs while keeping the parent web alive.

     

    While I was writing the code, I was wonder if there’s any way of processing only one web non-recursively. So my intention was to open only one web in memory at once. And then I found it. You can get all web Url(including all subwebs at all level) using SPSite.AllWebs.Names. The following code snippet shows the efficient way of processing all webs in the site collection:

    public void ProcessAllWeb(SPSite site)
    {
        string[] allWebUrls = site.AllWebs.Names;
        foreach (string webUrl in allWebUrls)
        {
            using (SPWeb web = site.OpenWeb(webUrl))
            {
                //process web
            }
        }
    }

    Code Snippet 2: Process all webs one by one (Optimized for large number of webs)

    Using the code snippet shown in figure 2, you just open one web at a time in memory for processing. The trick here is ‘SPSite.AllWebs.Names’ which will return all the (I mean it!) subwebs (including children and their children and so on) as a result. If you have thousands of webs under a site collection (and if it’s production), you should care about performance issue.

    Thursday, May 3, 2012

    SharePoint Tips: List.ItemCount vs List.Items.Count

    If you need to know the total items in the list, how do you write code? The usual way to write code is shown below:
    var itemCount = list.Items.Count;
    Code Snippet 1: Usual (not suggested) way to get items count
    However this will fetch all the records from database and apply the count in memory.

    SharePoint object model provides an easiest way to find the items count without fetching all records and you can use the following code snippet to do so:
    var itemCount = list.ItemCount;
    Code Snippet 2: Suggested way to get items count

    Saturday, April 21, 2012

    SharePoint Tips: Object Mode provides Built-in Field and Content type Ids

    Sometimes we need to access SharePoint built-in fields from list. You may find code to access list item value as shown below:

    listItem["Title"] = "value";

    Code Snippet 1: Usual approach

     

    The title field is SharePoint built-in field and you don’t need to hard-code the field name . SharePoint Object Model provides a class ‘SPBuiltInFieldId'’ where you can find most of the SharePoint built-in field’s IDs. So you can write the above code snippet as shown below:

    listItem[SPBuiltInFieldId.Title] = "value";

    Code snippet 2: Suggested approach to access built-in fields

     

    The class ‘SPBuiltInFieldId’ also provides many built-in fields Ids like ‘created by’ (known as owner), modified by etc.

    Similarly you can get built-in content type Ids using the class ‘SPBuiltInContentTypeId’. I would recommend you to use these classes to access built-in fields and content types.