52
Q. What Do you know about SharePoint Object Model? Ans. In Sharepoint Object model there are two Important namespaces. The Microsoft.Office.Server namespace is the root namespace of all Office Server objects and Microsoft.SharePoint is the root namespace for all WSS objects. Read More at SharePoint 2007 Object Model Q. Can you develop webparts and other SharePoint solutions at your local machine? Ans. In order to run and debug sharePoint solutions, the project must reside on the server which has Windows sharePoint services installed. However, you can reference theMicrosoft.SharePoint dll in your project at your local, but you won’t be able to run it. Q. How do you debug SharePoint Webparts? Ans. To debug SharePoint webpart (or any solution) you can simply drag and drop your complied .dll in GAC and recycle the app pool. You can also run upgrade solution command from stsadm. Q. How would you retrieve large number of Items form the list ? Ans. To retrieve large number of items with a better performance we can either use SPQuery or PortalSiteMapProvider Class (PortalSiteMapProvider is only available in MOSS). Read More with Examples Retrieving large number of Items from sharepoint list Q. How Do you implement Impersonation in ShrePoint. Ans. By Using RunWithElevatedPrivileges method provided by SPSecurity class. See e.g Impersonation in Sharepoint Q: What is the performance impact of RunWithElevatedPrivileges?

Share Point Interview

  • Upload
    bachpan

  • View
    127

  • Download
    1

Embed Size (px)

Citation preview

Page 1: Share Point Interview

Q. What Do you know about SharePoint Object Model?

Ans. In Sharepoint Object model there are two Important namespaces.

The Microsoft.Office.Server namespace is the root namespace of all Office Server objects and Microsoft.SharePoint is the root namespace for all WSS objects.Read More at SharePoint 2007 Object Model  

Q. Can you develop webparts and other SharePoint solutions at your local machine?

Ans. In order to run and debug sharePoint solutions, the project must reside on the server which has Windows sharePoint services installed. However, you can reference theMicrosoft.SharePoint dll in your project at your local, but you won’t be able to run it.

Q. How do you debug SharePoint Webparts?

Ans. To debug SharePoint webpart (or any solution) you can simply drag and drop your complied .dll in GAC and recycle the app pool. You can also run upgrade solution command from stsadm.

Q. How would you retrieve large number of Items form the list ?

Ans. To retrieve large number of items with a better performance we can either use SPQuery or PortalSiteMapProvider Class (PortalSiteMapProvider is only available in MOSS). Read More with ExamplesRetrieving large number of Items from sharepoint list

Q. How Do you implement Impersonation in ShrePoint. 

Ans. By Using RunWithElevatedPrivileges method provided by SPSecurity class.See e.g Impersonation in Sharepoint  

Q: What is the performance impact of RunWithElevatedPrivileges?

Ans. RunWithElevatedPrivileges creates a new thread with the App Pool's credentials, blocking your current thread until it finishes.

Q. How will you add Code behind to a Custom Applictaion Page or a Layout Page in SharePoint?

Ans. You do not deploy a code behind file with your custom Layouts page. Instead, you can

Page 2: Share Point Interview

have the page inherit from the complied dll of the solution to access the code behind.

Q. What is the difference between a Site Definition and a Site Template?

Ans. Site Definitions are stored on the hard drive of the SharePoint front end servers. They are used by the SharePoint application to generate the sites users can create. Site Templates are created by users as a copy of a site they have configured and modified so that they do not have to recreate lists, libraries, views and columns every time they need a new instance of a site.

Q. Why do you use Feature Receivers ?

Ans. Feature Receivers are used to execute any code on Activation\Deactivation of a Feature. You can use it for various purposes.

Q. Can you give a example where feature receivers are used.

Ans. You can use it to assign an event receiver feature to a specific type of list or can write a code in a feature receivers Deactivate method to remove a webpart from webpart gallery.

Q. Where do you deploy the additional files used in your webpart, like css or javascript files, and how do you use them in your WebPart?

Ans. You can deploy the css or javascript files in _layouts folder in SharePoint's 12 hive. To use them in your webpart, you need to first register them to your webpart page and then specify a virtual path for the file for e.g. _layouts\MyCSS.css See Code examples at Using External Javascript, CSS or Image File in a WebPart.  

Q: When should you dispose SPWeb and SPSite objects? 

Ans. According to the best Practices you should always dispose them if you have created them in your code. You can dispose them in Finally block or you can use the "Using" clause, so that they gets disposed when not required. If you are using SPContext then you need not dispose the spsite or spweb objects.

Q. What are the best practices for SharePoint development.

Ans. Some of the best practices are:

1. You should always dispose SPsite and SPWeb objects, once you refer them in your code. Using the "Using" clause is recommended.

Page 3: Share Point Interview

2. Use RunwithelevatePrivilages to avoid errors for end users.

3. Try writing your errors to SharePoint error logs (ULS Logs). Since it’s a bad idea to fill-up event log for your production environment.

4. Use SPQuery instead of foreach loop while retrieving Items from the list.

5. Deploy additional files used in your webpart to 12 hive. Use your solution package to drop the files in 12 hive. Also, make sure that all the references (for e.g. Css or .js files) get removed when the solution is retracted.Also See : Best Practices to Improve Site Performance

Q.What is the main difference between using SPListItem.Update() and SPListItem.SystemUpdate()?

Ans. Using SystemUpdate() will not create a new version and will also retain timestamps.

Q. When do you use SPSiteDataQuery ? 

Ans. You can use SPSiteDataQuery when you need to extract data from more than one list\library in your site colletcion. The data is extracted on the basis of the query you write and is returened as a Datatable. You can also specify the GUID for the lists\libraries you want to query against. 

Q. How do you create a Custom action for an item in a list ? 

Ans. This can be done by adding a new feature into SharePoint. You would need to use customaction tag in your elements.xml file and will have to set various properties like imageurl or UrlAction for your customaction. You can later add this feature into sharepoint using stsadm install feature command. 

Q. How would you bind this CustomAction to a specific list ? 

Ans. To do this you can either create a new list type(again a feature) and use the listtype number for the new list in your RegistrationType property of the Customaction. The CustomAction will then show up only for the items of this list type. or You can create a new content type and then use that content type's id in your cutsomaction to bind the custom action to items of just that content type. Add the new content type to the list where you need this customaction. 

Q. How will you deploy an existing asp.net webapplication or website in SharePoint? 

Ans. You would need to wrap the web application in a solution package in order to deploy it

Page 4: Share Point Interview

in 12 hive or say ShraePoint. It is recommended to create a feature first, and then wrap everything in a Solution package. See exampleDepoly a Custom aspx Page in SharePoint 

Q. How will you cancel a deployment from central admin -> solution managment, if its stuck at “deploying” or “Error”. 

Ans. You can either try to force execute timer jobs using execadmsvcjobs command or can cancel the dpeloyment using stsadm command stsadm –o cancaldeployment –id {GUID} command. The Id here would be GUID of the timer or deployment job. You can get the Id from stsadm enumdeployment command. This will display all the deployments which are process or are stuck with Error. 

Q. How do make an existing non-publishing site Publishing? 

Ans. You can simply activate the SharePoint Publishing Feature for the Site, you want to make publishing. 

Q. Can you name some of the tools used for SharePoint Administration? 

Ans. Tools Used for SharePoint Administration 

Q. What are Application Pages in SharePoint? 

Ans. Unlike site pages (for example, default.aspx), a custom application page is deployed once per Web server and cannot be customized on a site-by-site basis. Application pages are based in the virtual _layouts directory. In addition, they are compiled into a single assembly DLL. A good example of an Application Page is the default Site Settings page: every site has one, and it's not customizable on a per site basis (although the contents can be different for sites). With application pages, you can also add inline code. With site pages, you cannot add inline code. 

Q. What is Authentication and Authorization? 

Ans . An authentication system is how you identify yourself to the computer. The goal behind an authentication system is to verify that the user is actually who they say they are. Once the system knows who the user is through authentication, authorization is how the system decides what the user can do. 

Q. How do you deploy a User Control in SharePoint ? 

Page 5: Share Point Interview

Ans. You deploy your User Control either by a Custom webpart, which will simply load the control on the page or can use tools like SmartPart, which is again a webpart to load user control on the page. User Control can be deployed using a custom solution package for the webapplication or you can also the control in the webpart solution package so that it gets deployed in _controlstemplate folder. 

Q. Which is faster a WebPart or a User Control? 

Ans. A WebPart renders faster than a User Control. A User Control in SharePoint is usually loaded by a webpart which adds an overhead. User Controls however, gives you an Interface to add controls and styles. 

Q. What SharePoint Databases are Created during the standard Install? 

Ans. During standard install, the following databases are created : 

SharePoint_AdminContent SharePoint_Config WWS_Search_SERVERNAME%_%GUID_3% SharedServicesContent_%GUID_4% SharedServices1_DB_%GUID_5% SharedServices1_Search_DB_% GUID_6%WSS_Content_%GUID_7% 

Q. What are content types? 

Ans. A content type is a flexible and reusable WSS type definition (or we can a template) that defines the columns and behavior for an item in a list or a document in a document library. For example, you can create a content type for a leave approval document with a unique set of columns, an event handler, and its own document template and attach it with a document library/libraries. 

