Tuesday, December 20, 2011

How to Customize SharePoint List Content Display using Content Query Web Part

Here I'm going to describe how we can use Content Query Web Part to Style SharePoint List. Thus Assume we are having a  SharePoint List Called Projects with Following Fields.


As you already knew default look and feel would be like below.


Now I'm going to render this list in to format something like below.


Step One

First you need to define Some names for these place holders (Yeh., I know this do not make any sense to you. But don’t worry just do the step). Thus I'm going to define these columns as follows.

  • Title –> MyTitle
  • Logo –> MyLogo
  • Project Summary –> MySummary
  • Project Description –> MyDesc

Step Two

Now you want to define a XSL Style Sheet using these names. Therefore I'm going to use <table> to layout the list item as below.

<xsl:template name="MyStyle" match="Row[@Style='MyStyle']" mode="itemstyle">
<table border='1'>
        <td colspan="2"><h3><xsl:value-of select="@MyTitle" /></h3></td>
            <xsl:attribute name="src">
                <xsl:value-of select="@MyLogo" />
            <xsl:value-of disable-output-escaping="yes" select="@MySummary" />
        <td colspan="2">
            <xsl:value-of disable-output-escaping="yes" select="@MyDesc" />

here i used XSLT to position the content inside my html tags. There are few attributes which are mandatory in this section. 

  • Name and Match should have equal names.

    • name =’X’ match=Row[@style=’X’]

  • mode = ‘itemstyle

now you have created XSLT which can given as a list style in the SharePoint.

Step Three

here we are going to put XSLT to the SharePoint.

First you need to open the SharePoint designer with the particular site. Then navigate to All Files and Style Library.


Here you can see many Folders inside. Now you have to go to XSL Style Sheet Folder.


Now you can see XSL files which are used by SharePoint to render it’s content. Here we are using ItemStyle.xsl for enable custom rendering.


Thus open this xsl file and put your xsl (when we created in step two) in the bottom of the xsl as follows.


Now difficult things are over.

Step Four

  • Add a Content Query Web Part


  • then go to edit web part and  and browse your list. ( here our list is Our Projects )


  • Then go to presentation section. and go little bit down. You can see style drop down.
  • Wow ..  Now you can see your style.


  • Ok the then select your custom xsl ( here MySample).
  • When you select you can see something like below.


  • Now you need to put actual list column names to these text boxes as follows.(Title column should use with the scope)


  • Then Click ok to Save. Now Every thing ok. You can see your new list rendering now.


Happy SharePoint :)

Wednesday, December 14, 2011

How to use SharePoint Feature to Activate and Deactivate Custom SharePoint Master page

Below example only set the Master page Url but not the custom master page URL. thus Layout pages will be same after you deploy the master page.  You can also change the Custom master page URL also.

Feature Activation

public override void FeatureActivated(SPFeatureReceiverProperties properties)
SPWeb web = properties.Feature.Parent as SPWeb;

string urlMaster;
string urlCustom;

