Tuesday, November 17, 2009

Caching with SPList-Sharepoint

In big sharepoint projects, it may be possible that performance of our application get reduce because of large amount of data stored in sharepoint list.In such scenario, calling Sharepoint list through sharepoint object model will harm the performance. caching can be useful in such scenario.
To implement caching we can use PortalSiteMapProvider class. The GetCachedListItemsByQuery() method of PortalSiteMapProvider Class to get the cached data.Below is the code snippet-
string strVal;
SPWeb web=SPControl.GetContextWeb(context);
SPQuery query = new SPQuery();
query.Query = "CAML Query";
PortalSiteMapProvider provider = PortalSiteMapProvider.CurrentNavSiteMapProviderNoEncodePortalWebSiteMapNode node = provider.FindSiteMapNode(web.ServerRelativeUrl.ToString()) as PortalWebSiteMapNode;
SiteMapNodeCollection items = provider.GetCachedListItemsByQuery(node, "List Name", query, web);
if (items != null)
foreach (PortalListItemSiteMapNode item in items) {
strVal = item["column name"].ToString();
Now strVal will get the cached data.
Alternatevely we can use HttpRunTime.cache, provided by ASP.Net, to implement caching in following way-
SPList lstStore;
SPListItemCollection items;
if (HttpRuntime.Cache["configstorelist"] == null)
lstStore = web.GetList(strlistPath);
HttpRuntime.Cache.Add("configstorelist", lstStore, null, DateTime.MaxValue, TimeSpan.FromMinutes(10),System.Web.Caching.CacheItemPriority.Default, null);
lstStore = (SPList)HttpRuntime.Cache["configstorelist"];
Here we will check if the Cache object is null or not. if it is null, it will call getList() method, else it will take the data from Cache object.One more point is to use GetList() method instead of SPList.Lists["name"] as SPList.Lists iterate through all the list so it may reduce the performance in large projects. So it is advisable to use GetList().

Monday, November 16, 2009

Accessing SPList-cross web application, sitecollection and site

There might be some scenario where we might have to access list across site collection. We might have a situation that we have to search for a list across a site collection. We may have to check whether the list is present in any of the site collection or not and if present we may have to do some operation on the list. Below is the code snippet that may be useful in this scenario-
private string GetListvalue()
string strVal=string.Empty;
Uri uri = new Uri(SPContext.Current.Web.Url.ToString());
SPWebApplication webApp = SPWebApplication.Lookup(new Uri("http://" + uri.Host));
if (webApp != null && webApp.Sites != null && webApp.Sites.Count > 0)
using (SPWeb web = SPContext.Current.Site.RootWeb)
foreach (SPSite site in webApp.Sites)
foreach (SPWeb web in site.AllWebs)
if (IfListExists(web, "List Name"))
SPList lstStore;
SPListItemCollection items;
lstStore = web.GetList(list path);
SPQuery query = new SPQuery();
query.Query = "CAML query";
items = lstStore.GetItems(query);
strVal = items[0]["Column name"].ToString();
return strVal;
Here I am accessing a sigle column from the first row that will be returned by the query.
The IfListExists() method will use Linq to check whether the list exists or not. Sharepoint don't have any method or properties to check the existance of the list. Another alternative is to use the Extension Methods. Below is the definition of the IfListExists() method-
private static bool IfListExists(SPWeb web, string listName)
return web.Lists.Cast().Any(list => string.Equals(list.Title, listName));

Thats it.
Hopes it will help. :)

Wednesday, July 29, 2009

Accessing multiple lists across multiple sites - SPSiteDataQuery

Sometimes, we may require to access multiple lists in multiple websites using a single query. Sharepoint provides two ways to achieve this-
1. joined subview using sharepoint designer ( click here to see)
2. Using SPSiteDataQuery class
SPSiteDataQuery class can be used to run CAML query across multiple lists in multiple websites within a site collection. It can be defined as-
SPSiteDataQuery query = new SPSiteDataQuery();
SPSiteDataQuery class returns a DataTable Class which can be used to access the data.
SPSiteDataQuery class has few properties which need to be set in order to use it. These properties are-

