All posts by Hojo Clement

About Hojo Clement

Hojo Clement was working in US Technology in Trivandrum as a Senior Software Engineer. He has 6 years experience in working with Web Development Technologies inlcuding MOSS and ASP.net.

Complex CAML queries made simple

Update: If you want a quicker solution, please check out my new CAML Viewer Web Part for SharePoint 2010.

In this post we will see how we can generate complex CAML queries easily. We will also see how we can use this query to fetch data from the list.

If you want to create a complex query, first create a list view based on the required criteria. Then use the below code to get the query.

[sourcecode language="csharp"]
SPWeb web = SPControl.GetContextWeb(this.Context);
SPList spList = web.Lists["Mylist"];
SPView view = spList.Views["Myview"];
Response.Write(view.Query.ToString());
[/sourcecode]

Once we have this CAML query we can easily extract data from SharePoint list. Below is the code to fetch data from SharePoint list using CAML query

[sourcecode language="csharp"]
SPQuery query = new SPQuery();
query.Query = view.Query.ToString();
SPListItemCollection cole = spList.GetItems(query);
foreach (SPListItem item in cole)
{
Response.Write(item["Title"] +"<br />");
}
[/sourcecode]

Creating SharePoint list and add column programmatically

In this post we will see two methods for creating SharePoint list programmatically and add column to the created list

Using Object model
[sourcecode language="csharp"]SPSite site = new SPSite(SPContext.Current.Site.ID);
SPWeb web = site.OpenWeb();
SPListTemplate template = web.ListTemplates["Custom List"];
web.AllowUnsafeUpdates = true;
web.Lists.Add("MyList", "This list created using code", template);
SPList mylist = web.Lists["MyList"];
mylist.Fields.Add("MyField", SPFieldType.Text, false);
mylist.Update();
web.AllowUnsafeUpdates = false;[/sourcecode]

Using PowerShell Script

[sourcecode language="powershell"]
[system.reflection.assembly]::loadwithpartialname("microsoft.sharepoint")
$SPSite = New-Object Microsoft.SharePoint.SPSite("http://mysite");
$OpenWeb = $SpSite.OpenWeb();
$TemplateType = $OpenWeb.ListTemplates["Custom List"];
$OpenWeb.Lists.Add("my list"," ",$TemplateType);
$list=$Openweb.Lists["my list"]
$list.Fields.Add("My field", "Text", 0)
$OpenWeb.Dispose();
$SPSite.Dispose();[/sourcecode]

How to Add calculated column in SharePoint list programmatically

In this post we will see two methods for adding calculated field in SharePoint list.
Using Object model

[sourcecode language="csharp"]
SPSite site = new SPSite(SPContext.Current.Site.ID);
SPWeb web = site.OpenWeb();
web.AllowUnsafeUpdates = true;
SPList mylist = web.Lists["MyList"];
mylist.Fields.Add("CalcField", SPFieldType.Calculated, false);
SPFieldCalculated CalcField = (SPFieldCalculated)mylist.Fields["CalcField"];
CalcField.Formula = @"=CONCATENATE("" Calc : "",[Title])";
CalcField.Update();
mylist.Update();
web.AllowUnsafeUpdates = false;[/sourcecode]

Using PowerShell Script

[sourcecode language="powershell"]
[system.reflection.assembly]::loadwithpartialname("microsoft.sharepoint")
$SPSite = New-Object Microsoft.SharePoint.SPSite("http://mysite");
$OpenWeb = $SpSite.OpenWeb();
$list=$Openweb.Lists["MyList"]
$list.Fields.Add("CalcField", "Calculated", 0)
$SPField = $list.Fields.GetField("CalcField")
$SPField.Formula="=CONCATENATE([Field1],"" : "",[Field2])"
$SPField.Update()
$OpenWeb.Dispose();
$SPSite.Dispose();
[/sourcecode]

Simple Custom Feature in SharePoint

In this article we will see how we can develop a simple future for SharePoint.

Before starting the development, make sure that the following tools are installed.
1. Visual studio extension for windows SharePoint services:
http://www.microsoft.com/downloads/en/confirmation.aspx?familyId=7bf65b28-06e2-4e87-9bad-086e32185e68&displayLang=en

Note: You can refer the link
http://www.allaboutmoss.com/index.php/2010/03/22/install-visual-studio-2005-extensions-in-windows-xp-or-vista/ for installing Visual studio extension in Windows XP

2. WSP Builder: http://www.codeplex.com/wspbuilder

Let’s get started. Fire up visual studio

Click File -> New ->  Project