Q. Can a content type have receivers associated with it? 

Ans. Yes, a content type can have an event receiver associated with it, either inheriting from the SPListEventReciever base class for list level events, or inheriting from the SPItemEventReciever base class. Whenever the content type is instantiated, it will be subject to the event receivers that are associated with it. 

Q. Can you add a Cutsom Http Handler in SharePoint ? 

Ans. Yes, a Custom httphandler can be deployed in _layouts folder in SharePoint. Also, we need to be register the handler in the webapp's webconfig file. 

Page 6: Share Point Interview

Q. While creating a Web part, which is the ideal location to Initialize my new controls? Override the CreateChildControls method to include your new controls. You can control the exact rendering of your controls by calling the .Render method in the web parts Render method. 

Q. How do you return SharePoint List items using SharePoint web services? Ans. In order to retrieve list items from a SharePoint list through Web Services, you should use the lists.asmx web service by establishing a web reference in Visual Studio. The lists.asmx exposes the GetListItems method, which will allow the return of the full content of the list in an XML node. It will take parameters like the GUID of the name of the list you are querying against, the GUID of the view you are going to query, etc. 

Q. How Do you deploy Files in 12 hive when using wspbuilder or vsewss? 

Ans. Typically, you can add these files in the 12 hive folder structure in your project. In Vsewss however, you will have to create this structure manually. 

Q. What files gets created on a file system, when a Site collection is created ?

Ans. Windows SharePoint Services does not create any files or folders on the file system when the site collection or sites are created; everything is created in the content database. The Pages for the site collection are created as instances in the content database. These instances refer to the actual file on the file system.

Q. What are Customized and Uncustomized Files in SharePoint ?

Ans. There are two types of Pages in SharePoint; site pages (also known as content pages) and application pages.

Uncustomized :

When you create a new SharePoint site in a site collection, Windows SharePoint Services provisions instances of files into the content database that resides on the file system. That means if you create a new Site "xyz" of type Team Site(orTeam sIte Definition), an instance of the Team Site Definition( Which resides on the File System), i.e. "xyz" gets created in the Content database. So, When ASP.NET receives a request for the file, it first finds the file in the content database. This entry in the content database tells ASP.NET that the file is actually based on a file on the file system and therefore, ASP.NET retrieves the source of the file on the file system when it constructs the page.

Page 7: Share Point Interview

Customized :

A customized file is one in which the source of the file lives exclusively in the site collection's content database. This happens When you modify the file in any way through the SharePoint API, or by SharePoint Designer 2007,which uses the SharePoint API via RPC and Web service calls to change files in sites. So, When the file is requested, ASP.NET first finds the file in the content database. The entry in the database tells ASP.NET whether the file is customized or uncustomized. If it is customized, it contains the source of the file, which is used by ASP.NET in the page contraction phase.

Q. What are event receivers?

Ans. Event receivers are classes that inherit from the SpItemEventReciever or SPListEventReciever base class (both of which derive out of the abstract base class SPEventRecieverBase), and provide the option of responding to events as they occur within SharePoint, such as adding an item or deleting an item.

Q. When would you use an event receiver?

Ans. Since event receivers respond to events, you could use a receiver for something as simple as canceling an action, such as deleting a document library by using the Cancel property. This would essentially prevent users from deleting any documents if you wanted to maintain retention of stored data.

Q. If I wanted to restrict the deletion of the documents from a document library, how would I go about it?

Ans. You would create a event receiver for that list/library and implement the ItemDeleting method. Simply, set: properties.Cancel= true and display a friendly message using Properties.Message("How can u delete this... Its not your stuff!");

Q. What is the difference between an asynchronous and synchronous event receivers?

Ans. An asynchronous event occurs after an action has taken place, and a synchronous event occurs before an action has take place. For example, an asynchronous event is ItemAdded, and its sister synchronous event is ItemAdding

Q. How do you Increase trust level for a single WebPart in the WebConfig file.

Ans. To list a Web Part with Full Permissions within your Web Application while still retaining a WSS_Minimal permission set for all other Web Parts, You need to create a Custom policy file. This file will be then referenced in SharePoint Web.config file and will allow your specific webpart to be of Full trust.

Page 8: Share Point Interview

Steps :1. Make a copy of the WSS_Minimal.Config file from the 12\Config folder and paste it into the same folder renaming it to Custom_WSS_Minimal.Config. Now, edit the Custom_WSS_Minimal.Config file using NotePad. Obtain the Public Key Token for the Web Part assembly that you want to deploy, using the following command: sn –Tp filename.dll. Create a new entry in your Custom_WSS_Minimal.Config file for your WebPart. Save the File.Finally, Create a new TrustLevel element for your config file in the Web.Config called Custom_WSS_Minimal that points to your custom file in the 12\config folder. Recycle the Application Pool and You’re Done.

Q. How does Windows SharePoint Services help render the Webapplictaion in ShrePoint?

Ans. When a new web applictaion is created via Central Admin, Windows SharePoint Services creates a new Web application in IIS. Then the WSS, loads the custom HTTP application and replaces all installed HTTP handlers and modules with Windows SharePoint Services–specific ones. These handlers and modules essentially tell IIS to route all file requests through the ASP.NET 2.0 pipeline. This is because most files in a SharePoint site are stored in a Microsoft SQL Server database.

Q. How would you pass user credentials while using SharePoint WebService from your Web Part or application.

Ans. The web service needs credentials to be set before making calls.

Examples:

listService.UseDefaultCredentials = true; // use currently logged on user

listService.Credentials = new System.Net.NetworkCredential("user", "pass", "domain"); // use specified user

Q. How would you remove a webapart from the WebPart gallery? Does it get removed with Webpart retraction?

Ans. No, Webpart does not get removed from the WebPart gallery on retraction. You can write a feature receiver on Featuredeactivating method to remove the empty webpart from the gallery.

Q. What is a SharePoint Feature? Features are installed at what scope 

Ans. A SharePoint Feature is a functional component that can be activated and deactivate at various scopes throughout a SharePoint instances, scope of which are defined as1. Farm level 2. Web Application level 3. Site level 4. Web levelFeatures have their own receiver architecture, which allow you to trap events such as when

Page 9: Share Point Interview

a feature is Installing, Uninstalling, Activated, or Deactivated.

Q. What type of components can be created or deployed as a feature?

Ans. We can create menu commands, Custom Actions,page templates, page instances, list definitions, list instances,event handlers,webparts and workflows as feature.

strong>Q. How Do you bind a Drop-Down Listbox with a Column in SharePoint List ?

Ans.Method 1 : You can get a datatable for all items in the list and add that table to a data set. Finally, specify the dataset table as datasource for dropdown listbox.

Method 2 : You can also use SPDatasource in your aspx or design page.See Code example Binding Drop-Down with Sharepoint List data

Q. How Does SharePoint work?

Ans. The browser sends a DAV packet to IIS asking to perform a document check in. PKMDASL.DLL, an ISAPI DLL, parses the packet and sees that it has the proprietary INVOKE command. Because of the existence of this command, the packet is passed off to msdmserv.exe, who in turn processes the packet and uses EXOLEDB to access the WSS, perform the operation and send the results back to the user in the form of XML.

Q. What is CAML?

Ans. CAML stands for Collaborative Application Markup Language and is an XML-based languagethat is used inMicrosoft Windows SharePoint Services to define sites and lists, including, for Eg, fields, views, or forms, but CAML is also used to define tables in the Windows SharePoint Servies database during site provisioning. Developers mostly use CAML Queries to retrieve data from Lists\libraries.

Q. Can you display\add a Custom aspx or WebApplication Page in SharePoint Context ?

Ans. You need to make some modification in the aspx file to display it in SharePoint Context. Firstly, add the references for various sharepoint assemblies on the Page. Then wrap the Code in PlaceHolderMain contentPlaceholder, so that it gets displayed as a content page. Lastly, add a reference to SharePoint Master Page in aspx file and swicth it in Code behind if needed. See Code Example at Display aspx Page in SharePoint context

Page 10: Share Point Interview

Q. If you have an ItemUpdated or ItemUpdating event receiver and it causes an update to the item, how do you prevent another ItemUpdated and ItemUpdating event from being fired during your update?

A. Before performing your update, call DisableEventFiring(). After update, call EnableEventFiring().

Q: Name at least two shared services available in MOSS 2007

A: Shared Services Providers in MOSS 2007 can provide the following shared services:

User Profiles Audiences Personal Sites Search Excel Services Forms Services Business Data Catalog (Requires Enterprise Edition)

Q: How would you programmatically retrieve a list item?

A: SPQuery and SPSiteDataQuery. Bonus points for knowledge of CrossListQueryCache, PortalSiteMapProvider. Negative points for use of foreach.

What is safe mode processing and Safe Controls?

Answer: 

Any customized page is parsed using safe mode processing. This parsing brings in security. Safe mode processing guarantees that there is no inline script in the customized page. In other words safe mode processing disallows in-line script because a hacker can mount attack using in-line script. If you try to run in-line script on customized page you will get error ‘Code blocks are not allowed in this file’. 

