Saturday, November 14, 2009

Error and Resolution using SharePoint List web service

Problem #1
I have used the following code to connect to SharePoint list and upload data
Reference the SharePoint web service as ListService
http://servername:9000/_vti_bin/lists.asmx


ListService.ListsSoapClient addlist = new ListService.ListsSoapClient();
addlist.ClientCredentials.Windows.ClientCredential = System.Net.CredentialCache.DefaultNetworkCredentials;
addlist.ClientCredentials.Windows.AllowedImpersonationLevel = System.Security.Principal.TokenImpersonationLevel.Impersonation;
addlist.Endpoint.Address = new System.ServiceModel.EndpointAddress(sharePointServerUrl + "/_vti_bin/Lists.asmx");
// Input Data for the list
XmlDocument doc = new XmlDocument();
XmlElement batch = doc.CreateElement("Batch");

// NEw in the above XMl for new Element addtion
XmlElement result = addlist.UpdateListItems("share Point ListName" , batch);
Issue #1
I got the Error message "Exception of type 'Microsoft.SharePoint.SoapServer.SoapServerException' was thrown. "
Solution #1
The sharePoint list name in the UpdateListItems method was incorrect and changed that, then worked well for me.

Issue #2
XmlElement result = addlist.UpdateListItems("share Point ListName" , batch);
result.InnerText shows "0x81020014One or more field types are not installed properly. Go to the list settings page to delete these fields." and the list was not updated properly
Solution #2
The issue is due to the non usage of internal names for the field names. So check the internal name of the fields in the list and changed accordingly as below. In the input XML (batach.InnerXml) , use Field Name='Last_x0020_Name' (This is the internal name of the field) instead of Field Name='Last Name'. Use internal names for the field instead of display names. This worked for me.
Also check the case of the internal field name( LastName and Lastname are different). Use the correct casing in field name to work properly.
Issue #3
addlist.UpdateListItems("share Point ListName" , batch);
Error while updating the list item
0x80070005The operation failed because an unexpected error occurred. (Result Code: 0x80070005)
Solution #3
The list doesn't have update access to the user. Providing access to the list solves this issue

Tuesday, May 12, 2009

Smartpart in SharePoint (MOSS) 2007 - Easy Web User Controls

The SmartPart is a generic webpart that can contain an ASP.NET user control. Nothing new you would say, but the SmartPart can give your user control access to the SharePoint object model.

Smart Part allows developers to code simple (or complex) Web User Controls (.ascx files) utilizing the full set of visual development tools in VS and then deploy the result to a SharePoint (MOSS) 2007 site by just configuring the url of the user controls.

Need for SmartPart and it's benefits

  • The SmartPart is a SharePoint Webpart that can host any ASP.NET user control. Creation webparts by using the VS.NET designer(user control) instead of coding everything by hand.
  • It complies with sharepoint object model since it's a type of web part.
  • Easy to deploy user controls in MOSS sites
  • Simple configuration
  • Supports AJAX and hence we can create AJAX enabled Smartpart eaily.

The following steps shows the steps to create and deploy the smartpart in MOSS site

Step 1: Create a SmartPart
TO create a smartpart, we need to create a library project using visual studio editor and add the following code. Add the reference to Microsoft.SharePoint.dll.

using System;
using System.ComponentModel;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Xml.Serialization;
using Microsoft.SharePoint;
using Microsoft.SharePoint.Utilities;
using Microsoft.SharePoint.WebPartPages;
namespace SmartpartSample
{
/// <summay>
/// Description for UserControlContainer.
/// </summay>

[DefaultProperty("Text"),
ToolboxData("<{0}:UserControlContainer runat=server>"),
XmlRoot(Namespace = "SmartpartSample")]
public class SmartpartSample : Microsoft.SharePoint.WebPartPages.WebPart
{
private const string defaultText = "";
private string _userControl = defaultText;
private Control _control = null;

[Browsable(true),
Category("User Control"),
DefaultValue(defaultText),
WebPartStorage(Storage.Personal),
FriendlyName("User Control (.ascx)"),
Description("Path to the User Control (.ascx)")]

public string UserControl
{
// This property has the URL of the user control to be displayed in the web part
get
{
return _userControl;
}
set
{
_userControl = value;
}
}
/// <summay>
/// This method gets the custom tool parts for this Web Part by overriding the
/// GetToolParts method of the WebPart base class. You must implement
/// custom tool parts in a separate class that derives from
/// Microsoft.SharePoint.WebPartPages.ToolPart.

///An array of references to ToolPart objects.
/// </summay>
public override ToolPart[] GetToolParts()
{
// These tool parts are to set the properities of the smart part
ToolPart[] toolparts = new ToolPart[2];
WebPartToolPart wptp = new WebPartToolPart();
CustomPropertyToolPart custom = new CustomPropertyToolPart();
toolparts[0] = custom;
toolparts[1] = wptp;
wptp.Expand(Microsoft.SharePoint.WebPartPages.WebPartToolPart.Categories.Appearance);
custom.Expand("User Control");
return toolparts;
}

/// <summay>
/// Load the UserControl
/// </summay>

protected override void CreateChildControls()
{
base.CreateChildControls();
try
{
if (_userControl != defaultText)
{
_control = this.Page.LoadControl(_userControl);
}
else
{
_control = new LiteralControl(string.Format("To link to content, open the tool pane and then type a URL in the Link text box.", 1, 129, this.ID));
}
}
catch (System.Exception ex)
{
_control = new LiteralControl(string.Format("Error: unable to load {0}
Details: {1}", _userControl, ex.Message));
}
if (_control != null)
{
// Add to the Controls collection to support postback
this.Controls.Add(_control);
}
}

/// <summay>
/// Render this Web Part to the output parameter specified.
/// </summay>

/// The HTML writer to write out to
protected override void RenderWebPart(HtmlTextWriter output)
{
EnsureChildControls();
if (_control != null)
{
_control.RenderControl(output);
}
}
}
}

Step 2: Adding the smart part into MOSS Site
1. Place the dll of the smart part project into the bin folder present in the virtual directory folder of the MOSS site.
2. Add a safe control entry for the smart part in the web.config file of the MOSS Site.

<SafeControl Assembly="Assembly Name of the SmartPart, Version=1.0.0.0, Culture=neutral" Namespace="Namespace of the SmartPart" TypeName="*" Safe="True" />

3. Modify the trust level to WSS_Medium in the web.config as shown below.
<trust level="Full" originUrl="" />

4. Open the SharePoint portal where the web parts have to be deployed.

5. Click on Site Actions->Site Settings->Modify All Site Settings

6. Click on Web parts option under Galleries

7. Click on New tab on the Web Part Gallery page.

8. Click on the checkboxes against the Smart part which we have deployed using the above mentioned steps.

9. Click the “Populate Gallery” button.

Step 3: Placing the User Controls and link to MOSS site

1. Copy the User controls to the UserControls folder in the Virtual directory of the MOSS Site.

2. If the UserControls folder is not available create the same.

Step 4: Using the smart in the site pages

1. Create a new page in the MOSS site and edit the page.

2. Add the Smart Part to the page and edit the properties of the smart part.

3. In the properties window of the smart part provide the user control path to be loaded in that page.

4. The path of the usercontrol file should be in this format “~\UserControls\UserControl File Name”.

5. Click on OK button, now the User control should be visible on the page.

6. Exit the page edit mode.

Tuesday, May 5, 2009

Frequently asked interview questions in MOSS 2007 - Part II

This article explains the frequently asked interview questions in MOSS 2007 (SharePoint) with answers. This covers basic and advanced concepts of MOSS

If you have not gone through the first part of the FAQs, click here (Part One)

1. What all elements of SharePoint to which Workflows can be applied?
While workflow associations are often created directly on lists and document libraries, a workflow association can also be created on a content type that exists within the Content Type Gallery for the current site or content types defined within a list. Workflows are applied at