if (@"/".Equals(web.ServerRelativeUrl))
urlMaster = @"/_catalogs/masterpage/BLLICT.master";
urlCustom = @"/_catalogs/masterpage/v4.master";
else {
urlMaster = string.Concat(web.ServerRelativeUrl , @"/_catalogs/masterpage/BLLICT.master");
urlCustom = string.Concat(web.ServerRelativeUrl , @"/_catalogs/masterpage/v4.master");

web.MasterUrl = urlMaster;
web.CustomMasterUrl = urlCustom;



Feature Deactivation (Reverse to Original Master)

public override void FeatureDeactivating(SPFeatureReceiverProperties properties)
SPWeb web = properties.Feature.Parent as SPWeb;
string urlCustom;

if (@"/".Equals(web.ServerRelativeUrl))
urlCustom = @"/_catalogs/masterpage/v4.master";
urlCustom = string.Concat(web.ServerRelativeUrl, @"/_catalogs/masterpage/v4.master");

web.MasterUrl = urlCustom;
web.CustomMasterUrl = urlCustom;


Wednesday, December 7, 2011

How to impersonate SharePoint Programmatically

There are many occurrences that we need to impersonate our SharePoint requests to server. Otherwise SharePoint will use system account or context credentials to perform the task.

In my case i want to programmatically approve a workflow task. but then i noticed it is showing modifiedby as   system account so i used following code to change the user credentials to intended user.

SPUserToken ApprovingUser = web.GetUserToken(“domain\username”);

using (SPSite site = new SPSite(“Site Url”, ApprovingUser))
using (SPWeb wb = site.OpenWeb())
/* Do Anything You want */

SPWorkflowTask.AlterTask throws “Specified method is not supported”

This error occurred to me when i was trying to programmatically approve a task in the SharePoint 2010.  

Later on I found that the problem is the Task List do not have the content Type WorkFlow Task inherited. After i add that content type it worked for me.

Thursday, December 1, 2011

How to Use & Character in SharePoint List Instance’s Field value

There are some special characters which we can use in the XML. thus XML parser will return something like Entity X not defined like errors. this problem comes using ok special characters such as &, > and etc.

Following shoes hoe you can use XML special characters inside the Field values in XML or SharePoint list instance creation.

<Field Name="Value" ><![CDATA[ & ]]></Field>
you can use any special character inside the  CDATA tag.

Monday, November 28, 2011

This document resides in a document library that is not trusted.

This error i got when I'm opening a SharePoint Task from MS Outlook. So it is pretty forward. You need to add the source site to the Trusted Sites in the IE (Internet Explorer) or ask network security admin to trust it from the proxy policies.

Add To Trusted Sites

Monday, October 24, 2011

How to do SharePoint 2010 Content Deployment

There are many articles in the web by describing Content Deployment in SharePoint 2010. But most of the time (In my case it do not work fine always in first time :-( )  it is not working property and giving plenty of errors which direct us to restoring the backup rather than trying Content Deployment in the SharePoint Server.

Here I'm going to my experiences and how I'm resolving those errors and little bit of background about the  SharePoint Content Deployment. Luckily i have manage to successfully proceed with the SharePoint Content Deployment most of the time.

What is SharePoint Content Deployment 

Content deploy can be use to export (deploy) content from one site collection to another site collection. content deployment is taking care of following contents in the source site collection.

  • Web pages – Deploy corresponding images styles , master pages and etc.
  • libraries
  • lists
  • resources

Content Deployment do not deploy

  • programs
  • assemblies
  • features
  • configuration information(Web.config)

Most of the time Content Deployment fails due to features. in the later i will explain how to over come these issues.

How to Configure SharePoint 2010 Content Deployment

We will use following scenario for the deployment


First you need to create a site collection in the production server (Our One is production/sites/ALR) which you are going to use in the content deployment.

When you are creating I'm always using site template as Select Template Later in the Custom Tab.You can use the blank template also but I'm recommending this one  because this one worked for me  all the times.


After that you need to configure content deployment

For than go to Central Administrator –> General Application Settings–> Configure Content Deployment in the Production Server


go to this and 

  • allow Accept incoming content deployment jobs in Accept Content Deployment Jobs section.


  • select Do not require encryption  in connection security.(If you want you can use https also. but for the moment select the other one. )


Then Go to Development Server and proceed following steps to configure deployment path and job.

First we need to Configure Deployment Job. For that Go to Central Administrator of the development machine and then General Application Settings and  then Configure content deployment paths and jobs.


then select New Job to create new content deployment job.

Then Specify Title and Description (Optional) and for the source application select Source Web Application as Development and Source Site site collection  as  /sites/ALR ( this is as per scenario you can choose your one)

then you need to give production server Central Admin URL with the Port to Destination Central Administration Web Application. here i found that some times we need to give the with IP addresses. but most of the time URL will work.


Then we need to provide authentication information. here most users are failing in this point (I were also). because what ever the selection we made we have to provide user name and password. Earlier i thought if we select windows authentication it does not need but it is not. Following shows sample values for  Authentication Information


after that select the destination Web Application and Site collection in Destination web application and site collection section.


For the moment leave Deploy User Names selected and Security Information All.

The SharePoint Automatically Create a Quick Deployment Job for you.


For the moment leave this and create a Deployment Job by right clicking the Deployment Configuration.


Here you can schedule the content deployment but for the movement select following options but of cause you can change them as you want later.

SQL Snapshots --> Do not use SQL Snapshot
Scope --> Entire Site Collection

the clink and finish the job creation. then you will see following kind of a menu.


Now the hard part comes. In the Menu Click Run Now or Test Job. (I’m Recommending Test Job before actually run the Job. Because some times Run Now deploy content partially and failed thus better to Test the Job before it is actually run. ) Then Most of the Time you will get Test Failed. If Not you are very lucky, thus you can proceed with the Run Now. But if you get Test Failed (sure you are :-) ) Following are the workaround you can fixed those errors.

Following are the most common errors you are getting..

Could not find Feature someFeature.

This error coming because this feature is not in the Production Server. Thus Install the Feature to the production server and run the Test Job again, then it will say another feature is missing thus keep on adding or removing unnecessary features in the development machine until it get succeed. You can find more feature details by using  power shell commands (click here).  

Could not find Feature FT-01-bbb35132-7695-139b-2e18-27444285e766.

These features are InfoPath Form Template Features. Thus get the relevant Form template and upload it to the production server.  The run the Test Job and see the progress.

If every thing finds most of the time you are getting these kind of errors.

  • An unexpected error has occurred
  • A list, survey, discussion board, or document library with the specified title already exists in this Web site. Please choose another title.
  • Unable to import the folder _catalogs/fpdatasources. There is already an object with the Id d029169b-1f86-4275-bb99-dd78a48f7952 in the database from another site collection.

These errors are coming because content database is having these objects and those are orphan in the site collection. thus you can repair the content database to delete these orphan objects in the particular site collection. 

thus you can use following power shell command to get rid of these errors (click here).

Repair SharePoint Database

sometimes you may encountered with problems such as restoring failures and  content deployment failures thus it is better to repair the database and see where is there any orphan objects in the site collection.

For that go to SharePoint Management Shell as an administrator,

use following command

stsadm -o databaserepair -url <url name> -databasename <database name>



here no Orphaned Objects found if they are listed run the command with deletecorruption option.

stsadm -o databaserepair -url <url name> -databasename <database name> -deletecorruption


Tuesday, October 18, 2011

Power Shell Command for get SharePoint Feature (SP Feature) By ID

Use following power shell command to  search and get the SharePoint Feature.

Get-SPFeature -Identity ID


SharePoint Solution deployment not working and Falling in the front end after installing the SP1 (SharePoint Service Pack 1)

This issue is also generate the following event log.

Application Server Administration job failed for service instance Microsoft.Office.Server.Search.Administration.SearchServiceInstance

Reason: Requested registry access is not allowed.

Technical Support Details:
System.Security.SecurityException: Requested registry access is not allowed.
   at Microsoft.Office.Server.Search.Administration.SearchServiceInstance.Synchronize()
   at Microsoft.Office.Server.Administration.ApplicationServerJob.ProvisionLocalSharedServiceInstances(Boolean isAdministrationServiceJob)

these might be other reason also like not having correct permission to the application pool running user. But in my case i solved it by running the SharePoint Product Configuration Wizard.


Thursday, October 13, 2011

Presentation - MVC 3 @ University of Moratuwa

@ University Of Moratuwa 20 Oct 2011 10.30AM – 11.30AM
I have conducted this presentation  for IT students in Moratuwa University. The entire workshop is organized by Student Champs with great guidance of Wela.
I hope presentation went well and few questions are asked from student also. The presentation gave an introduction and guidance to Microsoft MVC 3 application development.  

Wednesday, October 12, 2011

Switch SharePoint Pages to Edit Mode

Type following JavaScript in the Address bar in the browser.

Thursday, October 6, 2011

Generic Type Convert in C#

Cannot implicitly convert type 'object' to 'T'. An explicit conversion exists (are you missing a cast?) 

Following code can be use to convert your object to generic value.
T ret = (T)Convert.ChangeType(yourobject,typeof(T));

SharePoint 2010 List Template Ids






1200 Administrator tasks list 202 Meeting Attendees list
104 Announcements list 204 Meeting Decisions list
303 Blog Categories list 207 Meeting Objectives list
302 Blog Comments list 200 Meeting Series list
301 Blog Posts list 210 Meeting text box
105 Contacts list 211 Meeting Things To Bring list
120 Custom grid for a list 212 Meeting Workspace Pages list
118 Custom Workflow Process 117 No-Code Workflows
130 Data Connection library 2002 Personal document library
110 Data sources 109 Picture library
108 Discussion board 300 Portal Sites list
101 Document library 2003 Private document library
106 Events list 111 Site template gallery
150 Gantt Tasks list 102 Survey
100 Generic list / Custom List 107 Tasks list
1100 Issue tracking 112 User Information list
103 Links list 113 Web Part gallery
114 List template gallery 119 Wiki Page library
116 Master pages gallery 140 Workflow History
201 Meeting Agenda list 115 XML Form library

Wednesday, October 5, 2011

My SQL LIMIT Clause gives problems with Stored Procedure

I found the following workout.


    SET @SQL = CONCAT("SELECT * FROM customers LIMIT ",paraFrom" , ",paraPage ) ;
    PREPARE stmt FROM @sql; execute stmt;

Could not load file or assembly 'Microsoft.SharePoint.Sandbox' or one of its dependencies ..

Go to the bin folder and remove the DLL and debug. It should work. It worked for me.

Tuesday, October 4, 2011

Form resubmit on Refresh

I had issue with resubmitting the form  when user refresh the form. i had to disable this accidental behavior in the MVC3. Yes of cause we can redirect to another action to prevent this behavior. but in my case i do not want to do that. there fore i used following JavaScript to disable browser refresh and back button.

document.attachEvent("onkeydown", my_onkeydown_handler);
function my_onkeydown_handler() {
switch (event.keyCode) {

case 116: // 'F5'
event.returnValue = false;
event.keyCode = 0;
window.status = "F5 disabled";

Monday, October 3, 2011

InfoPath Repeating Rows Selection Issue/Problem

I had a problem with selecting InfoPath repeating rows for applying a condition. Therefore for i used following mechanism to correctly select the current row.  Here is my scenario,


I’m writing a formula for fld_CorpStatus by accessing field fld_corpOff. but i should access the same row data in the run time. there for i used following xpath expression to access the fld_corpOff.


Explanation :- we are getting the current (fld_CorpStatus)  and then go to it’s parent (CorpOfficeGroup) the access the fld_corpOff

Wednesday, September 28, 2011

SharePoint 2010 CSS classes


CSS Class(es)




Applies CSS styles in corev4.css to the page.

Ribbon container


Makes the Ribbon container the full width of the page row.



Used to show or hide the ribbon title area when the ribbon is opened or closed.



Defines the main ribbon CSS class.



Defines the elements above the ribbon body, from the top of the page up to and including the ribbon tab titles.

Site Actions menu


Sets styles for the Site Actions menu as a whole.



Sets styles for the inner Site Actions menu.



Sets the margin-right property on the top menu.

Breadcrumb menu


Sets styles for the Breadcrumb menu as a whole.



Sets styles on hover over the Breadcrumb menu.

Breadcrumb menu header


Sets styles on the Breadcrumb menu top area when the drop-down tree is open.



Sets styles on the breadcrumb folder icon when the breadcrumb tree drop-down menu is selected.

Breadcrumb menu items


Sets breadcrumb item styles.



Sets styles on the breadcrumb Team Site root tree element.



Sets styles on the breadcrumb Home tree element.

Edit tab


Sets styles on the Edit tab.

Browse tab


Sets styles for the container for the tab title.



Sets styles for the tab title.



Sets styles specific to the Browse tab



Sets styles for a selected tab title.



Sets styles for the Ribbon tab title anchor (the link element that makes the table title clickable).



Sets styles for tab title span.

Page Tab


Sets styles for the tab title.



Sets styles for the Ribbon tab title anchor (the link element that makes the table title clickable).



Sets styles for tab title span.

User menu


Sets styles for the top right corner container menu.



Sets styles applied to a menu item.



Sets the margin-right property on a drop-down menu item.



Sets the margin-right property on the top menu.

Title row


Makes the Title row the full width of the page row.



Sets styles on page title elements.



Sets styles for elements on the left part of the page.



Sets margin and alignment on the title logo image.



Sets styles on all text to the right of the page logo graphic.

Search area


Sets padding values on the Search control in the secondary menu.



Sets styles for elements on the right part of the page.

QuickLaunch menu items


Sets styles for the Home button located under the Site logo.



Sets styles on the text of the Home button.

Recycle Bin link


Sets styles specific to the Recycle Bin link element.



Sets styles on the link element.

All Site Content link


Sets styles specific to the All Site Content link element.



Sets styles on the link element.

Shared Documents link


Sets styles on the header section in the Web Part.



Sets standard header styles.



Sets styles on the Web Part title.

Web part menu


Sets styles on the Web Part menu.



Sets styles on the Web Part menu image.

Selection checkbox


Sets styles on the Web Part selection check box.



Sets span styles on the Web Part selection check box.

Item selection checkbox


Sets styles on the item selection check-box icon.



Sets the height property.

Type option, Name option, Modified option, Modified By option


Sets padding-top property.



Sets padding, position, and display properties on the drop-down menu.



Sets the height property.

Shared Documents text


Sets styles on the Shared Documents control group text area (bottom of group).

Add document link


Sets styles specified to the Add document link.

Photo image


Rich text editor class that sets the float property on controls of the Team Site Home Web part.



Rich text editor class that sets styles on content areas of the Team Site Home Web part.



Rich text editor class that sets the theme fore-color (to dark blue) on the Getting Started Wiki area.

Getting Started area


Rich text editor class that sets the float property on controls of the Team Site Home Web part.



Rich text editor class that sets styles on content areas of the Team Site Home Web part.



Rich text editor class that sets the theme fore-color (to dark blue) on the Getting Started Wiki area.

Share this site, Change site theme, Set site icon, Customize QuickLaunch links

ms-rteTable-0, ms-rteTableEvenRow-0, ms-rteTableEvenCol-0, ms-rteTableOddCol-0, ms-rteTableOddRow-0

Rich text editor classes that set styles on the controls under the Getting Started Wiki area.


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

Thursday, September 22, 2011

Save site as template not visible in SharePoint Site Actions

This can make visible by turning off the SharePoint Server Publishing in the manage site features. If you enable the publishing features Save as Template is not visible.

Saturday, September 17, 2011

Please locate this file or insert Microsoft Visual Studio Team System 2010 Team Suite Beta 1 – ENU disk 1 now

this massage came when i tried to install  Visual Studio 2010 Service Pack 1. I do not have the Team foundation installed in my machine either.

Ultimately i found that there is a program installed in Microsoft Team Foundation Server 2010 Beta 1 Object Model – ENU in the program files. i uninstalled it,

Wow.. I manage to install the service pack without any errors.

Thursday, September 8, 2011

How to Improve Workflow Performance in SharePoint Server 2010

SharePoint workflows are getting  slow for several reasons. in my environment I'm having a problem with following performance issues, therefore in my environment i got following problems.

  • When a item added to the library it takes some times to initiate the workflow.
  • Workflow mail generating is not very fast sometimes.
  • Workflows takes more time to process
  • “Due to heavy load, the latest workflow operation has been queued. It will attempt to resume at a later time” is coming sometimes.
  • I had a custom workflow approval web part and it is taking more than 30 seconds to proceed.

Work Done

I had a custom workflow approval web part and it is taking more than 30 seconds to proceed.

here in my custom web part there is the function which is programmatically updating the workflow.

SPWorkflowTask.AlterTask(item, data, false)

the last parameter mentioning whether it is synchronous asynchronous. if  is it true it it will wait until workflow schedule accept the workflow task. this is taking 30 seconds most of  the time. if it is false the method will return true immediately and not waiting for schedule approval.


Farm Level Workflow Improvements

There are few ways that we can improve SharePoint workflow  services.

  • Increase Throttle Size
  • Increase Batch Size
  • Time Out
  • Workflow Timer Interval

Increase Throttle Size

“The workflow throttle setting controls how many workflows can be processing at any one time on the entire server farm”. (Ref MSDN) since if we  can increase the throttle it will help to increase the number of workflows running at a time.

Following command shows how to get the existing value. the default is set to 15. use SharePoint shell to execute this command.

stsadm -o getproperty -pn workflow-eventdelivery-throttle


You can change the value by using following command. Below example change the current value to 25.

stsadm -o setproperty -pn workflow-eventdelivery-throttle -pv "25"


Increase Batch Size

“batch size property controls how many work items waiting to be processed by the timer service will be executed in each run” (Ref MSDN). Therefore if we increase the Batch Size there will be more workflow items ready to execute in the next time. Batch size is improving performance in Immediate Execution and Timer Job.

Following command shows the current batch size in the farm.

stsadm -o getproperty -pn workitem-eventdelivery-batchsize


as you can see default value is set to 100. following command will increate the size to 125.

stsadm -o setproperty -pn workitem-eventdelivery-batchsize -pv "125"


Time Out

Timeout specify the time which can be take maximum to complete the workflow timer job. of cause not finished timers jobs can  proceed in next cycle. this value is specify in minutes. default value is 5.

Following command shows how you can view the current configuration.

stsadm -o getproperty -pn workflow-eventdelivery-timeout


Following command will change the existing value to 10.

stsadm -o setproperty -pn workflow-eventdelivery-timeout -pv "10"


Workflow Timer Interval

Workflow timer Interval how often SPtimer job should run to process workflow items. this is specify in the application level not in the farm level like others.

following command shows the current setting of the web application.

stsadm -o getproperty -pn job-workflow -url http://Webapplication

If you type wrong URL following error will come.

The server administration programs and the Microsoft SharePoint Foundation Web applications on this Web server are not compatible.  Ensure that the administration program is the same version as the Web application.


Following table shows the values you can set for the property.

SPTimer schedule string format


"Every 10 minutes between 0 and 30"

Timer fires every 10 minutes from the top of the hour to half past the hour

"Hourly between 9 and 17"

Every hour from 9 A.M. to 5 P.M.

"Daily at 15:00:00"

Timer fires every day at 3 P.M.

"Monthly at 15 15:00:00"

Timer fires on the 15th of every month at 3 P.M.

Following command set the workflow timer interval.

stsadm -o setproperty -pn job-workflow -pv "Every 10 minutes between 0 and 30" -url http://webapplication:port


Monday, August 15, 2011

Load SharePoint List Items Using Server Object Model

using (SPSite site = new SPSite(ServerUrl))
    using (SPWeb web = site.OpenWeb())
        SPList Tasks = web.Lists[TaskListName];
        // What ever u want

How to use SharePoint Client Object Model to get User Information by User Lookup ID

protected string getUserEmail(int lookupid)
    String Useremail = string.Empty; 
        using (ClientContext clientContext = new ClientContext(siteUrl))
            Microsoft.SharePoint.Client.ListItem userInfo = clientContext.Web.SiteUserInfoList.GetItemById(lookupid);
            Useremail = userInfo["EMail"].ToString();
    catch (Exception ex)
        // TODO: // handle the error             
    return Useremail;