Choose the language (I am choosing c# for this tutorial) and select WSP Builder Project . Enter a project name and click OK.

Add the reference for sharepoint DLL in your project.

Right click the project click on property and choose signing create a strong key and click OK without password. Then save the project.

Add feature template in this project by Right clicking the project -> Add -> New Item
Choose WSPbuilder, select Feature with receiver and give the name of  feature. Click OK

Then enter the feature settings (I am choosing web as scope)

Scope specifies the scope in which the Feature can be activated and contains one of the following values: Farm (farm), WebApplication (Web application), Site (site collection), Web (Web site).

Open the simplefeature.cs file

We have to comment below code from the FeatureActivated,FeatureDeactivating, FeatureInstalled and FeatureUninstalling method.

[sourcecode language="csharp"]
throw new Exception(“The method or operation is not implemented.”);[/sourcecode]

Add the following code in FeatureActivated method. This code is to create a Custom List in the site while activating feature.

[sourcecode language="csharp"]
SPSite site = SPContext.Current.Site;
SPWeb web = site.OpenWeb();
web.AllowUnsafeUpdates = true;
SPListTemplateCollection customListTemplates = site.GetCustomListTemplates(web);
SPListTemplate listTemplate = web.ListTemplates["Custom List"];
web.Lists.Add(“Mylist”, “A custom list created by feature”, listTemplate);
web.Update();
web.AllowUnsafeUpdates = false;[/sourcecode]

That’s it. Build your project and make sure there are no errors.
Next step is to build WSP for this.Right click the Solution -> WSP Builder -> Build WSP.

Now you will see a new file named simplefeature.wsp in your project folder.

Deploy and Activate this feature in server

  • Copy the WSP to your SharePoint server
  • Open command prompt and navigate to the folder Program Files\Common Files\Microsoft Shared\web server extensions\12\BIN
  • run  stsadm -o addsolution -filename “G:\simplefeature.wsp”
  • Open central administration -> click operations
  • Click Solutions under Global configurations
  • Locate the newly added web part (simplefeature.wsp) and click to open its solution property page.
  • Click solution deploy link and click OK in the resulting page.
  • Browse our sharepoint site
  • Go to Site Action-> Site settings -> Site feature
  • Activate Simplefeature

Now you can see a custom list named ‘Mylist’ is created in your site.

Setting a custom 404 error page for SharePoint

In this article we will see how to set a custom error 404 (page not found) error page for SharePoint.

  1. Log on the sharepoint server and access the language folder in layout of IIS (% systemdrive%\Program Files\Common Files\Microsoft Shared\Web Server Extensions\12\TEMPLATE\LAYOUTS\LangID)
    Note: In this path, LangID represents the actual Locale ID of the language that you use. For example, 1033 is the language ID for U.S. English.
  2. Rename the error.html file to error.old.
  3. Create the custom HTML file (pagenotfound.html) and copy it to above folder.
  4. Create a console
  5. application / PowerShell script for assigning the new custom error page for your web application and run / execute it in SharePoint server

C# code for console application

[sourcecode language="csharp"]
Microsoft.SharePoint.Administration.SPWebApplication webapp =
Microsoft.SharePoint.Administration.SPWebApplication.Lookup(new Uri("http://"));
webapp.FileNotFoundPage = "pagenotfound.html";
webapp.Update();
[/sourcecode]

PowerShell code

[sourcecode language="powershell"]
$webapp = [Microsoft.SharePoint.Administration.SPWebApplication]::Lookup("http://")
$webapp.FileNotFoundPage = "pagenotfound.html"
$webapp.Update()
[/sourcecode]

Note: By default, in Internet Explorer, the Show friendly HTTP error messages setting is turned on and the custom error page may not appear. In this case turn off this setting and try.

Read data from a content editor webpart

In this article we will see how we can to get data from a content editor webpart from one page and display it in another page using a custom webpart.

If you are new to webpart development you can check out my previous post about Hello world SharePoint Web Part for Beginners
Add the following code in the RenderWebPartmethod of the webpart you are creating. The code and comments are self explanatory. Please pose a comment if you have any problem in understanding the code.

[sourcecode language="csharp"]
SPSite site = new SPSite(“http://mysite”>http://mysite”); // create object of the site
SPWeb web;
Microsoft.SharePoint.WebPartPages.SPLimitedWebPartManager mgr = null;
web = site.OpenWeb();
mgr = web.GetLimitedWebPartManager(“Pages/mypage.aspx”, System.Web.UI.WebControls.WebParts.PersonalizationScope.User);//http://mysite/Pages/mypage.aspx will be the URL of the source page
foreach (System.Web.UI.WebControls.WebParts.WebPart wp in mgr.WebParts)
{
if (wp.Title ==  “My RichTextEditor”) //My RichTextEditor is the webpart title
{
SPWebPartPages.ContentEditorWebPart webPart =    (SPWebPartPages.ContentEditorWebPart)wp;
output.Write(webPart.Content.InnerText);
}
}

[/sourcecode]

3 ways to edit SharePoint page properties

Here comes another post in the series of “3 ways to do….”. Here is how you can edit the properties of a page in Sharepoint

using browser

1. Go to the pages library of the site.
2. Click Checkout menu of the page
3. Click property menu of the page
4. Edit property and save
5. Finally checkin that page
using Object model

[sourcecode language="csharp"]
SPSite site = new SPSite("http://mysite");
SPWeb web = site.OpenWeb();
SPFile file = web.GetFile("./pages/default.aspx");
file.CheckOut();
file.Item["Title"] = "new title";
file.Item.Update();
file.CheckIn("title edited");
[/sourcecode]

using PowerShell

[sourcecode language="powershell"]
[system.reflection.assembly]::loadwithpartialname("microsoft.sharepoint")
$site= New-Object Microsoft.SharePoint.SPSite ("http://mysite")
$web=$site.OpenWeb()
$page =  $web.GetFile("./Pages/default.aspx")
$page.CheckOut()
$page.Item["Title"] = "new title"
$page.item.update()
$page.CheckIn("title edited")
[/sourcecode]

Hide a required field in SharePoint list while adding new item

There may be cases when we need to a hide required field while adding a new item to a list but at the same time you may want to show it while editing the item.

The above case looks tricky but it is easily achievable using some extra bit of code or PowerShell

C#

[sourcecode language="csharp"]
string siteUrl = "http://mysite";
SPSite site = new SPSite(siteUrl);
SPWeb web = site.OpenWeb();
site.AllowUnsafeUpdates = true;
web.AllowUnsafeUpdates = true;
SPList list = web.Lists["mylist"];
SPField fldName = list.Fields["Name"];
fldName.ShowInNewForm = false;
fldName.Update();
list.Update();
[/sourcecode]

PowerShell

[sourcecode language="powershell"]
[system.reflection.assembly]::loadwithpartialname("microsoft.sharepoint")
$site= New-Object Microsoft.SharePoint.SPSite ("http://d-dev1:1234/gp")
$web=$site.OpenWeb()
$list=$web.Lists["mylist"]
$field = $list.Fields["Name"]
$field.ShowInNewForm = $false
$field.Update()
[/sourcecode]

If you want to hide this field in edit form, you can use below command

[sourcecode language="csharp"]
fldName.ShowInEditForm = false;
[/sourcecode]

If you want to hide this field in display form, you can use below command

[sourcecode language="csharp"]
fldName.ShowInDisplayForm = false;
[/sourcecode]

If you want to hide this field in list settings, you can use below command

[sourcecode language="csharp"]
fldName.ShowInListSettings = false;
[/sourcecode]

If it is not a required filed then you can hide the item using Jquery in client side.

[sourcecode language="Javascript"]
<script type="text/javascript">// <![CDATA[
$(document).ready(function() { $('nobr:contains("Name")').closest('tr').hide(); });
// ]]></script>
[/sourcecode]

3 ways for adding new column in SharePoint list

In this post we will see 3 different methods for adding columns in SharePoint list or document library or discussion board.

using browser
Go to the list which you want to add column
On the page that displays the list, click list’s settings and create columns.
Type a name for the column, choose the column type and click OK.

using Object model

[sourcecode language="csharp"]

SPSite site = new SPSite(siteUrl);
SPWeb web = site.OpenWeb();

site.AllowUnsafeUpdates = true;
web.AllowUnsafeUpdates = true;

SPList list = web.Lists["mylist"];
SPFieldText fldName = (SPFieldText)list.Fields.CreateNewField(SPFieldType.Text.ToString(), "mycolumn");
fldName.Required = true;
fldName.MaxLength = 50;
list.Fields.Add(fldName);
list.Update();

site.AllowUnsafeUpdates = false;
web.AllowUnsafeUpdates = false;
[/sourcecode]

using PowerShell

[sourcecode language="powershell"]

[system.reflection.assembly]::loadwithpartialname("microsoft.sharepoint")
$site= New-Object Microsoft.SharePoint.SPSite ("http://mysite")
$web=$site.OpenWeb()
$list=$web.Lists["mylist"]
$list.Fields.Add("mycolumn", "Text", 0)
[/sourcecode]

3 ways to find SharePoint list field’s Internal name

Update: If you want a quicker solution, please check out my new CAML Viewer Web Part for SharePoint 2010.

While working with caml query there may be cases where we may need to refer internal name of a sharepoint list and in some of the cases the display name and internal name may be different. If you try to access this list we will get object not found error.

We can find out the sharepoint field’s internal name using any of the following ways
1. Using browser (it applies to custom fields only)
Go to list settings -> Edit column. Then you can see field name from the query string

2. Object model (it applies for custom fields as well as system fields)

[sourcecode language="csharp"]
string siteUrl = "http://mysite";
SPSite site = new SPSite(siteUrl);
SPWeb web = site.OpenWeb();
SPList list = web.Lists["my forum"];
for (int i = 0; i < list.Fields.Count; i++)
Console.WriteLine(list.Fields[i].Title + "…" + list.Fields[i].InternalName + "…");
Console.ReadLine();
[/sourcecode]

3. Powershell (it applies for custom fields as well as system fields)

[sourcecode language="powershell"]
[system.reflection.assembly]::loadwithpartialname("microsoft.sharepoint")
$site= New-Object Microsoft.SharePoint.SPSite ("http://mysite")
$web=$site.OpenWeb()
$list=$web.Lists["my forum"]
$list.Fields |select title, internalname| more
[/sourcecode]