  • At the level of a list (or document library)
  • At the level of a content type defined at site scope
  • At the level of a content type defined at list scope

2. What are the ways to initiate the workflow?
The following ways in which the workflows can be initiated

  • Automatic (without User Interface and no user inputs)
  • Manual (standard WSS UI interface - Out of the box user interfaces)
  • Manual (Custom UI Interface developed using .net or InfoPath forms)

3. What are the types of input forms that can be created for a workflow?
You can create four different types of input forms including

  • Association form
  • Initiation form
  • Modification form
  • Task edit form.
Create a Custom Workflow in MOSS with input forms is available here
Note that these forms are optional when you create a workflow template.

4. What are ways to create input forms for workflow?
Two different approaches can be used to develop custom input forms for a WSS workflow template.
  • You can create your forms by using custom application pages, which are standard .aspx pages deployed to run out of the _layouts directory. (The disadvantage with this approach is lot of code required when compared to InfoPath approach).
  • Using Microsoft Office InfoPath 2007 (The disadvantage with this approach is dependent on MOSS and it cannot run in a standalone WSS environment)


5. What is the difference between method activity and event activity in Workflow?

A method activity is one that performs an action, such as creating or updating a task.

An event activity is one that runs in response to an action occurring.

6. What does SPExport/SPImport class do?

This class is available in Microsoft.SharePoint.Deployment namespace.SPExport Supports export of specified content from a source Windows SharePoint Services site collection to a CAB file (with .cmp file extension or custom file extension) in XML format.

SPImport class Supports importing specified content into a Windows SharePoint Services site collection using a migration package (.cmp) file in XML format.Using these APIs, we can Export and Import

To learn more about these APIs, Click here


7. What are the defaults SharePoint permission groups available? How this is different from windows security groups?

Following SharePoint groups are provided by default.

  • Reader - Has read-only access to the Web site.
  • Contributor - Can add content to existing document libraries and lists.
  • Web Designer - Can create lists and document libraries and customize pages in the Web site.
  • Administrator - Has full control of the Web site.

The permissions can be applied at

  • Site collection level
  • Web site/ sub site level
  • Library or list levelList item or page level

We can add Windows user accounts and Windows security groups to your SharePoint groups for providing access.

8. What are the different types of search queries in SharePoint?

Search in Windows SharePoint Services supports three types of search syntax for building search queries:

