Tag Archive for Sharepoint 2010

Creating Custom Properties in Webpart SharePoint.

A web part by default has some properties like Title, Height, and Width etc. The values for these properties can be either set through code or by using Edit Web Part option. The properties are normally displayed in a Property Pane on the right hand side, when Edit Web Part is clicked. Also these properties are grouped into sections like Appearance, Layout and Advanced.

In MSDN Article describing good for regarding custom properties in SharePoint Web part.

There are some properties below for use in webparts.


Property Type: String
Displayed in property pane as : TextBox

    private string _stringurl = "";
[Category("Custom Properties")]
[DefaultValue("")]
[Description("Enter the String Url :")]
[WebBrowsable(true)]
[Personalizable(true)]
public string Stringurl
{
get
{
return _stringurl;
}
set
{
_stringurl = value;
}
}

Property Type: Integer
Displayed in property pane as : TextBox

        private int _displayitem = 10;
[Category("Custom Properties")]
[DefaultValue(10)]
[FriendlyNameAttribute("Please Select this.")]
[Description("Please Select this.")]
[WebBrowsable(true)]
[Personalizable(true)]
public int Displayitem
{
get
{
return _displayitem;
}
set
{
_displayitem = value;
}
}

Property Type: bool
Displayed in property pane as : Check box

        private bool _checkbox = false;
[Category("Custom Properties")]
[DefaultValue(10)]
[FriendlyNameAttribute("Custom Boolean")]
[Description("Boolean")]
[WebBrowsable(true)]
[Personalizable(true)]
public bool Checkbox
{
get
{
return _checkbox;
}
set
{
_checkbox = value;
}
}

Property Type: enum
Displayed in property pane as : Dropdown list

       public enum ControlModes
{
[Description("Filter mode")]
FilterMode,
[Description("Last 10 item mode")]
LastItemmode

}
[Category("Custom Properties")]
[DefaultValue(ControlModes.FilterMode)]
[Description("Select Display Type:")]
[WebBrowsable(true)]
[Personalizable(true)]
public ControlModes ControlMode
{
get;
set;
}

so finally i am put whole code of my webpart.

    [ToolboxItemAttribute(false)]