a. Lists- Can be used to specify list type, lists which has to be used in query through ListID, Maximum number of lists can be used in query etc. List Type is specified by BaseType attribute. The value of BaseType attribute will be
0 for a generic list
1 for a document library
3 for a discussion forum
4 for a survey
5 for a issues list.
The Lists property can be set as
query.Lists="<Lists BaseType="'0'/">";
If we want to query some specific lists only then we must specify their list ID as below-
<List ID=\"E8A71D9E-DDB6-4A2A-985C-976FCFBBDD23\"/>
to get the list ID go to list setting page take the value of 'List' querystring from page URL. It will be like-

replace %7B with '{', %7D with '}' and %2D with a '-' and we will have the list ID as
The maximum number of lists that the query can use will be specified by MaxListsLimit attribute as below-
<Lists BaseType='0' MaxListsLimit='10'>

b. Webs Property- This will specify the scope of the query. It may have any of the three values-

1. SiteCollection- query will run through the whole site collection.
query.Webs = "<Webs Scope="'SiteCollection'/">";

2. Recursive- query will run within website and its child site.
query.Webs = "<Webs Scope="Recursive">";

3. Blank- query will run through current web only.
query.Webs = "<Webs Scope="'">";

c. ViewFields property- It can be used to specify the column we are going to display. It can be used a follow-
query.ViewFields = "<FieldRef Name='Department' Nullable='TRUE' /><FieldRef Name='desc' Nullable='TRUE' />"
If we set the value Nullable='TRUE' then the query will fetch the data even if the column has null value in the corresponding row.

d. Query property- It is used to specify the CAML query as below-
query.Query="<Where><Eq><FieldRef Name="'ID'"><Value Type=" 'Counter'"> 1</Value></Eq></Where>";

e. RowLimit- This property will limit the number of rows which has to be fetched.
It can be used as-
query.RowLimit=5; ( To limit the number of rows to 5)

Below is the sample code to use SPSiteDataQuery-

SPWeb web = SPControl.GetContextWeb(Context);

SPSiteDataQuery q = new SPSiteDataQuery();

query.Query = "<Where><Eq><FieldRef Name='ID' /><Value Type='Counter'>1</Value></Eq></Where>";

query.ViewFields = "<FieldRef Name='Department' Nullable='TRUE' /><FieldRef Name='desc' Nullable='TRUE' /><FieldRef Name='DepartmentLink' Nullable='TRUE' />";

query.Lists = "<Lists BaseType='0'><List ID=\"E8A71D9E-DDB6-4A2A-985C-976FCFBBDD23\"/><List ID=\"B59FC80A-B586-4F31-A376-2FE20896641D\"/><List ID=\"3482EBF1-A2A7-4420%2DA920-09EA2635C557\"/></Lists>";

query.Webs = "<Webs Scope='SiteCollection'/>";

query.RowLimit = 10;

DataTable t = web.GetSiteData(query);
The DataTable will be populated by the data fetched from the list. It can be used to display the contents on the web page.

Wednesday, July 22, 2009

Displaying data from more than one list- Joined subview in SharePoint designer

When we works with sharepoint designer, generally DataView is used to display content from sharepoint lists/libraries. We can easily display contents from a single list. But what if we have to display contents from multiple lists? Dataview has ability to display data from multiple lists. We need to create new data source which will have data from multiple lists. We need to follow some steps to accomplish this-
1. open the site from sharepoint designer.
2. Select data source library from right task pane and and then click on 'create a new linked source'. Below is the screen shot-

3. In data source properties dialogue box, click on configure linked source.
4. A new box will appear as below. Select the lists/library that you want to link and then click on next.

5. In the linked data source wizard, there will be two options- merging and joining. Now select the second option i.e. join the contents and then click finish and then Ok. Below is the screen shot-

Now our data source has been created.

6. Now open the page where you want to display the data. Add a dataview control from dataview menu to the content region.

7. Now click on newly created data source and then select show data as below-

8. After clicking on show data, it will display all the columns in the data source. select the columns from first list which you want to display on dataview. Drag and drop the selected column to the dataview control-

9. The selected column will be inserted in dataview inside TD tag. Now suppose you wants to display data from second list on the right. Then right Click on TD in designer and then select insert cell to the right as below-

10. Now Select the desired columns from second list and then select "insert as joined subview" from top as below-

11. A join subview dialog box will be open. Here we will columns from the two list which have matching data as here I used ID column-