In case you still want to run in-line script in customized pages you need to specify ‘AllowServerSideScript=true’ in the ‘SafeMode’ tag section in web.config file. 

<SharePoint><SafeMode ... ><PageParserPaths><PageParserPathVirtualPath="/sites/MySite/SitePages/*"IncludeSubFolders="true"CompilationMode="Always"AllowServerSideScript="true" /></PageParserPaths></SafeMode>

Page 11: Share Point Interview

</SharePoint>

Safe controls help us define which controls the customized pages will have. Customized pages can only have controls which are defined in the web.config file in the ‘SafeControls’ tag. For instance in the below code snippet we have defined that customized pages can use controls from ‘Microsoft.SharePoint.WebControls’.

<SafeControls><SafeControlAssembly="Microsoft.SharePoint"Namespace="Microsoft.SharePoint.WebControls"TypeName="*"AllowRemoteDesigner="True" /></SafeControls>

What are the different life cycle events that WebPart goes through?Show/Hide Answer

 A ‘WebPart’ control goes through various events and has a typical life cycle.

OnInit: - This is the initialization event and is the first event to occur.

OnLoad: - The load event.

CreateChildControls: - When any child controls are added to a composite control this event fires.

EnsureChildControls: - This event makes sure that ‘CreateChildControls’ fires.

OnPreRender: - This fires just before the render event.

Page.PreRenderComplete :- When all controls have executed the ‘OnPreRender’ event this event fires.

Render: - Render the full control.

RenderContents: - Renders the contents of the control only.

WSS and MOSS offer many of the same collaboration features:

Page 12: Share Point Interview

Site provisioning

Document management (check in/check out)

Discussions

Wikis, Blogs, RSS Feeds

Basic workflow

Custom lists

MOSS builds upon WSS and adds:

Additional workflows

Web content management (web publishing features)

Records management

Auditing

Additional search such as people search

My Sites (each user has their own personal site with public and private areas)

Enterprise features such as Excel Services and BDC

3.3 What are safe controls, and what type of information, is placed in that element in a SharePoint web.config file?When you deploy a WebPart to SharePoint, you must first make it as a safe control to use within SharePoint in the web.config file. Entries made in the safe controls element of SharePoint are encountered by the SharePointHandler object and will be loaded in the SharePoint environment properly, those not will not be loaded and will throw an error. In the generic safe control entry (this is general, there could be more), there is generally the Assembly name, the namespace, the public key token numeric, the typename, and the safe declaration (whether it is safe or not). There are other optional elements.

SharePoint features and Deployment

Do read all blogs from Adrea Vala fromhttp://blogit.create.pt/blogs/andrevala/archive/2007/12/02/SharePoint-2007-Deployment_3A00_-Overview.aspx

Who Needs Deployment?

Regarding the development environment, there are two types of SharePoint projects:

Page 13: Share Point Interview

Single environment projects, where everything is configured and developed directly in the production environment;

Multiple environment projects, where all the development and configuration is done in a development environment, then possibly deployed to a testing environment, and finally deployed to the production environment.

Additionally, you can have two types of farms, in a SharePoint installment:

Single server farm, when there is only one SharePoint Server in the farm (although there can be additional SQL Servers);

Multiple server farm, when there are several SharePoint Servers, possibly with different server roles, in the farm.

For Single Server – Single Environment projects, which are the least common type, the developers don't really need to be concerned about deployment since everything is done on the same server. But for the other types of projects (Single Server – Multiple Environment, Multiple Server – Single Environment and Multiple Server – Multiple Environment) developers will need to deploy their work to the servers.

What Does Deployment Mean, in a SharePoint Sense?

In SharePoint, deployment means the necessary actions to install your software solution in a SharePoint environment, whether that solution consists of web parts, custom web controls, event handlers, custom web pages, or just master pages.

So, imagine you have created site columns and content types directly on the SharePoint UI, customized some master pages using SharePoint Designer and installed a few custom web parts on your Development Environment, and now you need to deploy this to the Testing Environment (and later on, to the Production Environment). You can choose from a few different deployment methods:

Stone Age Deployment. You do it all over again in the Testing Environment, and later you will repeat the procedure in the Production Environment. It's not hard to figure out this is a bad practice: probably you won't be able to repeat the tasks in the exact same order as you did before, and that might result in errors or in a Testing Environment that is not a replica of the Development Environment. Also, that means the developers must have administration access in all the environments, which is not always the case.

Backup/Restore Deployment. You perform a farm backup on the Development Environment and restore it in the Testing Environment. Although commonly used, it's not the best practice either: you must make sure all the assemblies, web.config modifications, and file system changes are present in the destination environment before you restore the backup. Also, you might have some problems if the environments are not in the same windows domain.

Content Deployment. You use SharePoint's content deployment paths and jobs. That can be a good solution, but it has some limitations: unless you are deploying a whole site collection, you'll need to make sure all the assemblies, web.configmodifications, and file system changes are present in the destination environment before you restore the backup. Content deployment is targeted at "contents" and not at "structure", although some of the SharePoint structures are migrated with the contents. Also, both environments must be connected for automatic content deployment to work. You have the option to export

Page 14: Share Point Interview

a site collection to a .CAB file and import it in the destination environment using STSADM commands, but the same limitations apply.

Solution Deployment. You build SharePoint Features for all the objects you developed and pack them in one or moreSharePoint Solutions. This is the recommended approach for structure deployment, since it allows for multiple server farm deployment, allows the deployment of assemblies, web.config modifications, files in file system folders as well as all SharePoint objects.

What's a Feature?

A Feature is a package composed of a set of XML files that describe Windows SharePoint Services elements, which can be activated on a specific scope to help users accomplish a given task. To make it easier to understand, I usually say that you should use a Feature when you need to add one or more objects to SharePoint and want to allow users to easily enable or disable that option.

With a feature you can:

Add a site column Add a site content type Add a list template Create a list instance Add custom actions to SharePoint's menus Install web parts, master pages, layout pages, images and other contents Register event handlers Associate a content type with an existing list Install a custom workflow Install a custom control Install a custom document converter

However, a feature cannot install itself. For that, it needs a solution.

What's a Solution?

A Solution is a deployable and reusable package that can contain a set of Features, site definitions and assemblies that you can apply to a site, and can also enable or disable individually. A Solution is materialized in a solution file, which is a file with a CAB-based format with a .wsp extension.

With a solution you can:

Install Features Install assemblies in the GAC Install assemblies to the BIN folder of a web application Add assembly descriptions to the web.config safe controls section Set Code Access Security configurations Install files in the template folder of SharePoint (usually C:\Program Files\Common

Files\Microsoft Shared\web server extensions\12\TEMPLATE) Install files in the root folder of SharePoint (usually C:\Program Files\Common

Files\Microsoft Shared\web server extensions\12) Install a site definition

Page 15: Share Point Interview

A Solution is the only way to automatically execute a deployment of functionality to a SharePoint server farm.

Creating and Using Features

Feature Scopes

A Feature can be activated or deactivated in a specific scope, and there are four different scopes:

Farm – The elements will be deployed at the farm level. To activate or deactivate a farm-scoped Feature, go to Central Administration, Operations section, and click on Manage Farm Features in the Global Configuration group.

Web Application – The elements will be deployed at the web application level. To activate or deactivate a web application-scoped Feature, go to Central Administration, Application Management section, and click on Manage Web Application Features in the SharePoint Web Application Management group.

Site Collection – The elements will be deployed at the site collection level. To activate or deactivate a site collection-scoped Feature, go to the root web site settings, and click on Site Collection Features in the Site Collection Administrationgroup. You must be a site collection administrator to see this setting.

Web Site – The elements will be deployed at the web site level. To activate or deactivate a web site-scoped Feature, go to the web site settings, and click on Site Features in the Site Administration group. You must have ManageWebpermissions (for instance, being a site administrator) to see this setting.

Each type of element can be deployed to one or more of these scopes. When describing each element type, I will specify to which scopes they can be deployed to.

Feature Schema

To create a Feature you must create a XML file named feature.xml which contains all the general configurations for the Featureand the references to all the files that describe the Elements contained in the Feature. Below is an example of a feature.xml file that uses all possible attributes, just for demonstration purposes. Required attributes are printed in bold.

<?xml version="1.0" encoding="utf-8" ?><Feature xmlns="http://schemas.microsoft.com/sharepoint/"    Id="AB30188E-6F5D-4380-89D9-46F5D43E25F7"    Scope="Site"    Title="My Feature"    Description="My Feature includes several elements."

Page 16: Share Point Interview

    Version="1.0.0.0"    Creator="André Vala"    SolutionId="2530188E-6F5A-433B-89D9-BA98D43E25F7"    ImageUrl="/_layouts/MyFeature/MyFeatureIcon.jpg"    ImageUrlAltText="My Feature Icon"    Hidden="FALSE"    ActivateOnDefault="FALSE"    AlwaysForceInstall="FALSE"    AutoActivateInCentralAdmin="FALSE"    RequireResources="TRUE"    DefaultResourceFile="MyResourceFile"    ReceiverAssembly="MyFeatureReceiver, Version=1.0.0.0, Culture=Neutral, PublicKeyToken=3f5df55c01ba1c99"    ReceiverClass="MyFeatureReceiver.MyReceiverClass">    <ActivationDependencies>        <ActivationDependency FeatureId="C03829C4-0E85-4DCE-90F8-B7E3F008A0C5"/>    </ActivationDependencies>    <ElementManifests>        <ElementManifest Location="MyElement1.xml"/>        <ElementManifest Location="MyElement2.xml"/>        <ElementManifest Location="MyElement3.xml"/>        <ElementFile Location="MyFile1.jpg"/>        <ElementFile Location="MyFile2.jpg"/>    </ElementManifests>    <Properties>        <Property Key="MyProperty" Value="MyValue" />    </Properties></Feature>