  • Keyword Query syntax (search terms are passed directly to the Search service using OOB web parts like Search Web part)
  • SQL syntax (extension of SQL syntax for querying crawl databases by customizing the CoreResultsWebPart)
  • URL syntax (search parameters are encoded in URL, and posted directly to the search page E.g http://localhost/search/Results.aspx?q=keyword)

To learn more about search queries click here

9. What is the relationship between Microsoft SharePoint Portal Server and Microsoft Windows Services?

Microsoft SharePoint Products and Technologies (including SharePoint Portal Server and Windows SharePoint Services) deliver highly scalable collaboration solutions with flexible deployment and management tools. Windows SharePoint Services provides sites for team collaboration, while Share Point Portal Server connects these sites, people, and business processes—facilitating knowledge sharing and smart organizations. SharePoint Portal Server also extends the capabilities of Windows SharePoint Services by providing organizational and management tools for SharePoint sites, and by enabling teams to publish information to the entire organization.


10. What does SPWeb.EnsureUser method do?

Checks whether the specified login name belongs to a valid user of the Web site, and if the login name does not already exist, adds it to the Web site.

e.g

SPSite site = new SPSite("http://localhost");

SPWeb myweb = site.OpenWeb("");

SPUser usr = myWeb.EnsureUser("username");


11. While creating a Webpart, which is the ideal location to Initialize my new controls?

Override the CreateChildControls method to include your new controls. To make sure that the new controls are initialized. call 'EnsureChildControls' in the webparts Render method. You can control the exact Rendering of your controls by calling the .Render method in the webparts Render method.


12. How to query from multiple lists ?

Use SPSiteDataQuery to fetch data from multiple lists.

13. What are User Defined functions in Excel Services Calculation?

User-defined functions (UDFs) are custom functions that extend the calculation and data-import capabilities of Excel. Developers create custom calculation packages to provide:

  • Functions that are not built into Excel.
  • Custom implementations to built-in functions.
  • Custom data feeds for legacy or unsupported data sources, and application-specific data flows.

To use custom functions in a class as an Excel Services UDF class, you must mark your UDF class and method with the Microsoft.Office.Excel.Server.Udf.UdfClass and Microsoft.Office.Excel.Server.Udf.UdfMethod attributes.UDF assemblies are disabled by default.To Enable UDF Assemblies,Each Excel Services trusted location in the Shared Services Provider (SSP) has an AllowUdfs flag to true.


14. What are the sources of User Profiles information in SharePoint?

User Profile information can be imported from Active Directory through master connection.

In addition to Active Directory, importing profile information from all of the following data sources using Business Data Catalogue (BDC)

  • LDAP directory (which is not Active Directory)
  • Databases such as SQL Server
  • Enterprise applications (like SAP or PeopleSoft)


15. What is the use of query.ViewAttributes OR how can you force SPQuery to return results from all the folders of the SharePoint list?

If you use SPQuery on any SPlist, it will bring back results from the current folder only (One level only).If you want to get results from all the folders in the list (including sub folders) then you need to specify the scope of the query by the use of ViewAttributes.

e.g. SPList oList = oWebsite.Lists["DocLib_Name"];

SPView oView = oList.Views["View_Name"];

SPQuery oQuery = new SPQuery(oView);

oQuery.ViewAttributes = "Scope=\"Recursive\"";




Friday, May 1, 2009

Frequently asked interview questions in MOSS 2007

This article explains the frequently asked interview questions in MOSS 2007 (SharePoint) with answers

1. What MOSS (SharePoint) offers?

  • A framework that allows building business sites rapidly.
  • Lots of Out of the box features, Workflows and site templates already built-in Excellent integration with Word, Excel, PowerPoint etc
  • Audience Targeting and Document collaboration
  • Enterprise Search for content and people search
  • Wikis and Blogs
  • Really Simple Syndication (RSS) support

2. Is SharePoint supports Globalization?

Yes. Install different language packs for SharePoint. To learn about installing language pack, click here

3. Does SharePoint search results supports audience filtering?

The default SharePoint search results based on

  • Security of the items
  • Input keyword

The default search doesn’t support filter based on audience targeting. But we can customize coreresultswebpart to do that. To learn more about customizing core results web part is here


4. What is Shared Service Provider (SSP) in MOSS?

In MOSS 2007 there is this new concept of Shared Services Providers (SSP). The idea being that there are certain services that really make sense to centrally manage and share. A good example is user profiles. With a SSP we can import all of the profile information from AD (thru master connection) once as well as BDC (Business Data Catalog) and then our various web applications can consume the data. So maybe we have http://mossapp1/ and http://mossapp2/ it doesn't make sense for each one to maintain identical profile information, they should share.

The major services of SSP

  • Profiles and Audiences
  • My Sites
  • Search configuration
  • Excel Services
  • BDC (Business Data Catalog)
  • Manage usage analytics

5. Some of Out of the box web parts and its usage?

Web Part is a modular unit of information that consists of a title bar, a frame, and content. Web Parts are the basic building blocks of a Web Part Page. Web Part Page is a special type of Web page that contains one or more Web Parts.

Some of the major web parts are

  • Content Editor Web Part to add formatted text, tables, hyperlinks, and images to a Web Part Page. The Content Editor Web Part is intended for adding HTML content to a Web Part Page.

  • Page Viewer Web Part is to display a Web page, file, or folder on a Web Part Page. You enter a hyperlink, file path, or folder name to link to the content. You can use the Page Viewer Web Part only in a browser that supports the HTML IFRAME element. Displaying a file or folder requires Microsoft Internet Explorer.

  • Content Query Web Part (CQW or CQWP) is to display SharePoint content from another source like SharePoint list, pages library on a SharePoint page.

  • A Summary Link Web Part and a Summary Link field control both provide an easy way to build a page of links to various resources, both inside and outside of your site. You can control the appearance, organization, and presentation of the links that you add to a Summary Link Web Part or field control.

  • A Table of Contents Web Part is a configurable component that you can add to a Web Part Page. You use the Table of Contents Web Part to automatically generate a site map that point to various parts of your Office SharePoint Server 2007 site collection. When you add a Table of Contents Web Part to a page, you specify which part of your site collection the Web Part should generate links to, how the links are presented, and how the links are organized.

  • My Inbox web part Shows Inbox, open e-mail messages and even forward, reply, etc.
    Search Core Results Web Part, one of the most important ones displaying the search results to the user.

  • Excel Web Access web part is a feature of MOSS enterprise Edition. This web part is used to display an excel file from a Trusted file location. This comes as part of Excel services.

  • A Key Performance Indicator (KPI) web part is a visual cue that communicates the amount of progress made toward a goal. This article explains how to create KPIs by using Microsoft Office SharePoint Server 2007 KPI lists and how to display KPIs on Web pages.

6. What are the Components of Excel Services in MOSS?

There are three major components of Excel services

  • Excel Web Access
  • Excel Web Services
  • Excel Calculation Services

7. Personalization in MOSS and it’s different models

Personalization means providing a user centered experience of the Portal. Keeping user settings and preferences same every time the user logs in.

There are three main features in MOSS 2007 personalization model.

User profiles allow you to search and connect with people within your organization based on information published about them. MOSS 2007 provides a new search scope for searching people. Index Server crawls the user profile store to get the user’s information.


Audience Targeting: MOSS 2007 allows you to target content to people according to their membership in a particular audience. It supports targeting to rules-based audiences, distribution lists, and Windows SharePoint Services groups. Except for Windows SharePoint Services groups, these audiences can span one or more portal sites in a deployment.
Using targeting, you can target content in the portal site for viewing by one or more specific audiences. By default, you can display targeted content on the home page and on personalization sites.


My Site is a collection of Profile pages, personal sites, and personalization sites created in the Office SharePoint Server 2007 site. The Profile page of the My Site displays your user profile information. Your personal site provides personalized and customized information. Office SharePoint Server 2007 also supports personalization sites. Personalization sites display targeted content to users based on their membership in a particular audience or by slicing data.


8. What is WSS?

Windows SharePoint Services (WSS) is a set of components and services that is considered part of the Windows Server 2003 operating system. However, licensing and support for WSS is controlled by the Windows platform team, not the Office team.

Microsoft Windows SharePoint Services 3.0 is a versatile technology that organizations and business units of all sizes can use to increase the efficiency of business processes and improve team productivity. With tools for collaboration that help people stay connected across organizational and geographic boundaries, Windows SharePoint Services gives people access to information they need.
Built on Microsoft Windows Server 2003, Windows SharePoint Services also provides a foundation platform for building Web-based business applications that can flex and scale easily to meet the changing and growing needs of your business. Robust administrative controls for managing storage and Web infrastructure give IT departments a cost-effective way to implement and manage a high-performance collaboration environment. With a familiar, Web-based interface and close integration with everyday tools including the Microsoft Office system, Windows SharePoint Services is easy to use and can be deployed rapidly.


9. What are the different Workflow Types in MOSS?

Windows Workflow Foundation supports two fundamental workflow styles. You can create workflows of either type for Windows SharePoint Services 3.0.

A sequential workflow represents a workflow as a procession of steps that execute in order until the last activity completes. However, sequential workflows are not purely sequential in their execution. Because they can receive external events, and include parallel logic flows, the exact order of activity execution can vary somewhat.

A state machine workflow represents a set of states, transitions, and actions. One state is denoted as the start state, and then, based on an event, a transition can be made to another state. The state machine can have a final state that determines the end of the workflow.

10. What are content types?

A content type is a flexible and reusable WSS type definition 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 customer presentation document with a unique set of columns, an event handler, and its own document template. You can create a second content type for a customer proposal document with a different set of columns, a workflow, and a different document template.


11. What is the difference between Synchronous and Asynchronous events in MOSS?

Synchronous calls ending with 'ing' E.g. ItemDeleting

  • Occur before the event.
  • Event Handler code execute BEFORE action is committed
  • WSS waits for code to return
  • Option to cancel and return error code

Asynchronous calls ending with 'ed' E.g. ItemDeleted

  • Occur after the event.
  • Event Handler code executes AFTER action is committed
  • WSS does not wait for code to return
  • Executed in its own Worker thread.

Events in MOSS occurs at

  • Site Level - E.g SiteDeleted & SiteDeleting
  • List Level - E.g FieldAdded & FieldAdding
  • List Item Level - E.g ItemAdded & ItemAdding

12. What is ServerUpdate() ?

Any changes in the list, i.e. new addition or modification of an item, the operation is complete by calling the Update method. But if a List is set to maintain versions and you are editing an item, but don't want to save it as a new version, then use the SystemUpdate method instead and pass in 'false' as the parameter.

13. What does AllowUnsafeUpdates do ?

If your code modifies Windows SharePoint Services data in some way, you may need to allow unsafe updates on the Web site, without requiring a security validation. You can do by setting the AllowUnsafeUpdates property.


using(SPSite mySite = new SPSite("http://localhost")){

using(SPWeb myWeb = mySite.OpenWeb())

{myWeb.AllowUnsafeUpdates = true;

SPList interviewList = myWeb.Lists["listtoinsert"];

SPListItem newItem = interviewList.Items.Add();
newItem["test"] = "test";

newItem.Update();}}


14. What does RunWithElevatedPrivileges do?

Executes the specified method with Full Control rights even if the user does not otherwise have Full Control.

Assume that you have a Web Part in which you want to display information obtained through the Windows SharePoint Services object model, such as the name of the current site collection owner, usage statistics, or auditing information. These are examples of calls into the object model that require site-administration privileges. Your Web Part experiences an access-denied error if it attempts to obtain this information when the current user is not a site administrator. The request is initiated by a nonprivileged user. you can still successfully make these calls into the object model by calling the RunWithElevatedPrivileges method provided by the SPSecurity class.
SPSecurity.RunWithElevatedPrivileges(delegate() {

// Add custom code here

});


15.What is a SharePoint Feature? What files are used to define a feature?

A SharePoint Feature is a functional component that can be activated and deactivate at various scopes throughout a SharePoint instances, such as at the farm, site collection, web level etc.

Features have their own receiver architecture, which allow you to trap events such as when a feature is installing, uninstalling, activated, or deactivated. The element types that can be defined by a feature include menu commands, link commands, page templates, page instances, list definitions, list instances, event handlers, and workflows.

The two files that are used to define a feature are the feature.xml and manifest file (elements.xml).

  • The feature XML file defines the actual feature and will make SharePoint aware of the installed feature.
  • The manifest file contains details about the feature such as functionality.

Go to FAQs Part II

Thursday, April 30, 2009

Personalization in MOSS 2007 and Configuring Personalization

Personalization means providing a user centered experience of the Portal. Keeping user settings and preferences same every time the user logs in.

There are three main features in MOSS 2007 (SharePoint) personalization
1. User profiles
User profiles allow you to search and connect with people within your organization based on information published about them. MOSS 2007 provides a new search scope for searching people. Index Server crawls the user profile store to get the user’s information.

2. Audiences
MOSS 2007 allows you to target content to people according to their membership in a particular audience. It supports targeting to rules-based audiences, distribution lists, and Windows SharePoint Services groups. Except for Windows SharePoint Services groups, these audiences can span one or more portal sites in a deployment.
Using targeting, you can target content in the portal site for viewing by one or more specific audiences. By default, you can display targeted content on the home page and on personalization sites.

3. My Site
My Site is a collection of Profile pages, personal sites, and personalization sites created in the Office SharePoint Server 2007 site. The Profile page of the My Site displays your user profile information. Your personal site provides personalized and customized information. Office SharePoint Server 2007 also supports personalization sites. Personalization sites display targeted content to users based on their membership in a particular audience or by slicing data.

How to Create Personalized views in MOSS 2007
SSP(Shared Service provider) is necessary for creating personalized views in SharePoint

i. Audience Targeting

Importing user profiles in SharePoint from Active directory Through master connection

  • Open SSP
  • Under User Profiles and My Sites click on the link labeled “User profiles and properties”
  • On the User Profiles and Properties page click on “Configure profile import”
  • Provide a default access account, specify an account that has read access to your directory. Note: This account needs to also have Manage User Profiles rights, verify click on “Personalization services permissions” under User Profiles and My Sites on the SSP Admin page. To keep things simple until you have a grasp of the service you should use the SharePoint Admin account.

  • Click OK On the User Profiles and Properties page click on “Start full import”
  • Verify that import started and wait until import has completed before moving on to other personalization admin tasks (this may take a few hours)
  • After import is complete to view the results click on “View user profiles” on the User Profiles and Properties page
User Profiles can also be imported from SQL server or other sources using Business Data Catalog (BDC). TO learn more about configuring user profiles, Click here

Creating Audiences from User profiles
Once profile import is complete we can go back to setting up personalization services in the SSP

  • Go to the Shared Services Administration page for your SSP.
  • Click on “Audiences” under the section Audiences
  • On the Manage Audiences page click on “Create audience” Note: Audiences should not be created until after you’ve completed a profile import.
  • create a new audiences rules based on user profile data such as department, role etc.
  • once done creating audiences click on “Start compilation” from the Manage Audiences page.
  • After compilation is complete to view the results click on “View audiences” from the Manage Audiences page.

To display targeted content on SharePoint sites using web parts

  • Go to the site home page and add the Content Query Web Part. Content by query web part supports audience filtering by default.
  • Modify the Content Query Web Part Under Query
  • change List Type to Document Library
  • Under Query -> Audience Targeting check “Apply audience filtering”
  • Click OK Verify the items you targeted in the document library only show for people in those audiences.

ii. My Sites

To create a My Site

  • Click on My Site in the global actions bar which is in the top right corner of every SharePoint page.Wait while your My Site is created
  • After creation is complete check to make sure the name of the site created is titled with your name
  • If not then open a new browser window with your credentials and click the My Site link again or copy the URL behind the My Site link into the browser window.Note: My Site is highly personalized so it works best when its created using your credentials and not those of an admin account or alternate account
  • Follow the links in the Getting Started with My Site web part


iii. People Search

To configure People search in MOSS

  • Go to Shared Services Administration for your SSP Under Search section click on “Search settings”
  • On Configure Search Settings page find the default content access account
  • If this is not set then provide a default content access account Verify default content access account has Use personal features rights.
  • On Configure Search Settings page click on “Content sources and crawl schedules”
  • On the Manage Content Sources page hover over “Local Office SharePoint Server sites” and click the arrow to drop the ECB menu
  • In the drop menu click Start Full Crawl Verify that crawl started and wait until crawl has completed before moving on to search for people.
  • Once crawl is complete to main portal site and click on Search in the top navigation area to go to the Search Center
  • In Search Center click on tab labeled “People”
  • Type in a term you added to your profile while exploring your My Site such as a project, skill or responsibility Hit Enter or click the
  • Go button Verify that you and others who match that search term was returned as search results

Tuesday, April 28, 2009

MOSS Introduction for beginners

Microsoft Office SharePoint Server (MOSS) 2007 helps stream-line collaboration, shared business processes, content management, enterprise search, and data sharing. Whether you are working across departments, companies, or great distances, SharePoint Server 2007 lets you share information and work with others with great ease and complete security.

Custom Development needs for MOSS projects

  • .Net framework 3.0/3.5 depends on the user Requirement
  • Windows Server 2003
  • Microsoft Office SharePoint Server
  • Microsoft SQL Server 2005 - used internally by MOSS
  • SharePoint designer

Key Features/Elements of MOSS

  • Enterprise Search
  • Business Intelligence by providing integration with Excel Services, SSRS, PPS etc
  • Enterprise Content Management (ECM)
  • Integration with MS office
  • Security at Site Collection level to list item level
  • Site templates available to create sites and Portals easily
  • Out of the box web parts available having custom functionality by simple configuration
  • Out of the box workflows like approval workflow for implementing custom functionality
  • Integration with Reporting tools like SSRS, BSM, PPS etc
  • Every features is scoped at a Farm, Web application, Site Collection and Web Level
  • Document Management, Policy Management and Auditing
  • Personalization and deployment
  • OOB event handlers at site, web and Item level for custom functionality
  • Site Manager, which replaces the Portal Site Map administration page, is a Web-based drag-and-drop tool for managing a SharePoint site’s navigation, security access, and general look and feel.
  • Office SharePoint Server 2007 includes an LDAP pluggable provider for authenticating users of Office SharePoint Server 2007. This is in addition to the Active Directory provider included with Windows SharePoint Services.
  • Audience Targeting
  • Document collaboration
  • Wikis and Blogs
  • Really Simple Syndication (RSS) support
  • E-mail integration

Thursday, April 16, 2009

MOSS (SharePoint) online Free Test - Part two

Take a sample exam in MOSS for free in just few minutes. If you have not taken the first part of test. Please click here

1. User profiles in sharepoint is created using
Active Directory through master connection
SQL Server through Business data Catalog
Both
None of the above


2. How many master pages can we have for a MOSS site?
1
2
256
any number

3. A workflow in Sharepoint is always attached to exactly one List or Library?
True
False


4. ItemUpdating is a valid synchronous list item event in Sharepoint list
True
False


5. Which is/are the elements of Excel Services in MOSS?
Excel Web Access
Excel Web Services
Excel Calculation Services
None of the above

6. which of the following interface is not supported for connectable web parts in sharePoint?
IRowProvider
ICellProvider
IValueProvider
IListProvider

7. Using Sharepoint designer 2007, we can create custom workflow with out any code
True
False


8. SPExport class in sharepoint is/are used to Export the following and can be imported to another server
Pages
web sites
Sitecollection
Cannot be Exported


9. Reusable content is Sharepoint is/are
Items in this list contain HTML or text content which can be inserted into web pages
If an item has automatic update selected, the content will be inserted into web pages as a read-only reference, and the content will update if the item is changed.
The reusable content is inserted into the sharepoint site pages by publishing HTML content control
All the above


10. Search in Windows SharePoint Services supports the following search syntax for building search queries
Keyword Query syntax
SQL syntax
URL syntax as query string
1, 2 and 3
1 and 3





Part one Test








ANSWERS
1. C (both)
2. d (Any number)
3. a (True)
4. a (True)
5. a, b, c (Excel Web Access, Excel Web Services Excel, Calculation Services)
6. c (IValueProvider)
7. a (True)
8. a,b,c (Pages, Web sites, site collection)
9. d (All the above)
10. 1,2, 3(All the above)

Wednesday, April 15, 2009

Reusable Content in SharePoint

Items in this list contain HTML or text content which can be inserted into web pages.
  • If an item has automatic update selected, the content will be inserted into web pages as a read-only reference, and the content will update if the item is changed.

  • If the item does not have automatic update selected, the content will be inserted as a copy in the web page, and the content will not update if the item is changed.

The Reusable Content is created using Reusable content list available in the List all site contents under site Actions Menu. This Reusable content list has all the reusable contents for the site collection.

The first thing to understand is that Reusable Content is unique to the Publishing feature in MOSS. It can only be leveraged in Publishing sites and pages because it is available in only in the Page Content Field, one of the out-of-the-box columns available in Article Page and Welcome Page page layout content types.



[080307_1402_Understandi3.jpg]


The reusable content is inserted into the sharepoint site pages by Rich text editor or publishing HTML content control for a Page Content Field which has icon to insert the Reusable content.



The step by step configuration for reusable content in MOSS is available here

Friday, April 10, 2009

Creating Custom Web part in MOSS and add custom properties to the Tool part

You can create a Custom web part for implementing the custom functionalites in SharePoint by deriving the class from Microsoft.SharePoint.WebPartPages.webPart Class.

using Microsoft.SharePoint;
using Microsoft.SharePoint.WebPartPages;

public class CustomWebPart : WebPart
{
protected override void CreateChildControls()
{
// to do : Create the child controls of the web part and add to the controls collection
Button btncntrol = new Button();
this.Controls.Add(btncntrol);
}
public override void RenderControl(HtmlTextWriter writer)
{
// render control here
}
}

CreateChildControls and RenderControl methods are used to add controls to the web part also apply styles to the web part.

To add custom properties to the Tool Part in Modified Shared Web Part

[Browsable(true), Category("Behavior"), DefaultValue(false),
WebPartStorage(Storage.Shared),
FriendlyName("Enable values "),
Description("To modify values")]
public bool ShowCustomProperty
{
get
{
return showCustomproperty;
}
set
{
showCustomproperty = value;
}
}

To have more customization in the tool part like “on click of image a dialog should open”. Override GetToolPart method in web part class.

When the end-user chooses to modify a Web Part, the framework will call the GetToolParts method of the Web Part class. By overriding this method, I can control the order and appearance of the Tool Parts.

public override Microsoft.SharePoint.WebPartPages.ToolPart[] GetToolParts()
{
// returns array of tool part. Custom propery is also added here...
}

To learn more about creation of web part and connectable web parts in MOSS Click Here

Export and Import APIs in MOSS for migrating content

To Export Pages / Images/ Webs/Pages from one site or web site or sub site to another SharePoint site using content Migration APIs. This took physical copy of each object (pages, web sites, sub sites, site collection) and it can be moved to any other server.

The Content Migration APIs in Windows SharePoint Services 3.0 provide a flexible set of tools for migrating content between Windows SharePoint Services Web sites. Windows SharePoint Services uses the concept of the content migration package, which can include either single or multiple XML files, and then provides a flexible set of APIs to enable exporting and importing the migration packages. The content import/export feature of the deployment object model allows you to export not only Web site content but also existing dependencies, like security features, user roles, versioning data, workflows, and other metadata.

SPExportSettings settings = new SPExportSettings();
settings.SiteUrl = "http://localhost:2000";
// This is used to specify whether to export all or only incremental changes
settings.ExportMethod = SPExportMethodType.ExportAll;
// Location where the physical files on export are getting stored.
settings.FileLocation = @"c:\export";
settings.FileCompression = false;
settings.CommandLineVerbose = true;

// Settings is assigned to the SPExport object
SPExport export = new SPExport(settings);
// This method exports the content and store as physical files
export.Run();

Similarly, import should also be done in the similar fashion with SPImport class.
These APIs are used to migrate the content(Pages / Images/ Webs/Pages ) with in the same sharepoint server as well as other servers.

SiteUrl - this property defines which site collection the export should use. All objects being exported always have to be in the same site collection. The Content Deployment and Migration API cannot access items in different site collections in a single operation.

ExportMethod - this property allows to define whether to perform an incremental export (value = ExportChanges) or everything (value = ExportAll). Be aware that ExportChanges would require to provide an Export Change Token in a separate property.

FileLocation - this property defines where to store the exported content. The value should point to be an empty directory. If the directory does not exist it will be created during export. If file compression is being used, then only the compressed files will be stored on this location. The uncompressed files will be stored in the directory identified by the value of the system wide TMP environment variable. So you need to ensure that the directory the TMP environment variable points to also needs to have sufficient space available.

FileCompression - this property defines whether the content should be compressed into a CAB file. If you need to archive the exported content or need to transfer it to a different machine you should choose to compress. If you only export the content to import it afterwards using code on the same machine and don't need to archive (e.g. a copy or move operation) then you should decide to disable the compression as this is significantly quicker.

CommandVerbose - this parameter allows to control if the API should provide some verbose output. If you have ever seen the generated output when running STSADM -o export: this is exactly the flag the generates this output. If the value is false no output is generated.

ExcludeDependencies - This property controls whether to export dependent objects like referenced images, master pages or page layouts. If it is unclear if the dependent objects are already in the destination database you should export the dependent objects as well to prevent problems.

IncludeDescendants - This property controls whether to export child objects of the selected objects (like sub webs, lists, list items) or only the selected object. Possible values are None (only the object is exported), Content (List and libraries of a web will be exported but not sub webs) and All (all child content is exported)

Thursday, April 9, 2009

Configuring incoming/outgoing email for SharePoint/MOSS 2007

SharePoint 2007 allows for emails to be accepted into discussions, document libraries and lists. To enable this functionality, a few steps will need to be followed. One thing to note: integrating SharePoint with Exchange is NOT needed for this functionality, but if you do choose Exchange, you will get some added benefits.

-SMTP Service
You will need to install the SMTP Server Service on the SharePoint server. This is done via add/remove programs, and within the IIS component listing.

-Enable Incoming Email
Now, enable Incoming Email from the Central Administration website. It is found by following: Central Administration > Operations > Incoming Email Settings

-SMTP Connector
You will finally need to configure an SMTP connector within your email server so it knows where to send emails you designate for SharePoint.

Pre Requisites
· SMTP service to be installed

Enabling incoming/outgoing email for SharePoint/MOSS 2007 is done thru SharePoint Central Administration under Operations Section.

How-to configure incoming or outgoing e-mail in sharepoint video is available here

Pre-requisites are available here

Introduction to Excel Services in SharePoint and Components

Components of Excel Services in MOSS
Excel Services is a Microsoft Office SharePoint technology that makes it simple to use, share, secure, and manage Microsoft Office Excel 2007 workbooks as interactive reports in a consistent way throughout the enterprise.

We can also create custom connectable web parts to Excel OOB web parts for having custom functionality.

1. Excel Web Access
This allows the to display excel sheets on the web page. The Excel can be shown in sharePoint page as a web part.

2. Excel Web Services
Use SharePoint Excel API to manipulate excel sheet data. But these APIs are not used create an excel sheet dynamically.

3. Excel Calculation Services
Allows you to load excel sheets on the web page (as HTML) and render calculated data fro the User defined functions.

Limitations of Excel Services
  • Will not load excel files with VBA Low fidelity.
  • Charts in excel will have low fidelity.
  • Users cannot add or rearrange fields in pivot reports using web access.
  • No authoring support

To learn more about configuring excel services in Sharepoint Click here

Wednesday, April 8, 2009

Customize sharepoint CoreResultsWebPart to apply Audience filtering

The below code is to customize the CoreResultsWebPart (Sharepoint OOB web part) to filter based on audience using Reflection. To do so, we need to derive the web part from CoreResultsWebPart class and override the SetPropertiesOnHiddenObject method.

CoreResultsWebPart class internally uses the hiddenobject class to set all the inputs to generate the Search result result. On overriding the method, we can change the input query.

To learn more about sharepoint search queries and Mananaged property Click here

For Example. to filter based on a key word "Sharepoint", MOSS generates a SQL query like this
SELECT WorkId,Path,Title,Write,Author,HitHighlightedSummary, HitHighlightedProperties,CollapsingStatus FROM Scope() WHERE FREETEXT(defaultproperties, 'SharePoint') ORDER BY Rank Desc

To apply audience, query will become
SELECT WorkId,Path,Title,Write,Author,HitHighlightedSummary, HitHighlightedProperties,CollapsingStatusFROM Scope()WHERE FREETEXT(defaultproperties, 'SharePoint') AND CONTAINS(Audience,'TestAud' ) ORDER BY Rank Desc

Audience property added in the where clause of the query is a managed property which is created using Crawled property. Once added the Audience filter in SQL query, the Search result output is automatically generated based on Audience and key word.

Sample code for audience filtering in MOSS Search Result

using System;
using System.Data;
using System.Configuration;
using System.Linq;
using System.Web;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using Microsoft.Office.Server.Search.Query;
using Microsoft.Office.Server.Search.WebControls;
using Microsoft.SharePoint.Administration;
using Microsoft.Office.Server;
using Microsoft.SharePoint;
using Microsoft.SharePoint.Search;
using System.Reflection;

namespace customCoreResultsWebPart
{
public class customCoreResultsWebPart : Microsoft.Office.Server.Search.WebControls.CoreResultsWebPart
{
protected override void SetPropertiesOnHiddenObject()
{
base.SetPropertiesOnHiddenObject();
try
{
Type coreResultsWebPartType = this.GetType();

// get the private field containing the searchResultsHiddenObject srho
FieldInfo searchResultsHiddenObjectField = coreResultsWebPartType.BaseType.GetField("srho", BindingFlags.NonPublic BindingFlags.Instance);

// make sure the field exists
if (searchResultsHiddenObjectField != null)
{
// get the actual internal srho object attached to CoreResultsWebPart
object searchResultsHiddenObject = searchResultsHiddenObjectField.GetValue(this);

// get the type of the srho
Type searchResultsHiddenObjecType = searchResultsHiddenObject.GetType();

// get the keyword query property
PropertyInfo keywordQueryProperty = searchResultsHiddenObjecType.GetProperty("KeywordQuery", BindingFlags.Instance BindingFlags.Public);

// read what the user searched for
string keywordQuery = (string)keywordQueryProperty.GetValue(searchResultsHiddenObject, null);

// use this method to get the keywords as a query string to append to the search
// this doesn't seem to be working yet

MethodInfo keywordQueryMethod = searchResultsHiddenObjecType.GetMethod("GetKeywordsAsQuery", BindingFlags.Instance BindingFlags.NonPublic);
string keywordsAsQuery = (string)keywordQueryMethod.Invoke(searchResultsHiddenObject, null);

// set the keywordProperty to null so we can change it to a fullTextQuery
keywordQueryProperty.SetValue(searchResultsHiddenObject, null, null);

// create a new query and set it
string fullTextQueryString = null;

// get the fullTextQuery field i.e. ADVANCED SEARCH
PropertyInfo fullTextQueryProperty = searchResultsHiddenObjecType.GetProperty("FullTextQuery", BindingFlags.Instance BindingFlags.Public);

// This scenario is called when User used AADVANCED SEARCH
if (fullTextQueryProperty.GetValue(searchResultsHiddenObject, null) != null)
{
// This is in the form of SQL Query
fullTextQueryString = fullTextQueryProperty.GetValue(searchResultsHiddenObject, null).ToString();
}
// For normal Search Scenario, The keyword query is translated into SQL Query
else if (!string.IsNullOrEmpty(keywordQuery))
{
// This scenario, the value is just the Keyword... so modify to a SQL Query
fullTextQueryString = "SELECT WorkId,Path,Title,Write,Author,HitHighlightedSummary, HitHighlightedProperties,CollapsingStatus FROM Scope()WHERE FREETEXT(defaultproperties, '" + keywordQuery + "')";
}
// Not a Valid Search and hence Return
else
{
return;
}
// APPLY AUDIENCE FILTERING
fullTextQueryString = fullTextQueryString + " AND CONTAINS (AUDIENCE,'TestAud')";

// SET the SQL Query to the full Text Query - SET THE HIDDEN OBJECT TO NEW VALUE WITH AUDIENCE FILTER
fullTextQueryProperty.SetValue(searchResultsHiddenObject, fullTextQueryString, null);

// this field needs to be set to true to use a full text query
FieldInfo fullTextQuerySetField = searchResultsHiddenObjecType.GetField("_IsFullTextQuerySetFromForm", BindingFlags.NonPublic BindingFlags.Instance);
fullTextQuerySetField.SetValue(searchResultsHiddenObject, true);

// tell the srho that it is not a keyword query any more
FieldInfo isKeywordQueryField = searchResultsHiddenObjecType.GetField("m_bIsKeywordQuery", BindingFlags.NonPublic BindingFlags.Instance);
isKeywordQueryField.SetValue(searchResultsHiddenObject, false);
}
}
catch (Exception exp)
{
// To do: Exception Handling
}
}
}
}

Tuesday, April 7, 2009

Maximum number of web sites and Sub sites in MOSS (SharePoint) site collection

The total number of web sites and sub sites together in one site collection should be 2, 50,000. Web sites which are actually the first sub sites under a site collection, and sub sites are the sites under the web sites.
So if you've got fewer web sites, you can have more sub sites. But for better performance use not more than 2000 sub sites per web site.

MOSS 2007 Performance guidelines for number of sites
Click here

Guidelines for acceptable performance for number of sites
Click here

Monday, April 6, 2009

MOSS (SharePoint) Frequently asked questions - MOSS online Free Test - Part one

Take a sample basic exam in MOSS 2007 for free in just few minutes

1. Can we have multiple sub sites and web sites under a site collection?
Yes
No

2. Which of the following are true in MOSS?
The Sites under site collection are called Web sites
The Sites under web sites in MOSS are called sub sites
Both are true
Both are false

3. Can we customize the webpart to support personalization?
Yes
No


4. Shared Service provider(SSP) in MOSS is provided by
Windows SharePoint Services (WSS)
SharePoint server 2007
.net 3.5

5. MOSS supports events at
Site Level
List Level
List Item Level
MOSS doesn't support events

6. In MOSS, Security can be applied at
Site Level
Sub Site or Web site Level
List /document library Level
List Item Level
All the above

7. which of the following is not a valid site group with Windows SharePoint Services(WSS)?
Administrator
Web Designer
Contributor
Manager
Reader/Visitor


8. which of the following is/are true?
Content Type is a collection of logically related data element types or site columns
Site Column defines a data element for a site collection
Multiple content types can be added to sharepoint lists
Sharepoint doesn't have Out-Of-box workflows


9. which not a Out of the Box Workflow in MOSS?
Approval Workflow
Collect Signature Workflow
Service Workflow
Three State Workflow



10. MOSS (Sharepoint) offers
A framework that allows to build business sites rapidly
Lots of features, Workflows and site templates already built-in
Excellent integration with Word, Excel, PowerPoint etc
All the above



Go to Online Test - Part two


To learn more about frequently asked interview questions in MOSS, click here






ANSWERS
1. a
2. c
3. a
4. b
5. a,b,c
6. e (All the Above)
7. d (Manager)
8. a,b,c
9. c
10. d (All the above)

Friday, April 3, 2009

A splash page in MOSS

A splash page can be a useful method of providing users with information on the first visit to a web site. When the main page of the SharePoint site is navigated to by a user for the first time a different page is presented. This could provide a welcome note or current information – anything that should be seen once by a user, and then not again.

the creation and configuring splash page is available here

Thursday, March 19, 2009

Showing the page fields/Controls only in edit mode of the SharePoint page

To show the fields only in the Edit mode of the page, add the controls in the following node by editing the page layout of the page.

PublishingWebControls:EditModePanel control is used to show the controls only in the edit mode of the page.

The way we do this is by putting two edit mode panels on the page layout, one configured to render in edit mode, and another configured to render in view mode:

To show in view mode
<
PublishingWebControls:EditModePanel runat=server id="EditModePanelA" PageDisplayMode="Display">
<
SharePointWebControls:FieldValue runat="server" id="ImageFieldValue" FieldName="PublishingPageImage"/>
PublishingWebControls:EditModePanel>

To show in Edit mode only
<
PublishingWebControls:EditModePanel runat=server id="EditModePanelB">
<
SharePointWebControls:FieldValue id="ContactEMailId" FieldName="ContactEMail" runat="server" />
PublishingWebControls:EditModePanel>


The first one will render its contents when people are viewing the page, while the second one will render when people are editing the page

Creating MenuItem in the site Actions menu and adding Security

The application pages and supporting menu items in the Site Actions menu shown so far have been created in a manner so that they are accessible to all users of a site. However, that isn't always desirable. Application pages are often designed to provide information and functionality that should only be accessible to site administrators. The same shows to create a menu item in the Site Actions menu.

This can be installed to sharePoint as a feature as mentioned in the XML below. You can add an attribute named RequireSiteAdministrator and assign it a value of true so that the menu item only displays to those users who are also site administrators.


< CustomAction Id="SiteActionsToolbar" GroupId="SiteActions" Location="Microsoft.SharePoint.StandardMenu" Sequence="1003" Title="Application Page 3" Description="Check out some typical site properties" RequireSiteAdministrator="True" ImageUrl="/_layouts/images/DECISION.GIF">
< UrlAction url="~site/_layouts/CustomApplicationPages/ApplicationPage3.aspx">
< /CustomAction>


After Installing the feature, the SharePoint site looks like








Activating Auditing Programmatically for a Document Library in SharePoint

In the SharePoint (MOSS) object model, SPList objects and SPListItem objects expose an Audit property that makes it possible to configure auditing. The following example shows how to enable auditing in a single document library.

// Open site and Web objects
SPSite siteCollection = new SPSite(http://localhost);
SPWeb site = site.OpenWeb("testweb");

// Open the document library to enable auditing
SPList docLib = site.Lists("documents");

// Turn on auditing flags.
docLib.Audit.AuditFlags = SPAuditMaskType.View
SPAuditMaskType.ChildDelete;
docLib.Audit.Update();


To enable auditing at site collection level
// Open site object
SPSite siteCollection = new SPSite(http://localhost/);
// Enable auditing for the site
siteCollection.Audit.AuditFlags = SPAuditMaskType.All;
siteCollection.Audit.Update();

Wednesday, March 18, 2009

Configuring User Profiles in Sharepoint from Active directory

User profile is configured through SharePoint Shared Service provider (SSP).

The below steps describes the configuration of user profiles from Active directory

1. Create a SSP using Central Administration of sharepoint, if not available already.

2. Access SSP for sharepoint server from Central Administration















3. Access user profiles and properties from the Next screen













4. Click ‘View Import Connections’ from below screen














5. Choose ‘Create Connection’ to create a master connection to Active Directory











6. Enter type as Active Directoty and Enter Domain name and click ‘Auto Fill Root Search Base button’ from next screen

7. Make sure that the ‘Authentication Information’ has ‘Default Account’ selected

8. If the application requires incrmental import, then make sure that the ‘Enable server Side Incremental’ is checked to support incremental imports.

9. Then create the connection.

10. Once the connection is created from active directory, start full import using the below screen

Tuesday, March 17, 2009

Reading User Profiles from SharePoint(MOSS) programatically

User profile for SharePoint can be imported from Active directory(using master connection from current domain) and SQL server using Business data catalog(BDC) using an application definition file. Audiences can be created from the user profile information based on some rules.

To read the user profile information, we need the following namespaces.
using Microsoft.Office.Server.UserProfiles;
using Microsoft.Office.Server;
using Microsoft.SharePoint;

// GET THE current web
SPWeb web = SPContext.Current.Web;
// Get the logged in user
SPUser user = web.CurrentUser;

// Get the user context
ServerContext ctx = ServerContext.GetContext(HttpContext.Current);
// Get the user profile associated with the context
UserProfileManager userprofilemgr = new UserProfileManager(ctx);

// Get the user profile based on logged in User
UserProfile userprofile = userprofilemgr.GetUserProfile(user.LoginName);
// Reading User profile Information such as name, designation etc
string name = userprofile["First Name"];

userprofilemgr.GetUserProfile method in above code fails if the user does not have access to manage Audience. The permission to access the User profile is given by the following steps.
1. Open the SharePoint 3.0 Central Administration
2. Click on the Shared Services Provider (Farm SSP in this build) i.e. SSP linked to the current site.
3. Click on ‘Personalization services permissions’ under ‘User Profiles and My Sites’
4. Select the user ‘NT AUTHORITY\Authenticated Users’ and click on ‘Modify Permissions of Selected Users’
5. Select ‘Manage audiences’ and click on ‘Save’
6. ‘Manage Audiences’ right will be added to ‘NT AUTHORITY\Authenticated Users’

Running SharePoint custom code with elevated/ administrative privileges

Whenever writing a custom code(workflow / web parts / event handlers) for MOSS site, we sometimes require administrative previleges to run the custom code.


using Microsoft.SharePoint;

SPSecurity.RunWithElevatedPrivileges(delegate()
{
// Code to Run with admin privileges
});

This will take care of running the code with Administrative privileges. (Administrative account) even the user does not have access to the site.

To access the document in a SharePoint (MOSS) library programmatically

To access the document in a library, we need to do the following steps
1. First we need to create SPSite object for the site collection (E.g http://localhost)
2. Then we need to create SPWeb object inside the site collection (E.g http://localhost/testweb)
3. Get get the file by passing the relative url of the web (E.g /documents/samplefile.doc)
4. After getting the SPFile object, one can access the properties of the file as well as version.

Sample Code
using Microsoft.SharePoint;

SPSite site = new SPSite(http://localhost);
SPWeb spweb = site.OpenWeb("testweb");
SPFile file = spweb.GetFile("/documents/samplefile.doc");

Console.WriteLine(file.Url + ", " + file.Length);
SPFileVersionCollection versions = file.Versions;
Console.WriteLine(versions.Count);

for (int i = 1; i < versions.Count; i++)
{
SPFileVersion ver = versions[i];
Console.WriteLine(ver.VersionLabel + ", " + ver.Size);
}

Monday, March 16, 2009

Caching the first load times in SharePoint (Improving the performance of MOSS site at first load)

Generally the first time page load takes a huge time after doing IISReset. But by doing the below settings, the performance on first load will be faster.
To improve the performance of the SharePoint pages after we do an IISReset.
· Object cache size: 350 (http://servername/_Layouts/objectcachesettings.aspx)
· Site Collection Output Cache: enabled w/ modified Intranet profile:










Click on the image for better resoultion

Showing the page fields/Controls only in edit mode of the page

To show the fields only in the Edit mode of the page, add the controls in the following node by editing the page layout using SharePoint designer
layoutPublishingWebControls:EditModePanel

Integrating InfoPath with Sharepoint List

Microsoft InfoPath supports multiple views of the same form.Based on business requirements and user roles, different views of the form can be shown to different users. The below steps is to integrate Infopath forms with Sharepoint Server

  • Create the Sharepoint List
  • Create the CAML fragment to serve as the base schema to submit to the webservice
  • Create the form template and add the data connections
  • Identify the GUID used as the ID for the List
  • Add controls to the form template to display the current items in the list
  • Add fields and controls for entering new items to submit to the list
  • Add a connection to the sharepoint Lists webservice and define the parameters for calling UpdateListItems web method
  • Add the event handler code required to submit additions, updates and deletions from the list
  • Test the form and publish to Sharepoint Server To a Form Library or As a site content type

Building Windows SharePoint Services Search Queries

Search in Windows SharePoint Services supports three types of search syntax for building search queries:

· Keyword Query syntax (search terms are passed directly to the Search service)
· SQL syntax (extension of SQL syntax for querying databases)
· URL syntax (search parameters are encoded in URL, and posted directly to the search page)

Keyword Query syntax

You can pass two types of terms in a Windows SharePoint Services Search keyword query:
· Keywords (the actual query words for the search request)
· Property filters (the property constraints for the search request)
e.g Keyword site:http://marketing http://customersupport/

Site and URL are the Managed Properties used in Search.

The filtering Search results based on the web sites and sub sites can be done thru OOB search itself by giving the filter site keyword (Note: site is a Managed property). SharePoint allows searching content based on one or more managed property. If the search keyword is “Test”, we need to append the web site URL along with the search keyword in the OOB Search Web part to get the results Test site: http://servername/US. OOB web part provides this functionality and the site filter is appended along with the Search keyword.

Otherwise, the url is given like this http://servername/SearchCenter/Pages/results.aspx?k=Test.

In the above URL, key word and site are used to filter the results.
Where http://servername/SearchCenter/Pages/results.aspx is the Search results page

Mapping Crawled Properties to Managed Properties
To make a crawled property available for the Search experience—to make it available for Search queries and display it in Advanced Search and search results—you must map it to a managed property. You can map multiple crawled properties to a single managed property or map a single crawled property to multiple managed properties. If a managed property has multiple crawled properties mapped to it, and a document contains values for more than one of the crawled properties, the order in which the properties are mapped and their priority determine the managed property’s value.

Multiple Property Filters in Enterprise Search
Enterprise Search in Microsoft Office SharePoint Server 2007 keyword syntax supports the use of multiple property filters within the same query. You can use either multiple instances of the same property filter or different property filters.
Using the Same Property Filter
In this scenario, the keyword query is based on a union of the property filters. This is equivalent to the OR operator used in SQL search syntax.
For example, if you specify the following property filters for a keyword query, both the http://marketing/and http://customersupport/ sites are included in the search:
site:http://marketing/ site:http://customersupport/

Using Different Property Filters
In this scenario, the keyword query is based on an intersection of the property filters. This is equivalent to the AND operator used in SQL search syntax.

For example, if you specify the following property filters for a keyword query, all content authored by John Smith from the http://marketing site is included in the search:
site:http://marketing/ author:"John Smith"

SQL Syntax Examples
Search in Windows SharePoint Services provides support for constructing complex search queries through the SQL syntax. Some examples of what is available when using SQL syntax for search queries include the following:
· Comparison operators, such as ">", "<", or · Multiple logical operators, such as AND, OR, and NOT.

1. Finds relevant results containing the keyword SharePoint.
SELECT WorkId,Path,Title,Write,Author,HitHighlightedSummary, HitHighlightedProperties,CollapsingStatusFROM Scope()WHERE FREETEXT(defaultproperties, 'SharePoint') ORDER BY Rank Desc

2. Finds relevant results containing at least one of the keywords SharePoint and Search. SELECT WorkId,Path,Title,Write,Author,...FROM Scope()WHERE FREETEXT(defaultproperties, 'SharePoint Search') ORDER BY Rank Desc

3. Finds relevant results containing both the keywords SharePoint and Search.
SELECT WorkId,Path,Title,Write,Author,...FROM Scope()WHERE FREETEXT(defaultproperties, '+SharePoint +Search') ORDER BY Rank Desc

4. Finds relevant results containing the exact phrase SharePoint Search.
SELECT WorkId,Path,Title,Write,Author,...FROM Scope()WHERE FREETEXT(defaultproperties, ' "SharePoint Search" ') ORDER BY Rank Desc

5. Finds relevant results containing both the keywords SharePoint and Search but not the keyword WSS.
SELECT WorkId,Path,Title,Write,Author,...FROM Scope()WHERE FREETEXT(defaultproperties, '+SharePoint +Search -WSS') ORDER BY Rank Desc

6. Finds relevant SharePoint results authored by persons named John.
SELECT WorkId,Path,Title,Write,Author,...FROM Scope()WHERE FREETEXT(defaultproperties, 'SharePoint') AND CONTAINS(Author,' "John" ')ORDER BY Rank Desc

7. Finds relevant SharePoint results modified within the last 30 days. SELECT WorkId,Path,Title,Write,Author,...FROM Scope()WHERE FREETEXT(defaultproperties, 'SharePoint') AND Write<=DATEADD(DAY,30,GETGMTDATE())ORDER BY Rank Desc.

Configuring sharePoint Search step by step is available here

Customizing core results web part is avaialble here