After selecting the column click on Ok. Now the selected column will be inserted in the newly created TD tag.

Its done now. It will display data from the two list based on the value of matching column. The look and feel of the subview might not be perfect but it can be updated by doing a little modification in HTML which is generated for the joined subview and by applying custom CSS classes.

Tuesday, July 7, 2009

MySIte Customization

In Sharepoint, a user can have his own personal site where he can add his personal information, documents and other related information. Sharepoint dont have any built-in mechanism to customize the look and feel of MySite template. If we wants to customiza it through Sharepoint designer then we will have to customize it for each user seperately. What if we wants to have a custom template for MySite common to all users? We will have to change its master page. The master page for MySite can be found at
C:\Program Files\Common Files\Microsoft Shared\web server extensions\12\TEMPLATE\GLOBAL\ application directory with name default.master.
we can open it in Sharepoint designer and customize it to give look and feel. But this is not a recommended approach. If we will modify the default.master, then we will not be able to use default view of mysite anymore as we are customizing the master page from site definition.
An alternate and recommended way to do it is feature stapling. In feature stapling, we can create a custom master page and replace that with default.master at run time using the feature.

The site templates for MySite are-

  • SPSPERS (private view)

  • SPSMSITEHOST (public view)

The master page for these two templates need to be replaced with our custom master page. I found a great blog by sridhar to achieve the feature stapling-


Using this blog I was able to customize the look and feel of master page.
Now my next task was to add a content editor webpart in default.aspx. The solution for this is a bit tricky. I had to play with ONET.XML to add the webparts.

Here is the steps I followed

1. Open the ONET.XML file from the location - C:\Program Files\Common Files\Microsoft Shared\web server extensions\12\TEMPLATE\SiteTemplates\SPSPERS\XML\ using some editor.( dont forget to take a backup of the same.)
2. Find the Modules tag and then tag 'AllUsersWebPart' .
3. Remove all the lines inside tag 'AllUsersWebPart' and add the following lines-
http://schemas.microsoft.com/WebPart/v2< /a>"> Microsoft.SharePoint, Version=, Culture=neutral, PublicKeyToken=71e9bce111e9429c Microsoft.SharePoint.WebPartPages.ContentEditorWebPart Use for formatted text, tables, and images. 1 None true true true /_layouts/images/mscontl.gif true < xmlns="< a href=">http://schemas.microsoft.com/WebPart/v2/ContentEditor< /a>" /> < xmlns="< a href=">http://schemas.microsoft.com/WebPart/v2/ContentEditor"><div><TABLE< /a> style="WIDTH: 100%" summary=""><TBODY><TR><TD>&nbsp;Put your title here</TD></TR><TR><TD>&nbsp;your picture here</TD></TR><TR><TD>enter your detail</TD></TR></TBODY></TABLE></div>< /content> < xmlns="< a href=">http://schemas.microsoft.com/WebPart/v2/ContentEditor< /a>" />

If you dont want to see the other webpart, you can comment or remove them.
4. save and close the ONET.XML
5. Do an IIS reset.

Thats it. Now the default.aspx will display content editor webpart.

Adding custom links
To add custom left links and remove the links coming on the left, do the following-

Open ONET.XML and find 'navbar' tags. 'navbar' tag is for links coming on left. this tag has 'name' attribute, the value of this attribute (prefixed by dollor) is coming from resource file core.resx. we can find this file at location- C:\Program Files\Common Files\Microsoft Shared\web server extensions\12\Resources\.
So when we add our custom link, we will have to add them in resource file also. tag also have attributes ID and URL. give an unique ID value in ID attribute and give URL of the page to the attribute URL. suppose I am adding a link Home. then entry would be-

For this, the entry in the resource file would be-
Name -- category_MySiteHome
value-- Home

Its fine. Now comment the existing tag and add your custom link by adding new entry. dont forget to put an entry in core.resx file for each tag you have added. Now save and close the ONET.XML. do an IIS Reset. your custom link will be visible on the default.aspx page of MySIte.

'Home' will be the text appeared on the link.

Adding built-in page for custom links