Tip: To make things easier when creating these files in Visual Studio 2005 (or later), you can use the wss.xsd schema file, included with SharePoint (usually in C:\Program Files\Common Files\Microsoft Shared\web server extensions\12\TEMPLATE\XML), to enable Intellisense.

Site Column Features

Summary

This post is about developing features to create site columns in a SharePoint site. Check the first post SharePoint 2007 Deployment: Overview for an introduction and the series index.

Package Structure

As I mentioned previously in the post SharePoint 2007 Deployment: Creating and Using Features, to build a feature you need to create the following files:

The feature manifest file (which must be named feature.xml) One or more element manifest files

Page 17: Share Point Interview

The feature manifest file contains the generic information about the feature package, and the element manifest files contain the information about each specific type of element that makes up the feature. Since I already explained all the possible contents of the feature manifest file in the above mentioned post, I will focus this one the element manifest that allows the creation of site columns in a SharePoint site.

You can then place these two files inside a Solution following the instructions in the post SharePoint 2007 Deployment: Creating Solutions, to provide an easy way to deploy the feature (or upgrade it).

Site Columns

Just to keep everything clear, I'm going to give a brief explanation about the concept of site columns. Site columns are reusable column definitions, which means that they are exactly the same as a regular list column but do not belong to any single list. A site column exists in the context of a web site (organized in groups, in the site column gallery) and can be used in lists and content types in that web site or its child web sites.

One can create new site columns or edit the existing ones following the steps below:

Site Actions (press the button) Site Settings Site Columns (in the Galleries option group)

Allowed Scopes

The scopes to which a feature can be deployed, are dictated by the types of elements included in it. A feature with site column elements can only be deployed to Site Collection or Web Site scopes.

Feature Manifest

I will only present a simple feature manifest, since the additional options were presented in the above mentioned post.

<?xml version="1.0" encoding="utf-8" ?><Feature xmlns="http://schemas.microsoft.com/sharepoint/" Id="5DFD12AF-D0AA-4c63-8FB8-C49DB1191083" Title="My Site Columns Feature" Description="Adds My Site Columns." Scope="Site" Version="1.0.0.0"> <ElementManifests> <ElementManifest Location="SiteColumns.xml"/> </ElementManifests></Feature>

Notes about this feature manifest:

The title of the feature is My Site Columns Feature.

Page 18: Share Point Interview

It will be deployed as a Site Collection feature, since it's Scope value is Site. It references a single element manifest file: SiteColumns.xml.

Element Manifest

