AJAX in MOSS 2007




These days implementing AJAX in sharepoint has become a important request for share point applications.

Here i'm explaining how to create and deploy a AJnAX webpart in step by step manner...


Step 1:

Download and Install MS AJAX Extension for ASP.NET 2.0 from http://www.microsoft.com/downloads/details.aspx?FamilyID=ca9d90fa-e8c9-42e3-aa19-08e2c027f5d6&displaylang=en .

Step 2: Modify web.config file as mentioned in Web.config Changes

Step 3: Download AJAX tool kit from http://www.asp.net/ajax/downloads and install the same

Step 4: Move AjaxControlToolkit.dll to GAC from downloaded file in step 3

Step 5: Create a folder called AjaxWebSerivce under "_/layouts" directory and create a .asmx web service where in we could interact with the MOSS site to add\update\delete Sharepoint data.

Your asmx code may look like below...below code reads the value of "Title" column from
"AjaxDemoCustomList"

<%@ WebService Language="C#" Class="ReadDataFromList" %>

using System;
using System.Collections;
using System.Web;
using System.Web.Services;
using System.Web.Script.Services;
using System.Web.Services.Protocols;

[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
[ScriptService]
public class ReadDataFromList : System.Web.Services.WebService
{
[WebMethod]
public string[] GetListData(string prefixText, int count)
{
try
{
string siteURL = "http://mosssvr-ranjith:8091/SiteDirectory/AJAXDemo/default.aspx";
string msListName = "AJAXDemoCustomList";
string sTitleColumn = "Title";

Microsoft.SharePoint.SPSite spSite = new Microsoft.SharePoint.SPSite(siteURL);
Microsoft.SharePoint.SPWeb spWeb = spSite.OpenWeb();
Microsoft.SharePoint.SPList spList = spWeb.Lists[msListName];
Microsoft.SharePoint.SPQuery spQuery = new Microsoft.SharePoint.SPQuery();
spQuery.Query = string.Format("{1}",sTitleColumn, prefixText);
Microsoft.SharePoint.SPListItemCollection spItems = spList.GetItems(spQuery);

System.Collections.ArrayList items = new System.Collections.ArrayList(spItems.Count);

foreach (Microsoft.SharePoint.SPListItem spListItem in spItems)
items.Add(spListItem[sTitleColumn].ToString());

spWeb.Dispose();
spSite.Dispose();

return (string[])items.ToArray(typeof(string));
}
catch(Exception ex)
{
System.Collections.ArrayList items = new System.Collections.ArrayList(1);
items.Add(ex.Message);
return (string[])items.ToArray(typeof(string));
}
}
}



Note : You could r
eplace your SiteURL, List Name and Column Name in above asmx file, like

string siteURL = "http://yoursite
/AJAXDemo/default.aspx";
string msListName = "AJAXDemoCustomList";
string sTitleColumn = "ColumnName";

Step 6: Create a web part to read a list a show the data by using AJAX controls. This web part will interact with the above webservice through the AJAXToolKit ajax control. So All we need to do is just create a AJAXToolKit control , Map it with the above web service and display the data resultant data.



using System;
using System.Runtime.InteropServices;
using System.Web.UI;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Serialization;
using AjaxControlToolkit;
using Microsoft.SharePoint;
using Microsoft.SharePoint.WebControls;
using Microsoft.SharePoint.WebPartPages;
using System.Configuration;
using System.Collections.Specialized;
using System.Web.UI.WebControls;
namespace AJAXAutoCompleteDemo
{
[Guid("e8b6db14-c3c3-48f5-8301-b6f2e3fe0583")]
public class AJAXAutoCompleteDemo : System.Web.UI.WebControls.WebParts.WebPart
{

Exception meExp = null;
TextBox oTextBox = null;
AutoCompleteExtender oAutoCompleteExtender = null;
ScriptManager oScriptManager = null;

private string msAJAXWebServicePath = "_layouts/AjaxWebSerivce/ReadDataFromList.asmx";
private string msWebServiceMethodName = "GetListData";

public AJAXAutoCompleteDemo()
{
EnsureChildControls();
this.Title = "AJAXAutoCompleteDemo";
this.ExportMode = WebPartExportMode.All;
}


protected override void CreateChildControls()
{
try
{
base.CreateChildControls();
//
oScriptManager = new ScriptManager();
oScriptManager.ID = "oScriptManagerId";
oScriptManager.EnablePageMethods = true;
this.Controls.Add(oScriptManager);
//
oTextBox = new TextBox();
oTextBox.ID = "IdTestTextBox";
oTextBox.Width = new Unit("250px");
oTextBox.AutoCompleteType = AutoCompleteType.Disabled;
this.Controls.Add(oTextBox);

}
catch (Exception ex)
{
meExp = ex;
}
}

protected override void OnPreRender(EventArgs e)
{
try
{
oAutoCompleteExtender = new AutoCompleteExtender();
oAutoCompleteExtender.ID = "oAutoCompleteExtenderId";
oAutoCompleteExtender.TargetControlID = "IdTestTextBox";
oAutoCompleteExtender.ServiceMethod = msWebServiceMethodName;
oAutoCompleteExtender.ServicePath = msAJAXWebServicePath;
oAutoCompleteExtender.MinimumPrefixLength = 1;
oAutoCompleteExtender.EnableCaching = true;
oAutoCompleteExtender.CompletionSetCount = 12;
oAutoCompleteExtender.CompletionInterval = 2000;
this.Controls.Add(oAutoCompleteExtender);
}
catch (Exception ex)
{
meExp = ex;
}
}

protected override void Render(System.Web.UI.HtmlTextWriter output)
{
try
{
if (meExp != null)
{
renderException(output, meExp);
return;
}
//
EnsureChildControls();
output.Write("Enter the first letter of any state : ");
oScriptManager.RenderControl(output);
oTextBox.RenderControl(output);
oAutoCompleteExtender.RenderControl(output);
output.Write("");
output.Write("


");

}
catch (Exception ex)
{
renderException(output, ex);
}
}

private void renderException(HtmlTextWriter output, Exception e)
{
output.Write(string.Format("Message: {0}
Source: {1}
Stack Trace: {2}", e.Message, e.Source, e.StackTrace));

}
}
}


You web part should also have script manager control (if its no there in the master page), like below...


oScriptManager = new ScriptManager();
oScriptManager.ID = "oScriptManagerId";
oScriptManager.EnablePageMethods = true;
this.Controls.Add(oScriptManager);

Step 7: Deploy the webpart and Do iisreset



Now your web part will show the auto complete drop down with ajax interface.


If you type a first letter of field column value that you gave in the Step 6, it will fetch the all record for that first letter and will populate in auto complete drop down box.

For example in your list if you have stored all 49 states and if you type “N” in the text box, it will populate auto complete dropdown with “NewYork”,”NewJersey”, etc

Note: Please don’t forget to replace your sitename, listname and column name as mentioned in step 5.

Avoid recursive updates in event handler


I wrote a ItemUpdated event for a custom List (lets assume the list name is mylist) and my custom ItemUpdated event again updating a field value of the same mylist.

In this scenario the ItemUpdate event is getting triggered again and again (i don't remember how many times:)), as we call the update method for the same list inside the event handler(i have given below the code)


Code that updates list recursively in ItemUpdated Event


public override void ItemUpdated(SPItemEventProperties properties)
{
using (spWeb = properties.OpenWeb())
{
spWeb.AllowUnsafeUpdates = true;
properties.ListItem["MyColumnName"] = "NewValueToUpdate";
properties.ListItem.SystemUpdate(false);
spWeb.AllowUnsafeUpdates = false;
}
}



To Avoid this recursive call, eventhanler has DisableEventFiring() method before the Update method is getting called and pls dont forget to call EnableEventFiring() method after the Update.


Corrected Code which will not call ItemUpdated event recurcively


public override void ItemUpdated(SPItemEventProperties properties)
{
using (spWeb = properties.OpenWeb())
{
spWeb.AllowUnsafeUpdates = true;
//
this.DisableEventFiring();
//
properties.ListItem["MyColumnName"] = "NewValueToUpdate";
properties.ListItem.SystemUpdate(false);
//
this.EnableEventFiring();
spWeb.AllowUnsafeUpdates = false;
}
}






Update Vs SystemUpdate

Many of you might noticed that share point ListItem has Update() method as well as SystemUpdate().

What is the difference between these two methods and why MOSS has two different APIs for updating an ListItem ?


ListItem.Update() will....

  • Creates new version automatically for each and every update
  • Updates the Modifer field details with SystemAccount


ListItem.SystemUpdate()

  • Don't create new version for updates
  • Updates the Modifer field details with the user details who updates the ListItem

Master Pages in MOSS 2007

Master Pages in MOSS 2007

'MasterPages' feature in sharepoint 2007 makes the entire customization job easy.In 2003 we used to face lot of issues to get the same look and feel and the standard behaviour for overall site. In 2007, customizing the look and feel for the entire site can be done in a simple way by using 'MasterPage' feature.

'Master Page' concept has come from .Net framework 2.0, Its been used in Asp.Net 2.0. Basically a 'MasterPage' is a Asp.Net file with an extension '.master'. 'Master Page' will have a predefined layouts and that can be inherited throughout the site.So to modify the look and feel of the entier site, you can modify the master page and that will refelect the whole site. In SPS 2007 pages will be rendered with the combination of 'MasterPages', 'PageLayouts' and 'The content Type'.

Page Layouts are templates with the definetion of the content structure to dsiplay, usually page layouts are associated with the content types(Click here for Content Types).

Creating a custom Master Page

Go to Templates->Global, copy and paste the default.master, name the new master page as 'MySpace.Master'

Now open the 'MySpace.Master' in your favouite Asp.Net ide and do the required changes.


Note: I have changed the backgound color, alignment and width of the default master page.

Adding the Custom Master Page in Master Page Gallery

Once the new master page is created we need to add it in the master page gallery to apply it for all the pages.

Go to 'SiteActions' -> 'SiteSettings' -> 'Galleries' -> 'Master Pages'


In gallaries page click upload to Upload the custom master page




Once the mastre page is uploaded you should see it in gallaries list...

Applying the Custom Master Page for Sites

To apply the custom master page, we need activate 'Office SharePoint Server Publishing Infrastructure' feature so that we will get the 'Master Pages' link under 'Look and Feel' section of site settings page.This 'Master Page' will let administrator to change the master pages.

To activate 'Office SharePoint Server Publishing Infrastructure' , go to 'SiteActions -> Site Settings' -> and click 'Site Collection features' link

In site collection feature page activate the 'Office SharePoint Server Publishing Infrastructure'

once its activated you must see 'Master Pages' link under 'Look and Feel' Section

Now clikc 'Master Pages' link to apply the new master page for the entier site, In 'site master page settings' page select the custom master pages for both the 'System' and 'Site' master pages(as given below) and you should be able to see the modifed changes throught the site.

There are two types of master pages used in sharepoint 2007.They are 'Site Master Page' and 'System Master Page'

Site Master Pages are used for all publishing pages

System Master Pages are used for forms and views within the site

Finally the application with the custom master page will look like...









Site Columns in MOSS 2007

Site Columns in MOSS 2007

Site Column is one of the coolest featuer in MOSS 2007. Simply Site Column is a Custom Column which can be used/added in any list/content type across the site.

For example we can create a custom site column 'Manager Code' and can inherit it in any list/content type of the entier site.

Steps to create new site Column:

# 1 : Go to Site actions -> site Settings and click Site Columns under Galleries

#2 : click Create in Site Column Gallery

#3 : In New Site Column screen enter the Column Name, Type , Group(I have created new group here) and Description. (if you give the exsisting or reserved column name you will get 'The column name that you entered is already in use or reserved. Choose another name.' error).




# 4 : Now is new site coulmn 'ManagerCode' has been created , you should see it in 'Site Column Gallery' page under 'MySiteColumns'.




Steps to Use the new site Columns:

# 1 : Once Custom site columns are created, its ready to use in Content Type/Lists.

For Lists (or for content types go to Site Actions->Site Settings->Site Content Types(under gallery)->Content Type) , click 'Add from new site column' link under Columns section in settings page

# 2 : In 'Add Columns to Site Content Type' select the coulmn group name & column name and add to the selected columns to 'columns to add' section and click ok

Now you should be able to see the custom site column under the columns section of List/Content types.






Content Types in MOSS 2007


Content Types in MOSS 2007



In this article I will try to describe the one of the best feature in Microsoft office Share Point 2007 called Content Types.

Content types are simply collection of contents.Each content in a Content type can have different settings.Basically it is a reusable collection of settings which you want to apply to a particular category of contents.

Simply, We can map different content types(with different settings or templates or metadata) to a document library and create new/upload documents in any one of the content type.

Usually content types inherit its parent content type settings. There are four parent content types they are Document, Folder, Lists and Special.

Let me explain this feature and advantages of Contet Type with an example.

Assume that we need to create document library for following two different documents with the respective custom column and template...


Document Type 1: “Employee Severance Policy” with metadata Business Group

Document Type 2: “Contingent Worker Expense” with metadata “Region .

In this scenario in SPS 2003 we are forced to create two different document libraries for above documents as their metadata and the template is different. But in MOSS 2007 its not required to have two different document libraries as we could able to store in a same document library by using Content Types feature.




Creating Content Type for “Employee Severance Policy”



Let me create a Content Type for “Employee Severance Policy” and “Contingent Worker Expense” documents.

From Main Page Go to SiteActions -> SiteSettings ->

Clik ‘SiteContentType’ (Under Galleries Section)


Click Create new in site content type gallery…



Enter the new content type Name ,Description and Group. I have selected the new group option and created a new group called ‘Employee Severance Policy ’।

Now clik ok, so the new content type will be created like below…



Now clik ‘Add from new site column’ link under column section to add a new Drop Down column called ‘Business Group’ with the different values like ‘Trade’, ‘Finance’ , ‘Marketing’ , ect.




Click ‘OK’ button to create the new column and it will be under Columns section of ‘Employee Severance Policy’s site content type page…




Click ‘Advanced Settings’ link under Settings section of ‘Employee Severance Policy’s site content type page




In advanced settings page upload the document template file for Employee Severance Policy and click ok…


Finally the new Content Type for ‘Employee Severance Policy’ is created with custom column called ‘Business Group

Creating Content Type for “Contingent Worker Expense”

Next I’m going to create a Content Type for ‘Contingent Worker Expense’ templates with a custom column called ‘Region


Click Create new in site content type gallery…




Enter the new content type Name ,Description and Group. I have selected the new group option and created a new group called ‘Contingent Worker Expense’।

Now clik ok, so the new content type will be created like below…



Now clik ‘Add from new site column’ link under column section to add a new Drop Down column called ‘Region’ with the different values like ‘Canada’, ‘India’ , ‘UK’ ,’US’, ect.




The new column will be created after ‘OK’ click. It will be displayed under Columns section of ‘Contingent Worker Expense’s site content type page…




Click ‘Advanced Settings’ link under Settings section of ‘Contingent Worker Expense’s site content type page




In advanced settings page upload the document template file for Contingent Worker Expense and click ok…


Finally the new Content Type for ‘Contingent Worker Expense’ is created with custom column called ‘Region

Creating Document Library ‘CorpDocLib’, Assigning Content TypesEmployee Severance Policyand Contingent Worker Expensefor ‘CorpDocLib’.

Frist Lets Create a documents library called ‘CorpDocLib’ and Assign the new ‘Content Types’ for ‘CropDocLib’ document library



Go to Setting-> Document Library Settings of ‘CorpDocLib’




In CropDocLib’s Settings screen click Advanced Setting under General Settings section




In Advanced Settings page, select ‘Allow Management of content types?’ as ‘Yes and click ‘Ok’ button….




Now we will be able to see the new section called ‘Content Types’ next to ‘General Settings’ section in setting page of ‘CorpDocLib





Once the content type section is added, we could be able to assign the content types for the documents library.



= o ns = "urn:schemas-microsoft-com:office:office" />


Now click ‘Add from existing site content types’ under ‘Content Types’ section of ‘CropDocLib’s settings page.



In Add content types page select ‘Employee Severance Policy’ and ‘Contingent Worker Expense’ and click add button to get under ‘content types to add’



Now click ‘Ok’ button…



Now both the content types (‘Employee Severance Policy’ and ‘Contingent Worker Expense’) should be under ‘Content Types’ Section and both the custom columns( ‘Business Group’ and ‘Region’) should be under ‘Columns’ section।

Uploading Documents for Content Types ‘Employee Severance Policy’ and ‘Contingent Worker Expense’ in ‘CropDocLib’ document library।

Go to ‘CorpDocLib’ document library , Click ‘Upload’ -> ‘UploadDocument’ , browse the document to be uploaded and click ok



Now we will get the ‘edit item’ screen where in we will be asked to select the content type for the uploaded document with an warning message ‘The document was uploaded successfully. Use this form to update the properties of the document.



Select the content type ‘Contingent Worker Expense’ for the uploaded document



Now we be able to see the custom field ‘Region’ which we have added for ‘Contingent Worker Expense’ content type.




Select a value for custom field ‘Region’and click ok.


= o ns = "urn:schemas-microsoft-com:office:office" />

Repeat the same for ‘Employee Severance Policy’ (upload a new Employee Severance Policy document, select the value for custom field ‘Business Groups’ and click ok)



Now the document library ‘CropDocLib’ has two documents with two different templates assigned to it…।