Now we have created custom link. we would like to have a custom page which will be linked to the custom link we have created.
Create an ASP.Net Application. Add a page home.aspx into the application. In the aspx file, put proper HTML and webpart zone as you want to be on the page. If you are adding a zone then add 'webpartpages:webpartzone' tag instead of 'asp:webpartzone' tag. you may add the additional functionality and events on code behind file. give a strong name to the project and build it.
Now we need a feature which will be used to deploy this page into mysite.

First create feature.xml file. open it in a editor and add the following-

< ?xml version="1.0" encoding="utf-8" ?>
< id="A28CE77C-7E79-49e1-867E-AF4280466BA7" title="custom pages for mysite" description="" xmlns="http://schemas.microsoft.com/sharepoint/" scope="Web" hidden="false" version="">
< location="element.xml">
< location="home.aspx">
< /elementmanifests>
< /feature>

Now Create element.xml file. Open it in an editor and add the following-

< ?xml version="1.0" encoding="utf-8" ?>
< xmlns="http://schemas.microsoft.com/sharepoint/">
< url="">
< url="home.aspx" name="home.aspx" type="Ghostable">
< /File>
< /Module>
< /Elements>

Now create a folder say- MySitePages. Put feature.xml,element.xml and home.aspx file into it. put this folder in C:\Program Files\Common Files\Microsoft Shared\web server extensions\12\TEMPLATE\FEATURES\ directory. Take the DLL of your ASP.Net application and put it into GAC.

Now we may use stsadm -o installfeature and stsadm -o activatefeature utility to deploy and activate the feature. we can activate the feature at site level after creating mysite.

After activating the page will be attached to the mySite.
Its done now. :)

Wednesday, June 24, 2009

The two ways of developing custom webparts using .Net

Sharepoint comes up with some out-of-the box (OOB) webparts that can be used in sharepoint applications. In addition sharepoint is flexible enough for custom webpoarts. We can create custom webparts using .net and these webparts can be used in sharepoint pages.

There are two ways to create custom webpart-
1. using User control
2. using class library project

One may ask that which method is better. As far as I am concern, when you need a complex UI in your webpart then use user control otherwise you may use class library project.

Creating webpart using User control

We need to follow few steps-

1. Create an ASP.Net web application and add an user control into it. Give some interesting name to it.
2. create your UI and write your code and build your application.
You can deploy it in two way-
a. Using smartpart- a third party tool to add user control to your sharepoint site
b. by deploying the DLL into GAC and putting your ASCX file into
C:\Program Files\Common Files\Microsoft Shared\web server extensions\12\TEMPLATE\CONTROLTEMPLATES directory.

Smartpart can be downloaded from here

Deployment using smartpart
  • Take the DLL and put it in the bin folder of your web application. i.e. inside C:\Inetpub\wwwroot\wss\VirtualDirectories\port number\BIN\ directory.

  • Create a folder named 'UserControls' inside the web application ( inside the C:\Inetpub\wwwroot\wss\VirtualDirectories\port number\ directory) and put the ascx file in that folder.

  • Open the web.config. Increase the trust level to Full. we dont need safecontrol entry for user control as it will be there for smartpart.

  • Do an IIS reset. your user control is ready to use.

  • To use it, Open the page where you want to add webpart, in edit mode. Click on 'add a webpart' in webpart zone. select smartpart from webpart zone. open the tool pane and select the user control. click on Ok. Its done now.

Deployment without Smartpart

  • Sign your web Application with strong name and build it again.

  • take your DLL and put it in GAC.

  • Take the ASCX file and put it on C:\Program Files\Common Files\Microsoft Shared\web server extensions\12\TEMPLATE\CONTROLTEMPLATES directory.

  • Add a SafeControls entry into web.config.

  • Do an IIS reset.

  • Go to webpart gallery on your site and click on New tab.

  • Select your webpart and populate the gallery with it. Now the webpart will be in webpart gallery for use.

Creating webpart using class library project

Follow the below steps-
  • Open visual studio and create class library project.

  • write your custom code for webparts and rendering controls using CreatChildControls() and Render() methods.

  • Sign your project with strong name.

  • Build the project.

  • Put the DLL into the GAC.

  • Add the SafeControl entry into the web.config file specifying the namespace and assembly.

  • Do an IIS reset.

  • Go to webpart gallery on your site and click on New tab.

  • Select your webpart and populate the gallery with it. Now the webpart will be in webpart gallery for use.