The element manifest file can have any name you wish (in this example it's called SiteColumns.xml), but it's root element must be<Elements>. Inside this root element, you can place any number of feature element descriptions. In this example I will present the use of the <Field> element which is used to deploy Site Columns.

Since the <Field> element can have a very large number of attributes I will only show a subset with the most common ones.

<Elements xmlns = "http://schemas.microsoft.com/sharepoint/"> <Field ID="{b402db15-ee44-4ec4-89e3-23e10a8fc64c}" Type="Text" Title="TextField" Name="TextField" StaticName="TextField" DisplayName="TextField" Description="My Text Field." Required="FALSE" MaxLength="255" Hidden="FALSE" ReadOnly="FALSE" ShowInDisplayForm="TRUE" ShowInEditForm="TRUE" ShowInListSettings="TRUE" ShowInNewForm="TRUE" ShowInVersionHistory="TRUE" ShowInViewForms="TRUE" Group="Custom Columns"> </Field></Elements>

This example creates a site column, named TextField, of type Single Line of Text. See below a short explanation of the used attributes:

ID - This is the unique identifier of this site column. It will be used to reference this site column when including it in a content type or attaching it to a list.

Type - This attribute specifies the type of data stored in the site column. It can have one of the following values:

o AllDayEvent: All day event flag, used in calendar lists.o Attachments: Stores the URL of attachments.o Boolean: Specifies a Yes/No field.o Calculated: Specifies that this field's value is calculated based on other

columns' values.o Choice: Specifies a Choice (menu to choose from) field with a pre-defined

set of values.o Computed: Specifies a field whose value depends on another field's value.o ContentTypeId: Contains a Content Type ID value.o Counter: Used to hold the internal ID's for each item.

Page 19: Share Point Interview

o Currency: Specifies a field that stores a currency value (its format depends on the locale).

o DateTime: Specifies a Date and Time field.o File: Contains a file (used in document libraries).o GridChoice: Specifies a rating scale (used in surveys).o Guid: Specifies a field that holds a unique identifier.o Integer: Specifies a number field that holds integer values only.o Lookup: Specifies a Lookup field, which is similar to the Choice field except

the available choices are retrieved from another list.o LookupMulti: Specifies a Lookup field that allows multiple selections.o ModStat: Specifies a field that contains content approval status.o MultiChoice: Specifies a Choice field that allows multiple selections.o Note: Specifies a Multiple Lines of Text field.o Number: Specifies a Number field, that can hold floating-point values.o PageSeparator: Specifies a page separator (used in surveys).o Recurrence: Used to mark an event as recurrent in a calendar list.o Text: Specifies a Single Line of Text field.o ThreadIndex: Specifies the correlation ID in a threaded conversation (used in

discussion lists).o Threading: Used in the creation and display of threaded discussion-like views.o URL: Specifies a Hyperlink or Picture field.o User: Specifies a Person or Group field.o UserMulti: Specifies a Person or Group field that allows multiple selections.o WorkflowEventType: Contains the type of workflow history event (used in

workflow history list).o WorkflowStatus: Contains the workflow status (used in lists that have

associated workflows). Title - This is the name of the field shown in the interface, and it can be changed by

the user. Name - (optional) This is the internal name of the field, and is guaranteed to never

change during the lifetime of the field. It is automatically generated from the display name of the field, and the spaces and special characters are escaped.

StaticName - (optional) This is automatically set to the same value as the internal name, but can be changed programmatically (not through the interface though).

DisplayName - (optional) This is the same as the Title property. Description - (optional) This is the description for the field. SharePoint displays this

text in new/edit forms below the data entry control. Required - (optional) Specifies if the field is mandatory. Default value is FALSE. MaxLength - (optional) Specifies the maximum number of characters allowed for this

field. Hidden - (optional) Specifies that the field should be completely hidden from the

interface. If TRUE, this field will not be shown on views or forms. Default value is FALSE.

ReadOnly - (optional) Specifies that the field should be read-only, which means it appears in views but will be hidden from new/edit forms. Default value is FALSE.

ShowInDisplayForm - (optional) Specifies that the field should be shown in display forms. Default value is TRUE.

ShowInEditForm - (optional) Specifies that the field should be shown in edit forms. Default value is TRUE.

ShowInListSettings - (optional) Specifies that the field should be shown in the list settings screen. Default value is TRUE.

Page 20: Share Point Interview

ShowInNewForm - (optional) Specifies that the field should be shown in new forms. Default value is TRUE.

ShowInVersionHistory - (optional) Specifies that the field should be shown in the version history of an item. Default value isTRUE.

ShowInViewForms - (optional) Specifies that the field should be shown in view forms. Default value is TRUE.

Group - (optional) Specifies the name of the group that contains the site column.

Additional Samples

Because there are so many types of fields, I will include some additional samples and notes to show some of the other attributes used to specify a field.

The Choice Field <Field ID="{538c71e4-8650-4ce7-b021-920effa66346}" Type="Choice" Name="Publishing_x0020_Status" StaticName="Publishing_x0020_Status" DisplayName="Publishing Status" Required="FALSE" Format="Dropdown" FillInChoice="FALSE" Group="Custom Columns"> <Default>Not Published</Default> <CHOICES> <CHOICE>Not Published</CHOICE> <CHOICE>Pending</CHOICE> <CHOICE>Published</CHOICE> <CHOICE>Error</CHOICE> </CHOICES> </Field>

The Choice field has a few specific issues that are worth mentioning:

The Type attribute must be set to Choice. The Format attribute is used for several purposes, but in choice fields, it defines the

type of control used to select the option. Possible values are Dropdown (default) and RadioButtons.

The attribute FillInChoice specifies if the user can add choices to the column. The <Default> child element specifies which of the choices is pre-selected in the

control as default. The <CHOICES> child element contains all the possible value options, each in its

own <CHOICE> child element. Beware that you must use capital letters for these elements, otherwise the field will not contain any of the choices.

The Multiple Lines of Text Field <Field ID="{5b79f1f1-b14f-489b-9bd5-a76897db93b9}" Type="Note" Name="My_x0020_Comments" StaticName="My_x0020_Comments" DisplayName="My Comments"

Page 21: Share Point Interview

Required="FALSE" UnlimitedLengthInDocumentLibrary="TRUE" NumLines="10" RichText="FALSE" Sortable="FALSE" Group="Custom Columns"> </Field>

The Multiple Lines of Text field also has some specific attributes:

The Type attribute must be set to Note. The UnlimitedLengthInDocumentLibrary attribute specifies that there will be no

limitation to the contents of this field when used in document libraries. The NumLines attribute defines the number of lines shown in the data entry control

(textarea HTML control). The RichText attribute specifies if the field accepts formatted text or only plain text. The Sortable attribute specifies if the field can be used to sort a list. Note fields

always have the Sortable attribute set toFALSE.

The Number Field <Field ID="{5b7934e1-b14f-489b-9bd5-a76837da92b4}" Type="Number" Name="My_x0020_Number" StaticName="My_x0020_Number" DisplayName="My Number" Required="FALSE" Min="0" Max="100" Decimals="0" Percentage="FALSE" Group="Custom Columns"> </Field>

The Number field has the following additional attributes:

The Type attribute must be set to Number. The Min and Max attributes specify the minimum and maximum values that this field

can contain. Both attributes are optional. The Decimals attribute specifies the number of decimal places of the number stored

in the field. The Percentage attribute specifies if the number is to be shown as a percentage.

Default value is FALSE.

The Lookup Field

The Lookup field is the only field type that cannot be created with a simple feature such as this one. The cause for this is the fact that this type of field references a column of a list using the list's ID, and a list's ID is dynamically generated when a list is created.

Page 22: Share Point Interview

This means that there is no way one can predict what will be the ID of the list referenced by the Lookup field when the feature is developed. This value is only known when the feature is activated in a specific web site.

For that reason, the steps to create a feature for this type of site column will be the subject of one of the next posts of the series.

Also check following articles from AndreVala

art 0: Overview (this post) Part 1: Features and Solutions Part 2: Creating and Using Features Part 3: Creating and Using Solutions Part 4: Site Column Features Part 5: Site Content Type Features Part 6: List Template Features Part 7: List Instance Features Part 8: Custom Action Features Part 9: Module Features Part 10: Event Registration Features Part 11: Content Type Binding Features Part 12: Feature Stapling (Feature Site Template Association) Part 13: Using Resources in Features 

Feature Stapling

Summary

This post is about developing features that associate other features to an existing site definition. This is one of the most powerful types of feature since it allows you to add new functionality to existing site definitions. Check the first post SharePoint 2007 Deployment: Overview for an introduction and the series index.

Package Structure

As I mentioned previously in the post SharePoint 2007 Deployment: Creating and Using Features, to build a feature you need to create the following files:

The feature manifest file (which must be named feature.xml) One or more element manifest files

Page 23: Share Point Interview

The feature manifest file contains the generic information about the feature package, and the element manifest files contain the information about each specific type of element that makes up the feature. Since I already explained all the possible contents of the feature manifest file in the above mentioned post, I will focus this one the element manifest that allows the feature stapling (feature site template association).

You can then place these two files inside a Solution following the instructions in the post SharePoint 2007 Deployment: Creating Solutions, to provide an easy way to deploy the feature (or upgrade it).

Feature Stapling

Feature stapling is the process of associating features to existing site definitions so that, when a new site is provisioned from that definition the associated features are automatically activated.

This means that you need, at least, two features to do this:

The feature (or features) you wish to associate (that is, to staple) to a site definition; The feature that performs the association (the stapler).

The first one can be any feature with scope Site or Web. The second is the one I’m presenting in this post.

Allowed Scopes

The scopes to which a feature can be deployed, are dictated by the types of elements included in it. A feature with feature site template association elements can be deployed to Site Collection, Web Application or Farm scopes.

Understanding Ghosting and UnghostingBefore diving into site definitions it's important to understand one of the inner workings of SharePoint. When you create a new site, SharePoint doesn't really copy the pages for that site— default.aspx and

so on—into a new database table or directory. These files exist once and only once on each of the front end Web servers. Instead, SharePoint creates a reference to those files in the database tables that define the new site, a process called "ghosting." The outcome is that the site appears to have its own unique pages, but the pages are actually shared across all sites that use the same definition. 

This has two distinct advantages over copying the files to each site individually when the site is created. First, it saves space. If you have a thousand sites, rather than having a thousand copies of a file you still have only one. Second, it improves performance. Instead of having to load and cache a thousand pages from the database, the server needs to cache only one copy from the file system, which can improve performance by freeing cache memory for other purposes. Loading the file from the Web server's local file system improves performance by eliminating the overhead of the database call and the network traffic to the database. 

One interesting benefit of this approach is that when you make a change to one file on the file system,

Page 24: Share Point Interview

that change takes effect across all the sites that have been created. All in all, the process of ghosting is a huge benefit to SharePoint. However, there are some limitations. 

SharePoint can't ghost every page. Some operations, such as editing a page in FrontPage, cause SharePoint to "unghost" dependent pages for the site. Because ghosting requires all ghosted pages to be exactly the same across all the sites that share them, SharePoint unghosts, or creates a copy of the page in the database, whenever a ghosted page changes, for example, when someone performs an edit operation on the page. Unghosting lets users customize their own sites without impacting other users who might be using the same file. Unfortunately however, unghosting also has a negative performance impact, and makes global changes, such as applying corporate branding to the entire collection of sites far more difficult. Unghosting is the primary reason why efforts to leverage the power of site definitions to change the branding of an entire site may not work as intended. 

ONET.XML contains all the major settings that you need for controlling initial site creation. 

Functions of Onet.xml

Depending on where a Onet.xml file is located and whether it is part of a site definition or a Web template, the markup in the file does some or all of the following:

Specify the Web-scoped and site collection-scoped Features that are built-in to Web sites created from the site definition or Web template.

Specify the lists types, pages, files, and Web Parts that are built-in to Web sites created from the site definition or Web template.

Define the top and side navigation areas that appear on the home page and in list views for a site definition.

Specify the list definitions that are used in each site definition and whether they are available for creating lists in the UI.

Specify document templates that are available in the site definition for creating document library lists in the UI, and specify the files used in the document templates.

Define the base list types from which default SharePoint Foundation lists are derived. (Only the global Onet.xml file serves this function. You may not define new base list types.)

Specify SharePoint Foundation components. Define the footer section used in server e-mail.

SharePoint coding best practices Overviewhttp://msdn.microsoft.com/en-us/library/bb687949(office.12).aspx

Developers who write custom code with the SharePoint object model will encounter common issues related to performance, extensibility, and scalability. This article is a resource for developers who are working to troubleshoot and improve the performance of existing SharePoint applications or who are writing new SharePoint applications. In both cases, it is important to understand how to make the SharePoint object model work efficiently, and how to apply general programming techniques (such as caching and threading) to the SharePoint

Page 25: Share Point Interview

platform specifically. This information can make it easier to design your applications correctly, find and fix problem areas in your code, and avoid known pitfalls of using the SharePoint object model.

The following areas reflect the most common general concerns encountered by SharePoint developers:

Using SharePoint data and objects efficiently

Performance concerns related to folders, lists, and SPQuery objects

Writing applications that scale to large numbers of users

Using Web controls and timer jobs

Disposing of SharePoint objects 

This article addresses all but the last of these issues. For guidance on disposing of SharePoint objects, see Best Practices: Using Disposable Windows SharePoint Services Objects.

Additionally, we recommend that you read the following orientation topics as good starting points for using the SharePoint object model:

Server and Site Architecture: Object Model Overview

Understanding the Administrative Object Model of Windows SharePoint Services 3.0

Using SharePoint Data and Objects Efficiently

Caching is one good way to improve system performance. However, you must weigh the benefits of caching against the need for thread safety. Additionally, you should not create certain SharePoint objects within event receivers because this will cause performance problems related to excessive database calls.

This section describes these common areas of concern so that you can learn ways to optimize your use of SharePoint objects and data.

Caching Data and Objects

Many developers use the Microsoft .NET Framework caching objects (for example, System.Web.Caching.Cache) to help take better advantage of memory and increase overall system performance. But many objects are not "thread safe" and caching those objects can cause applications to fail and unexpected or unrelated user errors.

Note:

The caching techniques discussed in this section are not the same as the custom caching options for Web content management that are discussed in

Page 26: Share Point Interview

Overview.

Caching SharePoint Objects That Are Not Thread Safe

You might try to increase performance and memory usage by caching SPListItemCollection objects that are returned from queries. In general, this is a good practice; however, the SPListItemCollection object contains an embedded SPWeb object that is not thread safe and should not be cached.

For example, assume the SPListItemCollection object is cached in a thread. As other threads try to read this object, the application can fail or behave strangely because the embedded SPWeb object is not thread safe. For more information about the SPWeb object and thread safety, see the Microsoft.SharePoint.SPWeb class.

The guidance in the following section describes how you can prevent multiple threads from attempting to read the same cached object.

Understanding the Potential Pitfalls of Thread Synchronization

You might not be aware that your code is running in a multithreaded environment (by default, Internet Information Services, or IIS, is multithreaded) or how to manage that environment. The following example shows the code some developers use to cache Microsoft.SharePoint.SPListItemCollection objects.

Bad Coding Practice

Caching an Object That Multiple Threads Might Read

VB

C#

C++

F#

JScript

Copy

public void CacheData(){ SPListItemCollection oListItems;

oListItems = (SPListItemCollection)Cache["ListItemCacheName"]; if(oListItems == null) { oListItems = DoQueryToReturnItems(); Cache.Add("ListItemCacheName", oListItems, ..); }}

Page 27: Share Point Interview

Although the use of the cache in this example is functionally correct, because the ASP.NET cache object is thread safe, it introduces potential performance problems. (For more information about ASP.NET caching, see the Cache class.) If the query in the preceding example takes 10 seconds to complete, many users could try to access that page simultaneously during that amount of time. In this case, all of the users would run the same query, which would attempt to update the same cache object. If that same query runs 10, 50, or 100 times, with multiple threads trying to update the same object at the same time—especially on multiprocess, hyperthreaded computers—performance problems would become especially severe.

To prevent multiple queries from accessing the same objects simultaneously, you must change the code as follows.

Applying a Lock

Checking for null

VB

C#

C++

F#

JScript

Copy

private static object _lock = new object();

public void CacheData(){ SPListItemCollection oListItems;

lock(_lock) { oListItems = (SPListItemCollection)Cache["ListItemCacheName"]; if(oListItems == null) { oListItems = DoQueryToReturnItems(); Cache.Add("ListItemCacheName", oListItems, ..); } }}

You can increase performance slightly by placing the lock inside the if(oListItems == null) code block. When you do this, you do not need to suspend all threads while checking to see if the data is already cached. Depending on the time it takes the query to return the data, it is still possible that more than one user might be running the query at the same time. This is especially true if you are running on multiprocessor computers. Remember that the more processors that are running and the longer the query takes to run, the more likely putting the lock in the if() code block will cause problems. If you want to make absolutely

Page 28: Share Point Interview

sure that another thread has not created oListItems before the current thread has a chance to work on it, you could use the following pattern.

Applying a Lock

Rechecking for null

VB

C#

C++

F#

JScript

Copy

private static object _lock = new object();

public void CacheData(){ SPListItemCollection oListItems; oListItems = (SPListItemCollection)Cache["ListItemCacheName"]; if(oListItems == null) { lock (_lock) { //Ensure that the data was not loaded by a concurrent thread while waiting for lock. oListItems = (SPListItemCollection)Cache[“ListItemCacheName”]; if (oListItems == null) { oListItems = DoQueryToReturnItems(); Cache.Add("ListItemCacheName", oListItems, ..); } } }}

If the cache is already populated, this last example performs as well as the initial implementation. If the cache is not populated and the system is under a light load, acquiring the lock will cause a slight performance penalty. This approach should significantly improve performance when the system is under a heavy load, because the query will be executed only once instead of multiple times, and queries are usually expensive in comparison with the cost of synchronization.

The code in these examples suspends all other threads in a critical section running in IIS, and prevents other threads from accessing the cached object until it is completely built. This addresses the thread synchronization issue; however, the code is still not correct because it is caching an object that is not thread safe.

Page 29: Share Point Interview

To address thread safety, you can cache a DataTable object that is created from the SPListItemCollection object. You would modify the previous example as follows so that your code gets the data from the DataTable object.

Good Coding Practice

Caching a DataTable Object

private static object _lock = new object();

public void CacheData(){ DataTable oDataTable; SPListItemCollection oListItems; lock(_lock) { oDataTable = (DataTable)Cache["ListItemCacheName"]; if(oDataTable == null) { oListItems = DoQueryToReturnItems(); oDataTable = oListItems.GetDataTable(); Cache.Add("ListItemCacheName", oDataTable, ..); } }}

For more information and examples of using the DataTable object, and other good ideas for developing SharePoint applications, see the reference topic for the DataTable class.

Using Objects in Event Receivers

Do not instantiate SPWeb, SPSite, SPList, or SPListItem objects within an event receiver. Event receivers that instantiate SPSite, SPWeb, SPList, or SPListItem objects instead of using the instances passed via the event properties can cause the following problems:

They incur significant additional roundtrips to the database. (One write operation can result in up to five additional roundtrips in each event receiver.) 

Calling the Update method on these instances can cause subsequent Update calls in other registered event receivers to fail. 

Bad Coding Practice

Instantiating an SPSite Object Inside an Event Receiver

public override void ItemDeleting(SPItemEventProperties properties){ using (SPSite site = new SPSite(properties.WebUrl))

using (SPWeb web = site.OpenWeb())

Page 30: Share Point Interview

{ SPList list = web.Lists[properties.ListId]; SPListItem item = list.GetItemByUniqueId(properties.ListItemId); // Operate on item. } }}

Good Coding Practice

Using SPItemEventProperties

// Retrieve SPWeb and SPListItem from SPItemEventProperties instead of// from a new instance of SPSite.SPWeb web = properties.OpenWeb();// Operate on SPWeb object.SPListItem item = properties.ListItem;// Operate on item.

If you do not apply this fix in your code, when you call Update on the new instance, you must invalidate it with the Invalidate method in the appropriate child class ofSPEventPropertiesBase (for example, SPItemEventProperties.InvalidateListItem or SPItemEventProperties.InvalidateWeb).

Working with Folders and Lists

When folders and lists grow in size, custom code that works with them needs to be designed in ways that optimize performance. Otherwise, your applications will run slowly and even cause timeouts to occur. The following recommendations for addressing performance concerns while working with large folders and lists are based on the test results reported in Steve Peschka's white paper, Working with Large Lists in Office SharePoint Server 2007.

1. Do not use SPList.Items.

SPList.Items selects all items from all subfolders, including all fields in the list. Use the following alternatives for each use case.

o Retrieving all items in a list

Use SPList.GetItems(SPQuery query) instead. Apply filters, if appropriate, and specify only the fields you need to make the query more efficient. If the list contains more than 2,000 items, you will need to paginate the list in increments of no more than 2,000 items. The following code example shows how to paginate a large list.

Good Coding Practice

Retrieving Items with SPList.GetItems

Page 31: Share Point Interview

SPQuery query = new SPQuery();SPListItemCollection spListItems ; string lastItemIdOnPage = null; // Page position.int itemCount = 2000 while (itemCount == 2000){ // Include only the fields you will use. query.ViewFields = "<FieldRef Name=\"ID\"/><FieldRef Name=\"ContentTypeId\"/>";   query.RowLimit = 2000; // Only select the top 2000. // Include items in subfolder (if necessary). query.ViewAttributes = "Scope=\"Recursive\""; StringBuilder sb = new StringBuilder(); // To make it order by ID and stop scanning the table, specify the OrderBy override attribute. sb.Append("<OrderBy Override=\"TRUE\"><FieldRef Name=\"ID\"/></OrderBy>"); //.. Append more text as necessary .. query.Query = sb.ToString();  // Get 2,000 more items.  SPListItemCollectionPosition pos = new SPListItemCollectionPosition(lastItemIdOnPage); query.ListItemCollectionPosition = pos; //page info spListItems = spList.GetItems(query); lastItemIdOnPage = spListItems.ListItemCollectionPosition.PagingInfo; // Code to enumerate the spListItems. // If itemCount <2000, we finish the enumeration. itemCount = spListItems.Count;

}

The following example shows how to enumerate and paginate a large list.

SPWeb oWebsite = SPContext.Current.Web;SPList oList = oWebsite.Lists["Announcements"];

SPQuery oQuery = new SPQuery();oQuery.RowLimit = 10;int intIndex = 1;

do{ Response.Write("<BR>Page: " + intIndex + "<BR>"); SPListItemCollection collListItems = oList.GetItems(oQuery);

foreach (SPListItem oListItem in collListItems) { Response.Write(SPEncode.HtmlEncode(oListItem["Title"].ToString()) +"<BR>"); }

Page 32: Share Point Interview

oQuery.ListItemCollectionPosition = collListItems.ListItemCollectionPosition; intIndex++;} while (oQuery.ListItemCollectionPosition != null);

o Getting items by identifier

Instead of using SPList.Items.GetItemById, use SPList.GetItemById(int id, string field1, params string[] fields). Specify the item identifier and the field that you want.

2. Do not enumerate entire SPList.Items collections or SPFolder.Files collections.

Accessing the methods and properties that are listed in the left column of the following table will enumerate the entire SPList.Items collection, and cause poor performance and throttling for large lists. Instead, use the alternatives listed in the right column.

Table 1. Alternatives to SPList.Items

Poor Performing Methods and Properties Better Performing Alternatives

SPList.Items.Count SPList.ItemCount

SPList.Items.XmlDataSchema Create an SPQuery object to retrieve only the items you want.

SPList.Items.NumberOfFields Create an SPQuery object (specifying the ViewFields) to retrieve only the items you want.

SPList.Items[System.Guid] SPList.GetItemByUniqueId(System.Guid)

SPList.Items[System.Int32] SPList.GetItemById(System.Int32)

SPList.Items.GetItemById(System.Int32) SPList.GetItemById(System.Int32)

SPList.Items.ReorderItems(System.Boolean[],System.Int32[],System.

Int32)

Perform a paged query by using SPQuery and reorder the items within each page.

SPFolder.Files.Count SPFolder.ItemCount

Note:

The SPList.ItemCount property is the recommended way to retrieve the number of items in a list. As a side effect of tuning this property for performance, however, the property can occasionally return unexpected results. If the precise number is required, you should use the poorer performingshown in the preceding code example.

3. Use PortalSiteMapProvider (Microsoft Office SharePoint Server 2007 only).

Steve Peschka's white paper Working with Large Lists in Office SharePoint Server 2007 describes an efficient approach to retrieving list data in Office SharePoint Server 2007 by using

Page 33: Share Point Interview

the PortalSiteMapProvider class. PortalSiteMapProvider provides an automatic caching infrastructure for retrieving list data. TheGetCachedListItemsByQuery method of PortalSiteMapProvider takes an SPQuery object as a parameter, and then checks its cache to determine whether the items already exist. If they do, the method returns the cached results. If not, it queries the list and stores the results in a cache. This approach works especially well when you are retrieving list data that does not change significantly over time. When data sets change frequently, the class incurs the performance cost of continually writing to the cache in addition to the costs of reading from the database. Consider that the PortalSiteMapProvider class uses the site collection object cache to store data. This cache has a default size of 100 MB. You can increase the size of this cache for each site collection on the object cache settings page for the site collection. But this memory is taken from the shared memory available to the application pool and can therefore affect the performance of other applications. Another significant limitation is that you cannot use the PortalSiteMapProvider class in applications based on Windows Forms. The following code example shows how to use this method. 

Good Coding Practice

Using PortalSiteMap Provider

// Get the current SPWeb object. SPWeb curWeb = SPControl.GetContextWeb(HttpContext.Current);

// Create the query. SPQuery curQry = new SPQuery(); curQry.Query = "<Where><Eq><FieldRef Name='Expense_x0020_Category'/><Value Type='Text'>Hotel</Value></Eq></Where>";

// Create an instance of PortalSiteMapProvider. PortalSiteMapProvider ps = PortalSiteMapProvider.WebSiteMapProvider; PortalWebSiteMapNode pNode = ps.FindSiteMapNode(curWeb.ServerRelativeUrl) as PortalWebSiteMapNode;

// Retrieve the items.

SiteMapNodeCollection pItems = ps.GetCachedListItemsByQuery(pNode, "myListName_NotID", curQry, curWeb);

// Enumerate through all of the matches. foreach (PortalListItemSiteMapNode pItem in pItems) { // Do something with each match. }

4. Whenever possible, acquire a reference to a list by using the list's GUID or URL as a key.

You can retrieve an SPList object from the SPWeb.Lists property by using the list's GUID or display name as an indexer. Using SPWeb.Lists[GUID] andSPWeb.GetList(strURL) is always preferable to using SPWeb.Lists[strDisplayName]. Using the GUID is preferable because it is

Page 34: Share Point Interview

unique, permanent, and requires only a single database lookup. The display name indexer retrieves the names of all the lists in the site and then does a string comparison with them. If you have a list URL instead of a GUID, you can use the GetList method to look up the list's GUID in the content database before retrieving the list. 

Deleting Multiple Versions of a List Item

When you delete multiple versions of a list item, use the DeleteByID method; do not use the Delete method. You will experience performance problems if you delete eachSPListItemVersion object from an SPListItemVersionCollection object. The recommended practice is to create an array that contains the ID properties of each version and then delete each version by using the SPFileVersionCollection.DeleteByID method. The following code examples demonstrate both the approach that is not recommended and the recommended approach to deleting all versions of the first item of a custom list.

Bad Coding Practice

Deleting each SPListItemVersion object

SPSite site = new SPSite("site url");SPWeb web = site.OpenWeb();SPList list = web.Lists["custom list name"];SPListItem item = list.GetItemById(1); SPListItemVersionCollection vCollection = item.Versions;ArrayList idList = new ArrayList();foreach(SPListItemVersion ver in vCollection){ idList.Add(ver.VersionId);}foreach(int verID in idList){ SPListItemVersion version = vCollection.GetVersionFromID(verID); try{ version.Delete();}catch (Exception ex){ MessageBox.Show(ex.Message); }}

Good Coding Practice

Deleting each version of a list item by using the SPFileVersionCollection.DeleteByID method

SPSite site = new SPSite("site url");SPWeb web = site.OpenWeb();SPList list = web.Lists["custom list name"];SPListItem item = list.GetItemById(1);

Page 35: Share Point Interview

SPFile file = web.GetFile(item.Url);SPFileVersionCollection collection = file.Versions;ArrayList idList = new ArrayList();foreach (SPFileVersion ver in collection){ idList.Add(ver.ID);}foreach (int verID in idList){try{ collection.DeleteByID(verID);}catch (Exception ex){ MessageBox.Show(ex.Message); }}

If you are deleting versions of items in a document library, you can use a similar approach by retrieving the SPListItem.File.Versions property, as in the following code example.

Good Coding Practice

Deleting each version of a list item in a document library by using the SPFileVersionCollection.DeleteByID method

SPSite site = new SPSite("site url");SPWeb web = site.OpenWeb();SPList list = web.Lists["custom list name"];SPFile file = list.RootFolder.Files[0];SPFileVersionCollection collection = file.Versions;

ArrayList idList = new ArrayList();foreach (SPFileVersion ver in collection){ idList.Add(ver.ID);}foreach (int verID in idList){try{ collection.DeleteByID(verID);}catch (Exception ex){ MessageBox.Show(ex.Message); }}

Page 36: Share Point Interview

Writing Applications That Scale to Large Numbers of Users

You might not be aware that you need to write your code to be scalable so that it can handle multiple users simultaneously. A good example is creating custom navigation information for all sites and subsites on each page or as part of a master page. If you have a SharePoint site on a corporate intranet and each department has its own site with many subsites, your code might resemble the following.

public void GetNavigationInfoForAllSitesAndWebs(){ foreach(SPSite oSPSite in SPContext.Current.Site.WebApplication.Sites) { try { SPWeb oSPWeb = oSPSite.RootWeb; AddAllWebs(oSPWeb ); } finally { oSPSite.Dispose(); } }}

public void AddAllWebs(SPWeb oSPWeb){ foreach(SPWeb oSubWeb in oSPWeb.Webs) { try { //.. Code to add items .. AddAllWebs(oSubWeb); } finally { if (oSubWeb != null) oSubWeb.Dispose(); } }}

While the previous code disposes of objects properly, it still causes problems because the code iterates through the same lists over and over. For example, if you have 10 site collections and an average of 20 sites or subsites per site collection, you would iterate through the same code 200 times. For a small number of users this might not cause bad performance. But, as you add more users to the system, the problem gets worse, as shown in Table 2.

Table 2. Iterations increase as number of users increases

Page 37: Share Point Interview

Users Iterations

10 2000

50 10000

100 200000

250 500000

Although the code executes for each user that hits the system, the data remains the same for each user. The impact of this can vary depending on what the code is doing. In some cases, repeating code might not cause a performance problem; however, in the previous example the system must create a COM object (SPSite or SPWeb objects are created when retrieved from their collections), retrieve data from the object, and then dispose of the object for each item in the collection. This can have a significant impact on performance.

How to make this code more scalable or fine-tune it for a multiple user environment can be a hard question to answer. It depends on what the application is designed to do.

You should take the following into consideration when asking how to make code more scalable:

Is the data static (seldom changes), somewhat static (changes occasionally), or dynamic (changes constantly)?

Is the data the same for all users, or does it change? For example, does it change depending on the user who is logged on, the part of the site being accessed, or the time of year (seasonal information)?

Is the data easily accessible or does it require a long time to return the data? For example, is it returning from a long-running database query or from remote databases that can have some network latency in the data transfers?

Is the data public or does it require a higher level of security?

What is the size of the data?

Is the SharePoint site on a single server or on a server farm?

How you answer the previous questions will determine in which of several ways you can make your code more scalable and handle multiple users. The intent of this article is not to provide answers for all of the questions or scenarios but to provide a few ideas that you can apply to your specific needs. The following sections offer areas for your consideration.

Caching Raw Data

You can cache your data by using the System.Web.Caching.Cache object. This object requires that you query the data one time and store it in the cache for access by other users.

Page 38: Share Point Interview

If your data is static, you can set up the cache to load the data only one time and not expire until the application is restarted, or to load the data once per day to ensure data freshness. You can create the cache item when the application starts, when the first user session starts, or when the first user tries to access that data.

If your data is somewhat static, you can set up the cached items to expire within a certain number of seconds, minutes, or hours after the data is created. This enables you to refresh your data within a timeframe that is acceptable to your users. Even if the data is cached for only 30 seconds, under heavy loads you will still see improved performance because you are running the code only one time every 30 seconds instead of multiple times per second for each user who hits the system.

Security trimming is another issue to consider whenever you cache data. For example, if you cache items as you iterate through a list, you may get only a subset of the data (the data that the current user can see), or if you use a DataTable object to cache all of the items in a list, you have no easy way of applying security trimming to users who belong to groups that can see only a subset of the data. For more information about storing security trimmed data in caches, see the CrossListQueryCache class.

In addition, ensure you consider the issues described earlier in Caching Data and Objects.

Building Data Before Displaying It

Think about how your cached data will be used. If this data is used to make run-time decisions, putting it into a DataSet or DataTable object might be the best way to store it. You can then query those objects for the data to make run-time decisions. If the data is being used to display a list, table, or formatted page to the user, consider building a display object and storing that object in the cache. At run time, you need only retrieve the object from the cache and call its render function to display its contents. You could also store the rendered output; however, this can lead to security issues and the cached item could be quite large, causing increased page swapping or memory fragmentation.

Caching For a Single Server or Server Farm

Depending on how you set up your SharePoint site, you might have to address certain caching issues differently. If your data must be the same on all servers at all times, then you must ensure that the same data is cached on each server.

One way to ensure this is to create the cached data and store it on a common server or in a Microsoft SQL Server database. Again, you must consider how much time it takes to access the data and what security issues can arise from storing the data on a common server.

You can also create business-layer objects that cache data on a common sever, and then access that data by using various interprocess communications that are available in networking objects or APIs.

Using SPQuery Objects

SPQuery objects can cause performance problems whenever they return large result sets. The following suggestions will help you optimize your code so that performance will not suffer greatly whenever your searches return large numbers of items.

Page 39: Share Point Interview

Do not use an unbounded SPQuery object.

An SPQuery object without a value for RowLimit will perform poorly and fail on large lists. Specify a RowLimit between 1 and 2000 and, if necessary, page through the list.

Use indexed fields.

If you query on a field that is not indexed, the query will be blocked whenever it would result in a scan of more items than the query threshold (as soon as there are more items in the list than are specified in the query threshold). Set SPQuery.RowLimit to a value that is less than the query threshold.

If you know the URL of your list item and want to query by FileRef, use SPWeb.GetListItem(string strUrl, string field1, params string[] fields) instead.

Using Web Controls

When you inherit and override controls in the Microsoft.SharePoint.WebControls namespace, remember that SharePoint Web controls are templated controls. Unlike Microsoft ASP.NET Web controls, they are defined and rendered with templates instead of with the CreateChildControls method. Instead of having a thick CreateChildControls method that uses the new operator to create child controls, perform most child control creation and rendering by using the rendering templates that are referenced in the Template,AlternateTemplate, DisplayTemplate, CustomTemplate, and AlternateCustomTemplate properties of the SharePoint Web control. SharePoint Web controls do inherit theCreateChildControls method, but that method should typically do little or nothing beyond calling the parent control's CreateChildControls method and perhaps a bit of "final polish" rendering, such as assigning default values to child control properties in New mode or assigning the current values in Edit mode.

For an example, see Walkthrough: Creating a Custom Field Type. In addition, see the Microsoft.SharePoint.WebControls namespace.

Creating Timer Jobs

Design your timer jobs so that they consist of small, manageable pieces. Because administrators and other events, such as system restarts, can stop timer jobs, you can minimize the amount of rework after any interruption by breaking timer jobs into small pieces of work.

Conclusion

To ensure that your SharePoint system performs at its best, you need to be able to answer the following questions about the code you write:

Page 40: Share Point Interview

Does my code properly dispose of SharePoint objects? 

Does my code cache objects properly?

Does my code cache the correct types of objects?

Does my code use thread synchronization when necessary?

Does my code work as efficiently for 1,000 users as it does for 10 users? 

[SPSite] Represents a collection of sites on a virtual server, including a top-level site and all its subsites. Each SPSiteobject, or site collection, is represented within an SPSiteCollection object that consists of the collection of all site collections on the virtual server.

SPWeb Represents a SharePoint Web site.

SharePoint uses custom HTTPHandlers (SPHTTPHandler) and custom HTTPModules (SPRequestModule) to make it a sharepoint site.

Virtual Provider is nothing but HTTPHandler and HTTPModule to identify from where to display pages (from content database or from file system)

Definitions :

Web Parts are componentized, self-contained packages of user interface that can be dropped into place on SharePoint Web Part pages to provide discrete sets of functionality to users.It can be incredibly easy to get confused between sites, webs, web applications, and site collections. The farm is the topmost level in the hierarchy. Below the farm, you have web applications represented by the SPWebApplication class, which typically correspond to an IIS application pool. Below that, you have a collection of site collections contained in the SPSiteCollection class. Finally, you have site collections represented by the SPSite class and individual websites represented by the SPWeb class.

Features allow reusable pieces of functionality to be created and deployed to other

Page 41: Share Point Interview

sites,without modifying site templates.It is always better to deploy a feature in new site instead ofdirectly embedding mountains of complex XML.Using Features, you can do everything from adding a link to the Site Settings page to creating a complete, fully functioning Project Management suite that can be added to any SharePoint site.Features are organized in folders under the Features directory located under 12 hives; Where SharePoint Server 2007 puts all of its system files, at the following path: %SystemDrive%\Program Files\Common Files\Microsoft Shared\web server extensions\12. The two files that are used to define a feature are the feature.xml and Elements.xml .The feature XML file defines the actual feature and will make SharePoint aware of the installed feature. It usually identifies the Feature itself and its element manifest file and sets the Feature scope to Web site.Elements.xml file identifies the assembly, class, and method to implement in feature.

You can directly deploy a feature in sharepoint site with

stsadm -o installfeature -filename XYZEventHandler\Feature.xml

stsadm -o activatefeature -filename DeletingEventHandler\Feature.xml -url href="http://server/Site/Subsite">http://Server/Site/Subsite

iisreset

OR To Deploy it as solution package you need a solution manifest (manifest.xml).

Solutions allow you to package Features in a cabinet (.cab) file and define important metadata about those Features. After a Solution is installed on a server in the farm, you can then use SharePoint’s Solution management features to automate the deployment of that Solution to other sites within the farm.

The solution manifest (always called manifest.xml) is stored at the root of a solution file. This file defines the list of features, site definitions, resource files, Web Part files, and assemblies to process. It does not define the file structure—if files are included in a solution but not listed in the manifest XML file, they are not processed in any way.

Because the solution file is essentially a .cab file, use the makecab.exe tool to create the solution package. The makecab.exe tool takes a pointer to a .ddf file, which describes the structure of the .cab file. The format of a .ddf file is, declare a standard header and then enumerate, one file per line, the set of files by where they live on disk, separated by where they should live in the .cab file.

Features & Solutions:The Feature Framework has been extended to allow developers to create custom Features. Features can be deployed by using SharePoint Portal Server 2007 new form of deployment, namely Solution Deployment. Solutions as you know, are custom packages (e.g. WSP file) or redistributable CAB files, created by developers and deployed by SharePoint Administrators. Administrator can deploy Features to the individual site or to all Web front End Servers.

Page 42: Share Point Interview

Features are a method for developers to package customisations and deploy them to the SharePoint portal. They can then be activated and deactivated at the Site Collection level. Solutions are a way to bundle features together for deployment.

Custom action : Represents a link, toolbar button, menu item, or any control that can be added to a toolbar or menu that appears in the UI. You define custom actions by using a custom action element within a feature definition file. You can bind custom actions to a list type, content type, file type, or programmatic identifier (ProgID). For more information, see Custom Action Definitions.

Event receiver: Evaluator of an event and definer of the behavior of an application. Windows SharePoint Services 3.0 allows you to define event handlers within libraries, lists, and sites. Event receivers can be defined by using a receiver element within a feature definition file. For more information, see Event Registrations.

Master page: Pages that provide a consistent layout and appearance (look and feel) for SharePoint sites. They allow you to factor out layout, structure, and interface elements such as headers, footers, navigation bars, and content placeholders. Master pages in ASP.NET 2.0 and master pages in Windows SharePoint Services work in the same way. For more information, see Building Simple Master Pages for Windows SharePoint Services 3.0.

Module : A file or collection of file instances that define the location where the files are installed during site creation. Modules are frequently used to implement a Web Part Page in the site. You can define modules by using a module element within a feature definition file. For more information, see Modules.

SharePoint site: A Web site hosted in a virtual URL. A SharePoint site is a place for collaboration, communication, or content storage. Depending on your business needs, you can create sites such as team sites, blog sites, wiki sites, and others. You can customize a site's appearance, users, user permissions, galleries, and site administration by using the Site Settings administration pages.

SharePoint site collection: A collection of SharePoint sites that share common administration pages and site settings. Site collections allow you to share content types, site columns, templates, and Web Parts within a group of SharePoint sites.

SharePoint Web farm: A group of Office SharePoint 2007 servers that share the same configuration database. All site content and all configuration data is shared for all front-end Web servers in a server farm.

Page 43: Share Point Interview

Site definition.: A set of files that includes a master XML configuration file that is stored on all front-end Web servers. A site definition provides the basic blueprint for how sites look, what lists they include, their default navigational structures, and so on. For more information, see Working with Site Templates and Definitions.

Theme: A group of files (CSS, images) that allow you to define the appearance (look and feel) of Web pages. Themes in ASP.NET 2.0 and themes in SharePoint Products and Technologies work in the same way. Themes are used to help organizations to brand their portals and team sites. Office SharePoint Server 2007 includes a set of predefined themes. However, as a developer, you can create custom themes for your company. For more information, see How to: Customize Themes.