public class WebPart1 : System.Web.UI.WebControls.WebParts.WebPart
{

private string _stringurl = "";
[Category("Custom Properties")]
[DefaultValue("")]
[Description("Enter the String Url :")]
[WebBrowsable(true)]
[Personalizable(true)]
public string Stringurl
{
get
{
return _stringurl;
}
set
{
_stringurl = value;
}
}

public enum ControlModes
{
[Description("Filter mode")]
FilterMode,
[Description("Last 10 item mode")]
LastItemmode

}
[Category("Custom Properties")]
[DefaultValue(ControlModes.FilterMode)]
[Description("Select Display Type:")]
[WebBrowsable(true)]
[Personalizable(true)]
public ControlModes ControlMode
{
get;
set;
}

private int _displayitem = 10;
[Category("Custom Properties")]
[DefaultValue(10)]
[FriendlyNameAttribute("Please Select this.")]
[Description("Please Select this.")]
[WebBrowsable(true)]
[Personalizable(true)]
public int Displayitem
{
get
{
return _displayitem;
}
set
{
_displayitem = value;
}
}

private bool _checkbox = false;
[Category("Custom Properties")]
[DefaultValue(10)]
[FriendlyNameAttribute("Custom Boolean")]
[Description("Boolean")]
[WebBrowsable(true)]
[Personalizable(true)]
public bool Checkbox
{
get
{
return _checkbox;
}
set
{
_checkbox = value;
}
}

LiteralControl ltcntrl;
StringBuilder sb;
protected override void CreateChildControls()
{
base.CreateChildControls();
ltcntrl = new LiteralControl();

sb = new StringBuilder();
sb.Append("String Property Value :" + this.Stringurl + "
");
sb.Append("Int Property Value :" + Convert.ToString(this.Displayitem) + "
");
sb.Append("Dropdownlist Property Value :" + Convert.ToString(this.ControlMode) + "
");
sb.Append("Boolean Property Value :" + Convert.ToString(this.Checkbox) + "
");
ltcntrl.Text = sb.ToString();
this.Controls.Add(ltcntrl);

}
protected override void Render(HtmlTextWriter writer)
{
base.Render(writer);
ltcntrl.RenderControl(writer);
}

public override void RenderControl(HtmlTextWriter writer)
{
RenderChildren(writer);
}
}

now deployed your solution and make sure Activated Feature in Site Collection which your webparts exist on that feature.

afterward add your web part from web part gallery to your page and click on toolbar of verb-collection on that webpart than
goto Edit Webpart Property.

You will  able to see your custom webpart properties category which describe on your properties and  set values.

than set your property value as you like than do applied.now See the outputs

Url Properties of SPSite and SPWeb

 

There are some properties for SPSite and SPWeb class using which we can get the URL values for the sites and webs. The two most used of these properties are – ‘ServerRelativeUrl‘ and ‘Url

As a developer we use the values of the properties for writing some logic for satifying the business needs. Whenever I used to write a OM code to use these properties, the first question which flashes in my mind – “What values are returned by these properties?“. I immediately create a cosole application, and check the values returned by these properties and contiue with the actual work. I have seen many other developers doing this. So, for a quick reference I prepared the below table which has the url values returned by these properties.

Some poeple may find this easy, but some (like me ;)) get confused when the sites have managed paths. These properties return the managed path if the site has one. Here goes the list

SCENARIO 1: A Site Collection (SPSite) without any managed path.

URL : ‘http://rams’
Property Value
SPSite.ServerRelativeUrl /
SPSite.Url http://rams
SPWeb.ServerRelativeUrl /
SPWeb.Url http://rams
Url – http://rams/about (‘about’ is a sub site)
SPSite.ServerRelativeUrl /
SPSite.Url http://rams
SPWeb.ServerRelativeUrl /about
SPWeb.Url http://rams/about

This looks pretty simple. We get confused when sites are created using managed paths. Below are the samples values for site created with managed paths

SCENARIO 2: A Site Collection with a managed path (of type Explict inclusion). For the below URL ‘/my’ is the managed path

URL : ‘http://rams/my’
Property Value
SPSite.ServerRelativeUrl /my
SPSite.Url http://rams/my
SPWeb.ServerRelativeUrl /my
SPWeb.Url http://rams/my
Url – http://rams/my/about (‘about’ is a sub site)
SPSite.ServerRelativeUrl /my
SPSite.Url http://rams/my
SPWeb.ServerRelativeUrl /my/about
SPWeb.Url http://rams/my/about

 

SCENARIO 3: A Site Collection with a managed path (of type Wilcard inclusion). For the below URL ‘/sites’ is the managed path, and a site collection is created at ‘/blog’

URL : ‘http://rams/sites/blog’
Property Value
SPSite.ServerRelativeUrl /sites/blog
SPSite.Url http://rams/sites/blog
SPWeb.ServerRelativeUrl /sites/blog
SPWeb.Url http://rams/sites/blog
Url – http://rams/sites/blog/about (‘about’ is a sub site)
SPSite.ServerRelativeUrl /sites/blog
SPSite.Url http://rams/sites/blog
SPWeb.ServerRelativeUrl /sites/blog/about
SPWeb.Url http://rams/sites/blog/about

Create a List Definition in SharePoint 2010 using Visual Studio 2010

In this demonstration, I am going to create a list definition using Visual Studio 2010. For the demonstration purpose, I am going to create a list definition for storing expenses, once deployed, the list definition can be used to create lists to store expenses. The list definition will define a list template that inherit from custom list and add columns expensedate and amount.

Open Visual Studio, Go to File -> New project, In the Template selection dialog, choose List Definition as the template type.

Give a proper name to your List Definition project. Make sure the .Net framework selected is 3.5 as SharePoint 2010 is built on .Net framework 3.5.clip_image002

Click OK button, once you entered all the details.

In the next dialog you need to choose the SharePoint portal you need to use for debug. Also you need to specify whether it is a farm solution or sand boxed solution. Enter your SharePoint portal address and Click Next

clip_image003

Click Next once you are done

Now Visual Studio will bring you the List definition settings dialog. Here you can define the title for your list definition and choose a base list to inherit from. I choose my base list as “Custom List”. In addition to this you can decide whether to include a list instance when deploying this feature. Since I want to check my list definition, I selected “Add a list instance to this list definition” option. Click finish button, once you are done

clip_image004

Click Finish button once you are done with this step.

Visual Studio will add a default feature to your project and add a list definition. In the solution explorer the project will look similar to the following. I published an article for developing a SharePoint 2010 feature using Visual Studio, to read that article click here.

clip_image005

Let me explain the files exists under the List Definition

Elements.xml – this file defines the list template and fields such as name, display name, type etc. The properties specified in this file will be displayed in the Create Page, when you create a list template from this file.

Let us examine the Elements.Xml file. See the snapshot of the elements.xml file

clip_image006

The complete reference for Elements file for List template can be found in the below URL

http://msdn.microsoft.com/en-us/library/ms462947.aspx

The type identifier must be unique within the feature, but need not be unique across all feature definitions or site definitions. So make sure when you have multiple list templates in the same feature, you made them with different type attributes. It is also recommended to create Type value greater than 10000. For my List Instance I assigned the Type attribute with a value of 10001.

After Modifications, the List template file looks as follows.

clip_image007

Notice that, I just updated the Type attribute, but depending on your needs you may add other attributes.

Now I am going to add fields for my List template. As I mentioned initially, I will have only 2 fields date and amount. Refer this link to under stand more about Field element http://msdn.microsoft.com/en-us/library/ms437580.aspx

When you define a field, you need to specifiy a guid as ID enclosed in braces{}. To create a Guid, do the following steps.

From visual Studio menu, select tools, then select create guid

clip_image009

The Create Guid dialog will appear as follows

clip_image010

I have added the following fields to List Template.

 

 

Make sure for each field you create you use unique guid. Now I want to create a content type that includes these fields. When you define a content type, you need to define an ID for the content type. This is a bit tricky. Refer the below article to under stand more about content type ID.

http://msdn.microsoft.com/en-us/library/aa543822.aspx

My content type should be a sub of item content type, so I am going to use the following rule to create my list content type id.

 

System

Item

prefix

Hexadecimal GUID

0x

01

00

4FDDEDBF38D14332A625BCBC60F1667A

 

(for hexadecimal guid, I create a guid from visual studio and then removed braces and hyphens)

So my content type id is 0x01004FDDEDBF38D14332A625BCBC60F1667A

Add the following content type tag just above the ListTemplate start tag.

 
   
     
     
 
 

The definition is very straight forward. See the tags where you add the reference to previously created fields.

Find the snapshot of Elements.xml file after the above items added.

clip_image012

Now you have defined fields, content type and list template. Now you need to link your list definition to content type. You need to perform this in the schema.xml file. Open schema.xml file, by default it will look similar to the below snapshot.

clip_image013

Now you need to replace the element with the below

 

 
   

Now copy all the tags from Elements.xml and paste in between and . This is a duplication of work but you need to do this. After replaced, the Fields tag will look as follows.

 

 
   
  StaticName=”ExpenseDate” Name=”ExpenseDate” Group=”Expense Columns” /> 
   
  StaticName=”Amount” Name=”Amount” Group=”Expense Columns” /> 

Now you need to add the field references to view fields. There will be multiple tags, you can add field references in all or atleast in the View with BaseViewID=1, as this is the default view. See the snapshot of default view in the schema.xml file

clip_image014

In between ViewFields add the below markup.

See the snapshot of schema.xml after made the changes.

clip_image016

clip_image018

Now you are done with the list definition. Now you need to modify the List Instance to use the template you just created. Open the elements.xml file under the List Instance 1, the snap shot of default Elements.xml is as follows.

clip_image019

You need to change the TemplateType to the Type attribute you mentioned in the List Template, i.e. 10001. Also you can modify the list title, url etc. Also you can add initial data to the list instance so that the data will be inserted to the default list instance on feature activation.

Place the below xml inside tag for inserting initial data

 
   
     
      travel expense 
      01-01-2011 
      20.00 
   
 
     
       your expense title 
      01-01-2011 
      10.00 
   
 
 
 

See the snap shot of List Instance 1 after all changes were made.

clip_image020

Now we are ready to deploy the List defenition. Right click the project and click on deploy.

clip_image021

If you made everything correct, visual Studio will successfully deploy the list definition. Now you can find one list instance created in your SharePoint site. Open the list instance, you will find the data already inserted to it.

clip_image023

When you create new item in SharePoint, you will find the expense template.

clip_image025

It is easy to create List Definitions for SharePoint 2010 using Visual Studio 2010. Once you successfully tested your list definition project, you can package it to WSP file and deploy to multiple farms.

Creating a Folder in a SharePoint List and adding Items to it programatically

So, this took me a little while to get straight today when I was writing a web part.  It is pretty straight forward but the only information I could find online dealt with Document Libraries or didn’t provide code that worked.

I wanted to create a folder in a list, and then add items to that folder.  Furthermore, I needed to be able to find the folder in the future by name and add additional items to it.  Well, that seems like it should be quite simple, but there is no lookup by name, just GUID or int ID for the SPFolder object.

Here is the code to create the SPFolder for a list (Notice how it is actually an SPListItem…).  Note that this code already grabs the list from an SPWeb object.

SPListItem auditFolder = auditList.Items.Add(auditList.RootFolder.ServerRelativeUrl, SPFileSystemObjectType.Folder, auditFileName);
auditFolder.Update();

Then, the code to add an item to a folder inside of a list is below – note that I don’t update any fields before saving the list item with an Update call.

SPListItem auditItem = auditList.Items.Add(auditFolder.Folder.ServerRelativeUrl, SPFileSystemObjectType.File, null);
auditItem.Update();

But to the point I made before about not being able to do a lookup on a folder by its Name is kind of a pain, I ended up using a for loop, iterating through the folders in the list and looking for a specific one by name as shown below. Also note that you may need to call allowunsafeupdates for this to work in your environment.

SPList auditList = ElevatedWeb.Lists[auditLogList];
SPListItem auditFolder = null;
bool folderExists = false;
// Check to see if folder already exists, if not create it
for (int i = 0; i < auditList.Folders.Count; i++)
{
if (auditList.Folders[i].Folder.Name == auditFileName)
{
auditFolder = auditList.Folders[i];
folderExists = true;
}
}

if (!folderExists) // The folder does not exist so we create it and add the item
{
auditFolder = auditList.Items.Add(auditList.RootFolder.ServerRelativeUrl, SPFileSystemObjectType.Folder, auditFileName);
auditFolder.Update();
SPListItem auditItem = auditList.Items.Add(auditFolder.Folder.ServerRelativeUrl, SPFileSystemObjectType.File, null);
// Fill in properties of the list item here
auditItem.Update();
}

Well, like I said I used this inside of a web part, and since there wasn’t much to it I will probably put it up here in a few days. Hopefully this saves someone some time, Later.

SharePoint – ListField Iterator

This control renders each field in a list item with an appropriate control. A single line text field will be rendered as a text box while a lookup field will be rendered as combo box.
This control resides in the Microsoft.SharePoint.WebControlsnamespace of theMicrosoft.SharePoint.dll.
You  can use this control in a custom application page or in a custom Edit, New and Display form.
In its simplest way you can declare the control as follows:
                        ControlMode="New" ListId="{e2886b6e-4d63-4063-a02c-eac7fb3aef79}" />

This renders the first list item as follows:

You can set different properties of the ListFieldIterator control:

  • ListId: This property must contain the id – which is a Guid – of the list you want to display.
  • ControlMode: Defines whether the controls are displayed in display mode, edit mode or new mode.
  • ExcludeFields: Specify the fields that don’t need to be rendered. Separate each field with ;#
  • Item: In code behind, you can retrieve the current list item by using this property.
  • ItemId: in code behind, you can retrieve the id of the current list item. But you can also decide which item to render by setting this attribute declaratively.
            ControlMode="Edit" ListId="{e2886b6e-4d63-4063-a02c-eac7fb3aef79}" ItemId="2" />

  • List: In code behind, you can retrieve the current list by using this property.
  • Template: you can set this property if you have deployed your own custom template to the 12\TEMPLATE\CONTROLTEMPLATES folder.

Interacting with other fields from a custom field

 Today I will show you how you can create the interaction itself between the fields.

It requires some little tricks, but after we solve the exercise you will see that it is not so complicate and in the forthcoming post I will show you some very powerful example to demonstrate you the usability of this technique.

The main point of the interaction is to get the reference to the other field controls. As I did last time, I will first introduce an interesting approach that – sad but true – does not work.

On the forms the fields are rendered within a ListFieldIterator control. Individual fields of type SPField can be addressed through the Fieldscollection (inherited from FormComponent) of this class that returns an SPFieldCollection. SPField class has a property calledFieldRenderingControl that returns BaseFieldControl. Since the actualListFieldIterator can be accessed through the parent chain of the actual field control, at the first sight it seems to be a good idea to get the reference for another field using the following really long line of code:

BaseFieldControl fieldControl = ((Microsoft.SharePoint.WebControls.ListFieldIterator)this.Parent.Parent.Parent.Parent.Parent).Fields[fieldName].FieldRenderingControl;

Unfortunately that is not so simple. Although we got a valid reference to a field control, if you try to manipulate its properties, or just to read them, it turns out to be an other instance, not the one displayed on the forms. That is because theFieldRenderingControl returns a new instance of a subclass of theBaseFieldControl, that has really no relation to the actual form.

What other ways there are to get the reference field control? We know that it is a control on the page, but we don’t want to iterate through all of the controls just to find the field. Fortunately theBaseFieldControl class implements a specific interface IValidator and thus included in the Validators collection of the Page class. That is really nice, and we will depend on this behavior in a later post when implementing custom runtime validation of fields.

But for now it is enough to get the reference to the field control using a custom method like this:

  1. protected BaseFieldControl GetFieldControlByName(String fieldNameToSearch)
  2. {
  3.     String iteratorId = GetIteratorByFieldControl(this).ClientID;
  4.     foreach (IValidator validator in Page.Validators)
  5.     {
  6.         if (validator is BaseFieldControl)
  7.         {
  8.             BaseFieldControl baseField = (BaseFieldControl)validator;
  9.             String fieldName = baseField.FieldName;
  10.             if ((fieldName == fieldNameToSearch) &&
  11.                 (GetIteratorByFieldControl(baseField).ClientID == iteratorId))
  12.             {
  13.                 return baseField;
  14.             }
  15.         }
  16.     }
  17.     return null;
  18. }
  19.  
  20. private ListFieldIterator GetIteratorByFieldControl(BaseFieldControl fieldControl)
  21. {
  22.     return (Microsoft.SharePoint.WebControls.ListFieldIterator)this.Parent.Parent.Parent.Parent.Parent;
  23. }

In this method we iterate through the validators on the page, and do some checks in the following order:

  1. Is the field derived from the BaseFieldControl class?
  2. Is the field name the same we are looking for?
  3. An extra check just to be sure: is the field rendered in the sameListFieldIterator as the current field control. Without this check it is possible to have multiple forms on the same page having fields with the same name. We really don’t want to interact with fields in other forms. At least, not now…

Let’s see some simple practical example for usage of this method. Of course, in a production environment you should add some extra logic for null values, exception handling and tracing/logging, but I try to keep it simple now. All of the code snippets are for the field control class that is derived from the BaseFieldControl class.

In the first example we set the field control mode to display. That can you use to prevent users to modify the field value, for example based on the user’s permissions or the value of other field.

  1. protected void SetFieldReadOnly(String fieldName)
  2. {
  3.     BaseFieldControl fieldControl = GetFieldControlByName(fieldName);
  4.     fieldControl.ControlMode = SPControlMode.Display;          
  5. }

Sometimes it is required to hide the field value too. The next example hides the field having the specified name using the same technique we used to inject invisible field to the form.

  1. protected void HideField(String fieldName)
  2. {
  3.     BaseFieldControl fieldControl = GetFieldControlByName(fieldName);
  4.     fieldControl.Visible = false;
  5.     fieldControl.Parent.Parent.Visible = false;
  6. }

You can also set values of other fields using the same technique as illustrated in the code snippet below for a text field.

  1. protected void SetFieldValue(String fieldName, String fieldValue)
  2. {
  3.     TextField fieldText = (TextField)GetFieldControlByName(fieldName);
  4.     fieldText.Value = fieldValue;
  5.     fieldText.Text = fieldValue;
  6. }

You might ask why I don’t show you the simplest case: reading field value. That is because it is really not so simple, and I will describe it in details in a forthcoming post.

It might be useful to use these and similar methods in your custom field control and use that as the boilerplate class for more advanced fields.

The next code snippet assumes that you have a custom list with fields Field1, Field2, Field3, Field4 (all of these of type Single line of text), the default Title field and Field5 of type Choice with valuesValue1, Value2 and Value3. Furthermore, I suggest you to create your custom field as a “hidden” field as described here.

I’ve created an item in the list before adding our new field to the list columns. The following figure shows the values of the fields on the edit form. You can see there is nothing special on that:

image

We call the methods in the edit and new control modes of the field from the OnLoad method of the field control:

  1. if ((ControlMode == SPControlMode.Edit) || (ControlMode == SPControlMode.New))
  2. {
  3.     HideField(“Field1”);
  4.     SetFieldReadOnly(“Field3”);
  5.     SetFieldReadOnly(“Field5”);
  6.     SetFieldValue(“Field4”, “text”);
  7. }

After building, deploying, and adding the new field to the list, you should see the results immediately on the edit form:

image

It seems to be working perfectly, but if you would like to create you will notice that there is a minor issue with the code. Field3 should be empty, but it contains the text Field3 field value. The other read only field, Field5 of type Choice is displayed correctly.

image

There was a problem with setting the fields read only.

Since then I’ve found the source of the incorrect value in the display (read only) mode of the field on the new form and provide a workaround for that issue here, that is unfortunately a bit of hacking.

First, I should note, that as I observed, the value displayed in this case has no effect on the value saved into the item, but default values have also no effect. Furthermore, when the item is opened and saved in the edit mode, the former field values might be also lost.

I found that when the field control mode is set to display on the new form in our case, the value of the PreviewValueTyped property of the related field is displayed. That is FieldName field value. for the text fields (replace FieldName with the actual field name), 1,234.56 for numeric fields, the actual date and time for date type fields, default value or if there is no default value, the first option for choice fields.

The source of the issue seems to be is that the ItemFieldValueproperty and the ListItemFieldValue property of the BaseFieldControlreturn the value of the PreviewValueTyped if the ItemId property is zero, that is the case for a new item. I should note that the obfuscated RenderFieldForDisplay method also references thePreviewValueTyped property. I’ve tried a hack and set the ItemId to –1, and it seems to solve part of the issue, the field value is displayed correctly.

But the values of the affected fields in the item are still not saved correctly, since setting the ItemId to –1 has a side effect that it resets the ItemFieldValue and the ListItemFieldValue properties to null. To correct this behavior I backed up the value of theListItemFieldValue property before setting the ItemId to –1, and restore it at the end. I cannot omit setting the ItemId to –1, since while the ItemId is zero, setting the value of the ListItemFieldValueproperty has no effect.

  1. protected void SetFieldReadOnly(String fieldName)
  2. {
  3.     BaseFieldControl fieldControl = GetFieldControlByName(fieldName);
  4.     Object value = fieldControl.ListItemFieldValue;
  5.     fieldControl.ControlMode = SPControlMode.Display;
  6.     if (ControlMode == SPControlMode.New)
  7.     {
  8.         fieldControl.ItemId = -1;
  9.         fieldControl.ListItemFieldValue = value;
  10.     }
  11. }

After these modifications the new form works as expected, but there is an issue with the edit form. Even the correct values are displayed, empty text is saved for text field, and the first item is set for the choice field when saving the item.

This issue was solved by placing the code from the OnLoad method to the OnInit method of the field control.

An important note finally. It is mandatory to place the custom field that tries to access other fields using the GetFieldControlByNamemethod introduced in the former post after the last field it references. You can change the field order using the Change Field Order page(List Settings / Column ordering), or you can do it using code. If you don’t do that this way, the method will not find the field on the page, as it is added only after the current field is loaded.

Completely Empty the SharePoint 2007/2010 Recycle Bin

If you have lots of stuff in your SharePoint Recycle Bin and want to empty it all, here’s a quick tip:

  1. Navigate to the recycle bin page (e.g., http://localhost/_layouts/recyclebin.aspx)
  2. In the address bar, type “javascript:emptyItems()” (minus the quotes)
  3. Press Enter. You will be asked if you really want to empty the recycle bin.
  4. Click OK to empty it; click Cancel to leave it alone.

It’s much faster to empty it this way if you have multiple pages of “stuff” in your recycle bin.

[Update: This tip works with both SharePoint 2007 and SharePoint 2010.]

Working with SharePoint 2010 search web service

In this article we will discuss how to user search web service in SharePoint 2010. We will search by using SharePoint search web service. Also you can check about FAST search here. SharePoint 2010 search is very useful and advanced in SharePoint 2010.
There are different search web services available for SharePoint search and SharePoint Enterprise Search. The service url for sharepoint search is:

http://[URL]/_vti_bin/spsearch.asmx
The web service url for sharepoint enterprise search is:
http://[URL]/_vti_bin/search.asmx
For this demo we will use client object model and we will bind the search result to a datagridview in a windows application.
You can put a Textbox where user can put the search text, a button and a datagridview where user can see the search result as output. see the figure for reference.

In the next step we need to add reference to the web service.
For this Right click on the project and click Add service reference. This will open the Add Service Reference dialog box. On that box click on Advanced… as shown in the figure below:

This will open the Service Reference Settings dialog box, from there click on Add Web Reference… as shown in the figure below.

The above step will open the Add Web Reference dialog box.

In that window enter the URL of the web service and click on the green arrow. This will search and found the web service if present. Then click on Add Reference as shown in the figure below:

This finishes our reference to the web service.
Now open the Button click code.
First give reference to the web service like:
using SearchPOC.QueryWebServiceProxy;
Here we will use the QueryService class and pass the DefaultCredentials as the parameter.
Then it will take an XML as an search input parameter which is shown in the full code below.
Then here in this example we are calling the QueryEx method which returns the results as a DataSet. We also can use Query method which returns results as an XML document.
Full code:


private void btnSearch_Click(object sender, EventArgs e)
        {
            try
            {                      
            QueryService queryService = new QueryService();
            queryService.Credentials = System.Net.CredentialCache.DefaultCredentials;
            StringBuilder queryXml = new StringBuilder();
            queryXml.Append(““);
            queryXml.Append(““);
            queryXml.Append(““);
            queryXml.Append(““);
            queryXml.Append(“urn:Microsoft.Search.Response.Document.Document”);
            queryXml.Append(“
“);
            queryXml.Append(“
“);
            queryXml.Append(““);
            queryXml.Append(“5000“);
            queryXml.Append(“
“);
            queryXml.Append(““);
            queryXml.Append(““);
            queryXml.Append(txtSiteURL.Text);
            queryXml.Append(“
“);
            queryXml.Append(“
“);
            queryXml.Append(“
“);
            queryXml.Append(“
“);
            System.Data.DataSet queryResults = queryService.QueryEx(queryXml.ToString());
            dataGridView1.DataSource = queryResults.Tables[0];
            }
            catch (Exception ex)
            {
                string s = ex.InnerException.ToString();
            }
        }

Word wrapping SharePoint list column headers

A customer for our Highlighter product recently asked us how you could modify SharePoints List View Web Part (LVWP) to word wrap column headers. He had found that as he had replaced lengthy text with status icons he could fit a lot more columns on the page – if only he could shrink the column headers down.

To be clear – this isn’t unique to lists using our Highlighter product, this example shows a basic SharePoint list with a long title that is causing a horizontal toolbar as it won’t word warp even though the column will only ever contain Yes or No.

Of course you could rename the column and shorted the name and put more information in the description – but that only appears on the Edit form so it’s a balancing act between being brief and giving enough info so everyone knows what the columns contains.

Anyway – how to make these columns word wrap?

Inspired by this post on Stack Exchange I looked at using Cascading Style Sheets to do this.

The property we need is white-space : normal

Then we need to figure out which parts of the html to apply it to. This is done by HTML classes, so taking into account SharePoint 2007 and 2010 and different column styles (number/text/filterable/non-filterable) we end up with.

So the white-space property is applied to html elements with a class of .ms-vh, ms-vh2-nograd and so on.

We could also make the column headers center aligned and red (just for an example) by putting in

So how do we add these styles to the page?

You can use SharePoint Designer, but perhaps the easiest way is to add it via a Content Editor Web Part (CEWP)

  • Go to your list.
  • Select Site Actions > Edit Page
  • Click “Add a web part”



SharePoint 2007 SharePoint 2010
  • Select Miscellaneous > Content Editor Web Part
  • Click “open tool pane” then “Source Editor”
  • Add in the CSS from above
  • Select Media and Content > Content Editor
  • Select “Click here to add new content”
  • On the ribbon select Html > Edit HTML Source
  • Add in the CSS.

And – word wrapping :-

If this doesn’t work for you then as with all things ‘code’ exact syntax is important so check everything carefully – a “ is not the same as a ” for example. Also be sure that you’ve put the CSS in the HTML Source area, not just directly into the rich text editor.

You can add lots more effects (Red, bold etc) but sometimes its hard figuring out exactly what html elements and classes to target (e.g. you can’t apply a colour to the .ms-vh table header, you’ve got to apply it to an anchor element inside this – so “.ms-vh a”) – Firebug, the IE developer tools or the Chrome equivalent are invaluable for this – they will save your sanity!

Increase performance of SharePoint 2010 Server site


What?

How to tune SharePoint 2010 Server for better performance?
Why?

SharePoint has an array of areas where performance is an issue and bottlenecks occur. It is particularly important for public web sites, but Intranet sites & collaborative sites benefit from this as well. In this post we will learn how to tune SharePoint 2010 for better performance.

How?
Before you even start thinking about improving your performance, keep in mind that even the best configuration won’t help you if your hardware is simply too weak to handle the SharePoint environment.
SharePoint is very memory intensive. Always plan for fast network cards and plenty of RAM! It is very important that the server achieve the fastest response possible from the I/O subsystem. More and faster disks or arrays provide sufficient I/O operations per second (IOPS) while maintaining low latency and queuing on all disks.
In this post we will look at the below:
  • Infrastructure Optimization
  • Database Optimization
  • Caching
  • Server Optimization
  • Page Optimization
  • Other Considerations


Infrastructure Optimization:
Search in SharePoint is very memory intensive. It is often the first source of performance headaches.
The better the links to the database are optimized, the better the overall performance will be.
If all the servers (front-end servers and application servers) are behind the same switch, the application servers that run search will be going out through the switch each time an incremental crawl is kicked off. 
Below is an example diagram of an undesirable topography:
Try to separate front-end user traffic from back-end SQL traffic.
Front-end servers should talk to the SQL server(s) through one network and application servers & AD talk to SQL server(s) though a different network.

Below is a diagram of the desired topography:
Even better, set aside an index server in the farm and let it crawl itself without having to take traffic across the front-end servers, as shown below:

In addition to search, publishing sites require a lot of memory as the number of read operations will be 100-1000 times greater than write operations. ECM sites require more application servers as there will be a lot of back and forth talk between them.

Try to distribute your service applications across multiple application servers whenever possible.

Database Optimization:

Database Operations:

Different things in SharePoint have different effects on the databases.
Order of items by their impact (1 being the biggest killer whereas 10 has the least impact):
  1. Performance Point Services
  2. Search
  3. Content Query
  4. Security Trimming (SPSecurityTrimmedControl delegate)
  5. Collaboration
  6. Workflow
  7. Publishing
  8. Social
  9. Client Access
  10. Browsing
What is the impact of custom code? It depends on the quality of the code.
Database Size:

Even though Microsoft says that each content database can hold up to 4 TB, the recommended practical limit is 200 GB for easily manageable backup and restores.
Analytics databases grow very quickly to very large sizes. Try to isolate Analytics databases. Analytics reports can have significant impact on CPU load.

Search uses multiple databases for its operations. It uses separate databases for crawl, properties and administration. Crawl databases can be extremely large. Crawl databases also have heavy transactional volumes. Try to isolate temp and crawl databases if possible.

Database Management:


Performing the below steps at the database might result in better performance:
  • Manually configure auto-growth settings. The default auto-growth setting in SQL Server is 1 MB. Set it to 100MB / 200 MB depending on your environment. This allows the database to grow in larger chunks, which is more efficient since these databases tend to grow rapidly.
  • Defragment database indexes regularly.
  • Limit content DB size per site collection.
  • Isolate transaction logs by writing them off onto separate disks.
  • Enforce site collection quotas in Central Administration.


Caching:

Make sure that all the custom controls / web parts use caching.
I have build and contributed a framework for custom web parts out in Codeplex.
It is available here: http://asyncwebpartframewrk.codeplex.com/.
Web parts that are built using this framework will make use of caching and asynchronous loading of data into the web part after the page is loaded.

SharePoint supports the following types of cache:
  1. BLOB Cache
  2. Output Cache
  3. Object Cache
  4. Branch Cache
BLOB Cache:
BLOB Cache/Disk-based caching controls caching for binary large objects (BLOBs) such as image, sound, video, and some static content files like CSS. Disk-based caching is fast. It eliminates the need for database round trips. BLOBs are retrieved from the database once and stored on the Web client. Further requests are served from the cache and trimmed based on security.

BLOB Cache needs to be enabled from Web.Config. Make sure that there is enough space in the drive/server where blob cache is stored. It’s important to understand that BLOB cache is per-machine. So make sure that the BLOB cache settings are consistent across the whole farm. You don’t want one server with 1 GB of BLOB cache and another server with 4 GB of BLOB cache. You might see strange and inconsistency in performance if you don’t configure BLOB cache consistently.
By default, the disk-based BLOB cache is off and must be enabled on the front-end Web server. In order to enable BLOB cache, locate the Web.Config for the web application and edit it. The recommended approach for making such changes in Web.Config file is through a feature receiver or PowerShell by making use of SharePoint’s SPWebConfigModification class.
In the Web.Config file, find the following line:
In this line, change the location attribute to specify a directory that has enough space to accommodate the cache size.
We strongly recommend that you specify a directory that is not on the same drive as where either the server operating system swap files or server log files are stored.
To add or remove file types from the list of file types to be cached, for the path attribute, modify the regular expression to include or remove the appropriate file extension. If you add file extensions, make sure to separate each file type with a pipe (|), as shown in this line of code.
To change the size of the cache, type a new number for maxSize. The size is expressed in gigabytes (GB), and 10 GB is the default. It is recommended that you not set the cache size smaller than 10 GB. When you set the cache size, make sure to specify a number large enough to provide a buffer at least 20 percent bigger than the estimated size of the content that will be stored in the cache.
To enable the BLOB cache, change the enabled attribute, from “false” to “true“.
You can use an STSADM command to flush all BLOB caches associated with a specified Web application on different Web front-end computers on the farm:
stsadm –o setproperty –propertyname blobcacheflushcount –propertyvalue 11 –url http://mywebapp::port
Output Cache:
Output cache requires publishing infrastructure. It is specifically geared more towards publishing portals. HTML pages are written into memory and served from memory as opposed to serving them from databases. Watch out for authoring experience! If output cache is set in an authoring environment, authors may not see their changes until the cache expires. Similarly, make sure to not output cache search results.
Object Cache:
Object Cache is used in custom code. This is especially useful when the content that is served does not change quite often. It is extremely important to make sure that you cache and serve data appropriately to users based on their permissions when using object cache. You don’t want a user with insufficient privileges to be able to access data that he/she is not supposed to access just because the custom code has cached the data incorrectly without giving enough consideration to the permission levels.
Branch Cache:
Branch Cache is a feature within Windows 2008 R2 / Windows 7 Enterprise & Ultimate that allows you to pull documents from the network and cache them locally. Branch Cache improves performance of applications that use HTTP, HTTPS, as well as SMB (the protocol used for shared folders) and WebDav (an extension of HTTP). Because SharePoint uses these protocols, it is able to take advantage of Branch Cache. Just remember that clients must be using Windows 7 and Windows 2008 Server for it to work.
In order to enable cache for a site collection, navigate to the site collection settings page and then scroll down to the section “Site Collection Administration”.

As highlighted in the above screenshot, you can configure Object & Output cache from SharePoint UI.
Enable Output Cache, Object Cache & Cache Profiles on each SharePoint site collection. Enabling blob & output cache improves the site performance by 50-60%.
Server Optimization

IIS Compression:
IIS Compression is turned on by default in Windows Server 2008. An important thing to note is that it is just enabled but not configured.  IIS Compression takes all the objects in the site, compresses them and delivers them as smaller packages to the clients.  It can be configured to be set at a level between 0 and 9. By default, it is set to 0 when it is turned on. 9 means lot of pressure on CPU utilization.  We recommend it being set to 6/7/8/9 depending upon your hardware.
IIS Compression wont effect dynamic content such as web parts like Content Query Web Part etc. Just like blob & output cache it can only compress static content.  Depending on the level of compression set, page size will be reduced by 30% – 40%. 
IIS Compression is only enabled but not configured. If you want to make sure that it is enabled, fire open IIS Manager and choose a site.  Click on the button “Compression” as shown in the screenshot below:

IIS Compression needs to be configured through command prompt using the following scripts. (The below script sets the levels to 9)

%windir%\system32\inetsrv\appcmd.exe set config /section:httpCompression –[name=’gzip’].dynamicCompressionLevel:9

%windir%\system32\inetsrv\appcmd.exe set config /section:httpCompression –[name=’gzip’].staticCompressionLevel:9

Resource Throttling & Locks:

By default, resource throttling is set to 5000 items (You can have up to 20,000).  SQL Server by default locks the table when it executes a query that returns more than 5000 records from a record set.  You can change the 5000 item limit in Central Admin depending on your environment and requirements, but this is not recommended.
Instead, consider enabling bit rate throttling.  Bit rate throttling controls download speeds of large objects like Flash, Silverlight, videos, etc. by limiting the amount of bandwidth that can be used for streaming.

To enable bit rate throttling:

Navigate to Central Admin > Application Management > Manage Web Applications
Choose the desired web application and click on the button “General Settings” in the ribbon. In the drop down click on “Resource Throttling”

Enabling object model override allows custom code to be able to retrieve more than 5000 items at a time.

HTTP Request Throttling, which is on by default, monitors front-end server performance and in the event of HTTP request overload, rejects low priority requests when the threshold is reached. This is particularly useful for public facing web sites where there are more chances for DDOS kind of attacks.



Page Optimization:

Optimize Pages:

SharePoint pages contain lot of resources; these can include but are not limited to:
  • JavaScript Files
  • CSS Files
  • Navigation Controls
  • Menus
  • Web Parts
  • Custom Controls
  • Ribbon Control
  • Delegates
  • SPSecurityTrimmedControls
  • Publishing Fields
  • Search Controls
  • Hidden Controls
Customized pages (unghosted pages as they are called in earlier versions) may be easy to develop but they are bad in performance. However, The advantage with customized pages is that they can be created and modified using SharePoint Designer.  When a page is customized in SharePoint and saved, it will no longer be served from file system. Instead a copy of the page will be written into the database and from there on whenever the page is requested, it will be retrieved dynamically from the database.
Un-customized pages (ghosted pages) are always loaded from the file system. Thus they take advantage of blog cache and output cache. Thus, they load faster and perform better.  There is a noticeable 10% – 30% performance difference between customized and un-customized pages.  In order to create un-customized page layouts or master pages, you will have to develop solutions using Visual Studio 2010 that will deploy them to /_layouts/ folder in 14 hive.

In addition to pulling all the content from databases, all the customized pages will have to run through safe mode parser. Safe mode parser is a control that resides in each customized page and watches for inline scripts. Anything that comes out of the database has to run through the safe mode parser.

ASP.NET parses a page on first render and compiles it into an assembly. The safe mode parser does NOT compile pages. It is designed to interpretatively parse a page and create the object structure of the page. In the event inline server-side code is detected, the safe mode parser will not allow the page to render. Additionally, the only objects within the page (i.e. controls marked as runat=’server’) which can be instantiated are those items found in the SafeControls list in Web.Config.

Optimize Branding:

I advise you start building master pages from minimal.master.  This is a much cleaner starting point that will remove much of the unnecessary items in standard master pages.  Consolidate all the CSS & JavaScript files and try to minify the JavaScript files so that the browser does not have to make multiple requests for multiple CSS/JS files.  Additionally, Use image stitching on pages with lots of small images to reduce the number of requests.

It is also recommended that all the resources such as style sheets, master pages, page layouts, images, JavaScript files, etc are stored on file system (i.e. /_layouts/ folder in 14 hive) not in the virtual file system within your site (Style Library, Publishing Images etc…). To achieve this, you will have to develop solutions using Visual Studio 2010 that will deploy them to /_layouts/ folder in 14 hive.

Also consider referencing files like jQuery.js, etc.. from Content Delivery Networks. Many of them allow you to link to their copies of the files.  Often times, you can Use CDN—for example the Google AJAX Libraries content delivery network—to serve JQuery to your users directly from Google’s network of data centers. Doing so has several advantages over hosting JQuery on your server(s): decreased latency, increased parallelism, and better caching.

Just because a SharePoint list can hold millions of items does not mean it should.  All user content in all lists throughout the entire site collection is stored in a single table in content database. Scary!!  The more the number of items, the slower the site will be. Consider partitioning the data into multiple site collections.

Even though list view web parts are improved in SharePoint 2010 and are XSLT based, they are still bad on performance with large data sets. XSLT is not particularly fast when there are large datasets. That is due to the large amount of looping that it needs to do to the xml that is returned. So consider developing custom controls with good caching mechanisms if you need to render large datasets to your users.

Wake up SharePoint 2010 Every Day:

Avoid that COLD, SLOW request that baffles users. Use a simple application called SPWakeUp.exe found here that touches each site and site collection on your SharePoint server to rebuild the IIS cache. Use Windows Task Scheduler to run this application once a day usually at around 4:00 AM.

Asynchronously Load Web Parts / Controls:

If you have XSLT List View Web Parts / Search Results Web Parts for displaying list data or aggregated data, SharePoint 2010 allows you to load the web part data asynchronously after the page is loaded. To enable asynchronous loading, edit the web part and in the editor part, navigate to the AJAX Options section and check the option “Enable Asynchronous Load”.
You can also enable asynchronous loading for Content Query Web Part as well. Unfortunately it is not so straight forward, explained in this post


Other Considerations:

List Definitions:

Plan list schemas, list and library limits well in advance. If a list definition consists of more columns of a particular type than the recommended number of columns, it results in row wrapping.


Column limits:

It is widely known that SharePoint Server 2010 data is stored in SQL Server tables. To allow for the maximum number of possible columns in a SharePoint list, SharePoint Server will create several rows in the database when data will not fit on a single row. This is called row wrapping.

Each time that a row is wrapped in SQL Server, an additional query load is put on the server when that item is queried because a SQL join must be included in the query. To prevent too much load, by default a maximum of six SQL Server rows are allowed for a SharePoint item. This limit leads to a particular limitation on the number of columns of each type that can be included in a SharePoint list. The article at this URL describes all the column limits: http://technet.microsoft.com/en-us/library/cc262787.aspx#Column

The row wrapping parameter can be increased beyond six, but this may result in too much load on the server. Performance testing is recommended before exceeding this limit.  Be careful—SQL row wrapping can degrade the performance by 35%.


Developer Dashboard:

Developer dashboard provides metrics on object execution for individual pages.  Turning on developer dashboard can be done in code or with PowerShell.
Wictor Wilen created a solution that can be used for configuring developer dashboard through UI.http://www.wictorwilen.se/Post/SharePoint-2010-Developer-Dashboard-configuration-feature.aspx

Timer Job Separation:

You can take some jobs and pin them to a content database which is running in a different farm or a different environment. So that load is off the server.

Finally many thanks to Eric Shupps for his wonderful demonstration at SharePoint Conference 2011. He inspired me to share this wealth of information that I learned from him. Eric can be found athttp://www.binarywave.com/blogs/eshupps/default.aspx

Additional Resources:

SharePoint Server 2010 Capacity Management: Software Boundaries and Limits
Capacity Management and Sizing Overview for SharePoint Server 2010
Capacity Planning for SharePoint Server 2010
Performance Testing for SharePoint Server 2010
Storage and SQL Server Capacity Planning and Configuration
Performance and Capacity Technical Case Studies
Monitoring and Maintaining SharePoint Server 2010
Performance Testing for SharePoint Server 2010