Thats It.
Hopes it would be helpful for everyone.


Monday, June 1, 2009

OWA-Sharepoint Integration- A tricky solution

Hi everyone, In my recent project I had to show mails, calendar and task from exchange server on sharepoint portal. I used OWA webparts to do the same. But the problem is- OWA webparts does not show the mails, calendar and tasks instead they were showing OWA login screen. After configuring Integrated window authentication on Exchange server the problem has been resolved but within the domain. when the user logs in from outside of the domain, it doesn't works. After spending few weeks on OWA-sharepoint integration and after experiencing every alternative, I came to some tricky solution by using the below blog-


I used Single-sign-on solution from this blog. In this an HTML file has been used which is using an IFRAME control for OWA login form and submitting the credential automatically to the OWA login form. To enable SSO, I used below blog.


With the help of network administrator I was able to enable the SSO on sharepoint server.As we are authenticating the user from AD, we need to put all the user credentials into SSO database once. later when u will update the credential from AD, it will automatically be updated in SSO database. The problem with this solution is-the credentials will be passed as clear text in querystring. to resolve this I wrote some custom encryption method. As here the encryption will me server side and the decryption will be on client side so I did not tried to use built-in encryption provided in .Net. Instead I followed custom encryption as below-

public string EncryptCredentials(string Cred)
string EncryptedCred = string.Empty;
string[] arr = new string[10];
for (int i = 0; i < Cred.Length; i++)
arr[i] = Cred.Substring(i, 1);
for (int i = 0; i < Cred.Length; i++)
switch (arr[i])
case "A":
arr[i] = "!@#$%";
......... and so on.
Now we need to decrypt the credentials on client side to pass it on OWA login form. I wrote some javascript decryption code to decrypt the credentials as below-

function getPassword(pwd)
var len=pwd.toString().length;
var arr=new Array();
var i;
var ClearPwd="";
for(i=0;i < len;i+=5)
for(i=0;i < len;i+=5)
switch (arr[i])
case "!@#$%":
arr[i] = "A";
} .......
n so on
Here the encrypted credential has been taken into array of string each having length five. This will again decrypt the credentials and that will be passed to OWA login form. Now the credential is being decrypted and can be passed to login form of OWA. Also, it will not be visible to anyone as a clear text. Its done Now. you may use the webpart now. hopes it will help. :)


Monday, May 25, 2009

Custom breadcrumb in sharepoint 2007

Hi every one,

In my recent sharepoint project,I need to use the breadcrumbs but the default breadcrumb provided in sharepoint is less flexible. For example if your pages are in 'Pages' directory then in the bradcrumb, there will be a link for 'pages' directory also which in most of the cases we dont want end user to view. The SiteMapPath control from ASP.net can be used to create a custom breadcrumb but I used an easy approach(as i felt) for it. I used C# and write some code as below-

String[] nav = null;
string[] navUrl = null;
nav = new string[10];
navUrl = new string[10];
int i = 0;
SPWeb web = SPControl.GetContextWeb(Context);
if (web.IsRootWeb == true)
nav[0] = web.Title;
navUrl[0] = web.Url.ToString() + "/" + SPContext.Current.File.Url.ToString();
while (!web.IsRootWeb)
nav[i] = web.Title;
navUrl[i] = web.Url.ToString() + "/Pages/Default.aspx";
web.Title = web.ParentWeb.Title;
web = web.ParentWeb;

nav[i] = web.Title;
navUrl[i] = web.Url.ToString() + "/" + SPContext.Current.File.Url.ToString();
string navigationStr = string.Empty;
navigationStr = "
Home";//set the home link

while (i > 0)
navigationStr = navigationStr + ">" + "
" + nav[i - 1] + "";
navigationStr = navigationStr + ">" + SPContext.Current.File.Title;
Table tblMain = new Table();
mainDiv.Controls.Add(tblMain);// mainDiv is a DIV tag works as container for the table
TableRow trMain = new TableRow();
TableCell tdBrad = new TableCell();
tdBrad.Text = navigationStr;

thats it. I put this code in an user control and deployed that control using smartpart(a third party tool). we may also create a class library project to create webpart for breadcrumb.

Hopes It will be helpful for needy people. :)