Search This Blog

Loading...

2011-02-24

Create a List event receiver feature

Step 1-Create a class library project "EventReceiverFeature" and add reference the dll as follows-


Step 2-Create a custom list "EventReceiverList" and a Column "Company" (Single line of text)

Step 3-Feature.xml will be as follows-
<Feature xmlns="http://schemas.microsoft.com/sharepoint/"
Id="82540374-276A-458b-BB6C-B605D35E8DD6"
Title="List Event Receiver Feature"
Description="This is my Event Receiver feature"
Hidden="false"
Scope="Web"
ImageUrl="menuprofile.gif"
ReceiverClass="EventReceiverFeature.FeatureReceiver"
ReceiverAssembly="EventReceiverFeature, Version=1.0.0.0, Culture=neutral, PublicKeyToken=30534ee939de1c1d"
>
</Feature>

Step 4-"FeatureReceiver.cs" will be as follows-
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.SharePoint;

namespace EventReceiverFeature
{
class FeatureReceiver : SPFeatureReceiver
{
public override void FeatureActivated(SPFeatureReceiverProperties properties)
{


// access SPSite object for current site collection
// SPSite siteCollection = (SPSite)properties.Feature.Parent;
SPWeb web = (SPWeb)properties.Feature.Parent;
SPList lstVendors = web.Lists["EventReceiverList"];
// add event handlers to vendors list
string asmName = "EventReceiverFeature, Version=1.0.0.0, Culture=neutral, PublicKeyToken=30534ee939de1c1d";
string itemReceiverName = "EventReceiverFeature.ListItemEventReceiver";

// add event receiver to fire before existing item is deleted
lstVendors.EventReceivers.Add(SPEventReceiverType.ItemAdded,
asmName,
itemReceiverName);

// add event receiver to fire before existing item is deleted
lstVendors.EventReceivers.Add(SPEventReceiverType.ItemUpdated,
asmName,
itemReceiverName);


}

public override void FeatureDeactivating(SPFeatureReceiverProperties properties)
{
string asmName = "EventReceiverFeature, Version=1.0.0.0, Culture=neutral, PublicKeyToken=30534ee939de1c1d";

using (SPWeb web = (SPWeb)properties.Feature.Parent)
{
SPDocumentLibrary proposals = (SPDocumentLibrary)web.Lists["EventReceiverList"];
SPEventReceiverDefinitionCollection erdc = proposals.EventReceivers;
SPEventReceiverDefinition erd = null;
bool found = false;

for (int i = 0; i < erdc.Count; ++i)
{
erd = erdc[i];
if (erd.Assembly == asmName && ((erd.Type == SPEventReceiverType.ItemAdded)||(erd.Type==SPEventReceiverType.ItemUpdated)))
{
found = true;
break;
}
} if (found)
erd.Delete();
}


}

public override void FeatureInstalled(SPFeatureReceiverProperties properties)
{
//throw new NotImplementedException();
}

public override void FeatureUninstalling(SPFeatureReceiverProperties properties)
{
// throw new NotImplementedException();
}
}
}

Step 5-"ListItemEventReceiver.cs" will be as foll0ws-
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.SharePoint;

namespace EventReceiverFeature
{
public class ListItemEventReceiver:SPItemEventReceiver
{
private string FormatCompanyName(string value)
{
return value.ToUpper();
}
public override void ItemAdded(SPItemEventProperties properties)
{
UpperFormat(properties);
}
public override void ItemUpdated(SPItemEventProperties properties)
{
UpperFormat(properties);
}
public void UpperFormat(SPItemEventProperties properties)
{
DisableEventFiring();
//SPListItemCollection col=SPContext.Current.Web.Lists[properties.ListTitle].Items.Count
//(SPSite(properties.SiteId).OpenWeb(properties.lists.RelativeWebUrl))

//for (int i = 0; i < SPContext.Current.Web.Lists[properties.ListTitle].Items.Count; i++)
//{
// properties.ListItem[i] = FormatCompanyName(properties.ListItem[i+1].ToString());
// properties.ListItem.Update();
//}
string CompanyName = properties.ListItem["Company"].ToString();
properties.ListItem["Company"] = FormatCompanyName(CompanyName);
properties.ListItem.Update();
EnableEventFiring();

}
}
}

Step 6-Copy the dll to the GAC

Step 7-Copy the EventReceiverFeature to the feature folder and activate the feature-

Step 8-Now add New Item to your list in Any case(Upper/Lower) and click OK


Step 9-The output will be as follows-

Create a custom Field in Sharepoint 2007

Step 1-Create a class libary Project "CustomField_TelephoneNumber"

Step 2--Create the folder structure and add reference as follows-


Step 3-"TelephoneFieldControl.ascx" will be as follows-

<%@ Control Language="C#" Debug="true" %>
<%@ Assembly Name="Microsoft.SharePoint, Version=12.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c" %>
<%@ Register TagPrefix="SharePoint" Assembly="Microsoft.SharePoint, Version=12.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c"
Namespace="Microsoft.SharePoint.WebControls" %>
<SharePoint:RenderingTemplate ID="TelephoneFieldControl" runat="server">
<Template>

<script language="javascript">
<!-- This script is based on the javascript code of Roman Feldblum (web.developer@programmer.net) -->
<!-- Original script : http://javascript.internet.com/forms/format-phone-number.html -->
<!-- Original script is revised by Eralper Yilmaz (http://www.eralper.com) -->
<!-- Revised script : http://www.kodyaz.com -->

var zChar = new Array(' ', '(', ')', '-', '.');
var maxphonelength = 13;
var phonevalue1;
var phonevalue2;
var cursorposition;

function ParseForNumber1(object){
phonevalue1 = ParseChar(object.value, zChar);
}

function ParseForNumber2(object){
phonevalue2 = ParseChar(object.value, zChar);
}

function backspacerUP(object,e) {
if(e){
e = e
} else {
e = window.event
}

if(e.which){
var keycode = e.which
} else {
var keycode = e.keyCode
}

ParseForNumber1(object)
if(keycode > 48){
ValidatePhone(object)
}
}


function backspacerDOWN(object,e) {
if(e){
e = e
} else {
e = window.event
}

if(e.which){
var keycode = e.which
} else {
var keycode = e.keyCode
}

ParseForNumber2(object)
}

function GetCursorPosition(){
var t1 = phonevalue1;
var t2 = phonevalue2;
var bool = false
for (i=0; i<t1.length; i++)
{
if (t1.substring(i,1) != t2.substring(i,1)) {
if(!bool) {
cursorposition=i
bool=true
}
}
}
}


function ValidatePhone(object){



var p = phonevalue1



p = p.replace(/[^\d]*/gi,"")



if (p.length < 3) {

object.value=p

} else if(p.length==3){

pp=p;

d4=p.indexOf('(')

d5=p.indexOf(')')

if(d4==-1){

pp="("+pp;

}

if(d5==-1){

pp=pp+")";

}

object.value = pp;

} else if(p.length>3 && p.length < 7){

p ="(" + p;

l30=p.length;

p30=p.substring(0,4);

p30=p30+")"



p31=p.substring(4,l30);

pp=p30+p31;



object.value = pp;



} else if(p.length >= 7){

p ="(" + p;

l30=p.length;

p30=p.substring(0,4);

p30=p30+")"



p31=p.substring(4,l30);

pp=p30+p31;



l40 = pp.length;

p40 = pp.substring(0,8);

p40 = p40 + "-"



p41 = pp.substring(8,l40);

ppp = p40 + p41;



object.value = ppp.substring(0, maxphonelength);

}



GetCursorPosition()



if(cursorposition >= 0){

if (cursorposition == 0) {

cursorposition = 2

} else if (cursorposition <= 2) {

cursorposition = cursorposition + 1

} else if (cursorposition <= 5) {

cursorposition = cursorposition + 2

} else if (cursorposition == 6) {

cursorposition = cursorposition + 2

} else if (cursorposition == 7) {

cursorposition = cursorposition + 4

e1=object.value.indexOf(')')

e2=object.value.indexOf('-')

if (e1>-1 && e2>-1){

if (e2-e1 == 4) {

cursorposition = cursorposition - 1

}

}

} else if (cursorposition < 11) {

cursorposition = cursorposition + 3

} else if (cursorposition == 11) {

cursorposition = cursorposition + 1

} else if (cursorposition >= 12) {

cursorposition = cursorposition

}



var txtRange = object.createTextRange();

txtRange.moveStart( "character", cursorposition);

txtRange.moveEnd( "character", cursorposition - object.value.length);

txtRange.select();

}



}



function ParseChar(sStr, sChar)

{

if (sChar.length == null)

{

zChar = new Array(sChar);

}

else zChar = sChar;



for (i=0; i<zChar.length; i++)

{

sNewStr = "";



var iStart = 0;

var iEnd = sStr.indexOf(sChar[i]);



while (iEnd != -1)

{

sNewStr += sStr.substring(iStart, iEnd);

iStart = iEnd + 1;

iEnd = sStr.indexOf(sChar[i], iStart);

}

sNewStr += sStr.substring(sStr.lastIndexOf(sChar[i]) + 1, sStr.length);



sStr = sNewStr;

}



return sNewStr;

}

</script>

<asp:TextBox ID="txtNumber" runat="server" MaxLength="15" Size="20" onkeydown="javascript:backspacerDOWN(this,event);"
onkeyup="javascript:backspacerUP(this,event);" />
</Template>
</SharePoint:RenderingTemplate>


Step 4-"FLDTYPES_Telephone.xml" will be as follows-

<?xml version="1.0" encoding="utf-8"?>
<FieldTypes>
<FieldType>
<Field Name="TypeName">PhoneNumber</Field>
<Field Name="ParentType">Text</Field>
<Field Name="TypeDisplayName">Phone Number</Field>
<Field Name="TypeShortDescription">Phone Number</Field>
<Field Name="UserCreatable">TRUE</Field>
<Field Name="ShowInListCreate">TRUE</Field>
<Field Name="ShowInSurveyCreate">TRUE</Field>
<Field Name="ShowInDocumentLibraryCreate">TRUE</Field>
<Field Name="ShowInColumnTemplateCreate">TRUE</Field>
<Field Name="FieldTypeClass">CustomField_TelephoneNumber.TelephoneField,CustomField_TelephoneNumber, Version=1.0.0.0, Culture=neutral, PublicKeyToken=30534ee939de1c1d</Field>
<!-- We will implement this later to add display formating for the fields value. ie (xxx)xxx-xxxx
<RenderPattern Name="DisplayPattern">
<Switch>
<Expr>
<Column />
</Expr>
<Case Value="" />
<Default>
<HTML><![CDATA[^]]></HTML>
<Column HTMLEncode="TRUE" />
</Default>
</Switch>
</RenderPattern>
-->
</FieldType>
</FieldTypes>


Step 5-"TelephoneField.cs" will be as follows-

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.SharePoint;
using System.Text.RegularExpressions;

namespace CustomField_TelephoneNumber
{
//Should inherit from an existing SPField class
public class TelephoneField : SPFieldText
{
#region Contstructors
public TelephoneField(SPFieldCollection fields, string fieldName)
: base(fields, fieldName)
{

}
public TelephoneField(Microsoft.SharePoint.SPFieldCollection fields, string typeName, string displayName)
: base(fields, typeName, displayName)
{

}

#endregion

public override Microsoft.SharePoint.WebControls.BaseFieldControl FieldRenderingControl
{
get
{
Microsoft.SharePoint.WebControls.BaseFieldControl phoneNumberFieldControl = new TelephoneFieldControl();
phoneNumberFieldControl.FieldName = InternalName;
return phoneNumberFieldControl;
}
}
/// <summary>
/// This method validates the data as it is entered into the column. If it doesnt match the criteria a sharepoint exception is thrown.
/// </summary>
/// <param name="value"></param>
/// <returns></returns>
public override string GetValidatedString(object value)
{
string myVal = value as string;
if (myVal == null)
return String.Empty;

//Strip formating characters from the value..
myVal = myVal.Replace("(", "");
myVal = myVal.Replace(")", "");
myVal = myVal.Replace("-", "");
myVal = myVal.Replace("+", "");
myVal = myVal.Replace(" ", "");
myVal = myVal.Trim();

//Use regex to makes the string only contains numbers and is within the correct range.
Regex foo = new Regex("^\\d{10,11}$");
if (foo.IsMatch(myVal))
{

}

else
{
throw new Microsoft.SharePoint.SPFieldValidationException("The Telephone number field must contain only numbers, (, ), -, or + characters. It must also be between 10 and 11 digits. val:" + myVal);
}
return myVal;
}
/// <summary>
/// Here we can apply formating to our number that will show up on the edit page.
/// </summary>
/// <param name="value"></param>
/// <returns></returns>
public override object GetFieldValue(string value)
{
if (String.IsNullOrEmpty(value))
return null;
//TODO - Format the phone number here (XXX)XXX-XXXX
return value;
}
}
}


Step 6-"TelephoneFieldControl.cs" will be as follows-

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web.UI.WebControls;
using Microsoft.SharePoint.WebControls;
//http://www.sharethispoint.com/archive/2006/08/07/23.aspx#codethree

namespace CustomField_TelephoneNumber
{
class TelephoneFieldControl : BaseFieldControl
{
protected TextBox txtNumber;
//The DefaultTemplateName property lets sharepoint know which rendering template to use this class for.
protected override string DefaultTemplateName
{
get
{
return "TelephoneFieldControl";
}
}

//The value property controls how the data that SharePoint provides gets parsed into our control
public override object Value
{
get
{
EnsureChildControls();
return txtNumber.Text.Trim();
}
set
{
EnsureChildControls();
txtNumber.Text = (string)this.ItemFieldValue;
}
}

public override void Focus()
{
EnsureChildControls();
txtNumber.Focus();
}

protected override void CreateChildControls()
{
if (Field == null) return;
base.CreateChildControls();
if (ControlMode == Microsoft.SharePoint.WebControls.SPControlMode.Display)
return;

txtNumber = (TextBox)TemplateContainer.FindControl("txtNumber");
if (txtNumber == null)
throw new ArgumentException("txtNumber is null. Corrupted TelephoneFieldControl.ascx file.");

txtNumber.TabIndex = TabIndex;
txtNumber.CssClass = CssClass;
txtNumber.ToolTip = Field.Title + " Phone Number";
}
}
}

Step 7-Attach the strong name & Copy the dll to GAC.

Step 8-Copy the files to their respective folder as folder structure in the project.

Step 9-Reset IIS

Step 10-Create a Custom list in sharepoint 2007 and add your custome field column to the list.



Step 11-Add item to your Custom List

2011-02-12

Create Custom Sitepages in Sharepoint 2007

Step 1-Create a Web Application project "CustSitePages" and a class library project "CustSitePagesClass"
Step 2-Make the folder structure as follows




Step 3-"SiteFileViewer.ascx" will be as follows-
<%@ Assembly Name="Microsoft.SharePoint, Version=12.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c" %>
<%@ Control Language="C#" %>
<%@ Register Assembly="Microsoft.SharePoint, Version=12.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c"
Namespace="Microsoft.SharePoint.WebControls" TagPrefix="SharePoint" %>
<%@ Import Namespace="Microsoft.SharePoint" %>


<script runat="server">

protected override void OnLoad(EventArgs e) {
SPWeb site = SPContext.Current.Web;
SPFolder rootFolder = site.RootFolder;
TreeNode rootNode = new TreeNode(site.Title, "", @"\_layouts\images\FPWEB16.GIF");
rootNode.NavigateUrl = site.ServerRelativeUrl;
LoadFolderNodes(rootFolder, rootNode);
treeSitesFiles.Nodes.Add(rootNode);
treeSitesFiles.ExpandDepth = 1;
}

protected void LoadFolderNodes(SPFolder folder, TreeNode folderNode) {

foreach (SPFolder childFolder in folder.SubFolders) {
TreeNode childFolderNode = new TreeNode(childFolder.Name, "", @"\_layouts\images\FOLDER16.GIF");
childFolderNode.NavigateUrl = childFolder.ServerRelativeUrl;
LoadFolderNodes(childFolder, childFolderNode);
folderNode.ChildNodes.Add(childFolderNode);
}

foreach (SPFile file in folder.Files){
TreeNode fileNode;
if (file.CustomizedPageStatus == SPCustomizedPageStatus.Uncustomized) {
fileNode = new TreeNode(file.Name, "", @"\_layouts\images\NEWDOC.GIF");
fileNode.NavigateUrl = file.ServerRelativeUrl;
}
else {
fileNode = new TreeNode(file.Name, "", @"\_layouts\images\RAT16.GIF");
fileNode.NavigateUrl = file.ServerRelativeUrl;
}
folderNode.ChildNodes.Add(fileNode);
}


}


</script>

<asp:TreeView NodeStyle-HorizontalPadding="6" ID="treeSitesFiles" runat="server" EnableViewState="false" />


Step 4-"UserControl1.ascx" will be as follows-
<%@ Control Language="C#" %>

<script runat="server">

protected void cmdAddCustomer_Click(object sender, EventArgs e) {
string msg = "Customer " + txtName.Text + " has been added.";
lblStatus.Text = msg;
}

</script>


<h4>Add New Customer</h4>
<table>
<tr>
<td>Name:</td>
<td><asp:TextBox ID="txtName" runat="server" /></td>
</tr>
<tr>
<td>Address:</td>
<td><asp:TextBox ID="txtAddress" runat="server" /></td>
</tr>
<tr>
<td>City:</td>
<td><asp:TextBox ID="txtCity" runat="server" /></td>
</tr>
<tr>
<td>
State:
</td>
<td>
<asp:TextBox ID="txtState" runat="server" />
</td>
</tr>

<tr>
<td>
Zip:
</td>
<td>
<asp:TextBox ID="txtZip" runat="server" />
</td>
</tr>


</table>

<p>
<asp:Button ID="cmdAddCustomer" runat="server" Text="Add Customer" OnClick="cmdAddCustomer_Click" />
</p>
<p>
<asp:Label ID="lblStatus" runat="server" Text="" />
</p>

Step 5-"UserControl2.ascx" will be as follows-
<%@ Control Language="C#" %>
<%@ Assembly Name="Microsoft.SharePoint, Version=12.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c" %>
<%@ Import Namespace="Microsoft.SharePoint" %>

<script runat="server">
protected override void OnLoad(EventArgs e) {
SPWeb site = SPContext.Current.Web;
lblDisplay.Text = "Current Site: " + site.Url;
}
</script>

<asp:Label ID="lblDisplay" runat="server" />


Step 6-"CustSitePages_All.aspx" will be as follows-
<%@ Page Language="C#" MasterPageFile="~masterurl/default.master" Inherits="Microsoft.SharePoint.WebPartPages.WebPartPage,Microsoft.SharePoint,Version=12.0.0.0,Culture=neutral,PublicKeyToken=71e9bce111e9429c"
meta:progid="SharePoint.WebPartPage.Document" %>

<%@ Register Assembly="CustSitePagesClass, Version=1.0.0.0, Culture=neutral, PublicKeyToken=30534ee939de1c1d"
Namespace="CustSitePagesClass" TagPrefix="CustomSitePages" %>
<%@ Register TagPrefix="luc" TagName="UserControl1" Src="~/_controltemplates/MRB/UserControl1.ascx" %>
<%@ Register TagPrefix="luc" TagName="UserControl2" Src="~/_controltemplates/MRB/UserControl2.ascx" %>
<%@ Register Assembly="Microsoft.SharePoint, Version=12.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c"
Namespace="Microsoft.SharePoint.WebControls" TagPrefix="SharePoint" %>
<%@ Register TagPrefix="WebPartPages" Namespace="Microsoft.SharePoint.WebPartPages"
Assembly="Microsoft.SharePoint, Version=12.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c" %>
<asp:Content ID="main" runat="server" ContentPlaceHolderID="PlaceHolderMain">
<table width="100%">
<tr>
<td colspan="2">
<h3>
Page 1 - Hello World</h3>
A simple page template used to create site pages
</td>
</tr>
<tr>
<td colspan="2">
<h3>
Page 2 - Server-side scripts and safe mode</h3>
<% Response.Write("Hello world from server-side script"); %>
</td>
</tr>
<tr>
<td colspan="2">
<h3>
Page 3 - Custom Control Demo</h3>
<CustomSitePages:CustSitePagesCls ID="cc1" runat="server" />
</td>
</tr>
<tr>
<td colspan="2">
<h3>
Page 4- User Control Demo</h3>
<luc:UserControl1 ID="id1" runat="server" />
<hr />
<luc:UserControl2 ID="id2" runat="server" />
</td>
</tr>
<tr>
<td colspan="2">
<h3>
Page 5- Built-in WSS Controls</h3>
<h4>
AspMenu control</h4>
<SharePoint:AspMenu ID="MyMenu" DataSourceID="SiteMapDataSource1" runat="server"
Orientation="Vertical" StaticDisplayLevels="2" MaximumDynamicDisplayLevels="1"
BorderWidth="1" StaticMenuItemStyle-BorderWidth="2" />
<asp:SiteMapDataSource ShowStartingNode="False" SiteMapProvider="SPNavigationProvider"
ID="SiteMapDataSource1" runat="server" StartingNodeUrl="sid:1002" />
<br />
<hr />
<h4>
SPTreeView control</h4>
<SharePoint:SPTreeView ID="WebTreeView" runat="server" ShowLines="true" DataSourceID="TreeViewDataSource1"
ExpandDepth="2" ShowExpandCollapse="true" ShowCheckBoxes="All" SelectedNodeStyle-CssClass="ms-tvselected"
NodeStyle-CssClass="ms-navitem" NodeStyle-HorizontalPadding="2" SkipLinkText=""
NodeIndent="12" ExpandImageUrl="/_layouts/images/tvplus.gif" CollapseImageUrl="/_layouts/images/tvminus.gif"
NoExpandImageUrl="/_layouts/images/tvblank.gif">
</SharePoint:SPTreeView>
<SharePoint:SPHierarchyDataSourceControl runat="server" ID="TreeViewDataSource1"
RootContextObject="Web" IncludeDiscussionFolders="true" ShowFolderChildren="true" />
</td>
</tr>
<tr>
<td colspan="2">
<h3>
Page 6- Custom Web Part Page</h3>
</td>
</tr>
<tr>
<td valign="top" style="width: 50%">
<WebPartPages:WebPartZone ID="Left" runat="server" FrameType="TitleBarOnly" Title="Left Web Part Zone" />
</td>
<td valign="top" style="width: 50%">
<WebPartPages:WebPartZone ID="Right" runat="server" FrameType="TitleBarOnly" Title="Right Web Part Zone" />
</td>
</tr>
</table>
</asp:Content>


Step 7-"Feature.xml" will be as follows-
<Feature
Id="EE3300F0-D4E3-4c0d-8F07-6D965F6D6D6D"
Title="My Custom Site Pages"
Description="THIS IS A EXAMPLE OF CUSTOM SITE PAGE"
Scope="Web"
Hidden="false"
ImageUrl="menuprofile.gif"
ReceiverAssembly="CustSitePagesClass, Version=1.0.0.0, Culture=neutral, PublicKeyToken=30534ee939de1c1d"
ReceiverClass="CustSitePagesClass.FeatureReceiver"
xmlns="http://schemas.microsoft.com/sharepoint/">

<ElementManifests>
<ElementManifest Location="Elements.xml"/>
</ElementManifests>

</Feature>


Step 8-"Elements.xml" will be as follows-
<Elements xmlns="http://schemas.microsoft.com/sharepoint/">

<Module Path="PageTemplates" Url="SitePages" >
<!-- provision standard pages -->

/*
<File Url="Page01.aspx" Type="Ghostable" />
<File Url="Page02.aspx" Type="Ghostable" />
<File Url="Page03.aspx" Type="Ghostable" />
<File Url="Page04.aspx" Type="Ghostable" />
<File Url="Page05.aspx" Type="Ghostable" />
<File Url="Page06.aspx" Type="Ghostable" />
<!-- provision Web Part pages -->
<File Url="WebPartPage.aspx" Name="WebPartPage01.aspx" Type="Ghostable" />
<File Url="WebPartPage.aspx" Name="WebPartPage02.aspx" Type="Ghostable" />
<!-- provision Web Part page with Web Parts inside -->
<File Url="WebPartPage.aspx" Name="WebPartPage03.aspx" Type="Ghostable" /> */

<File Url="CustSitePages_All.aspx" Name="CustSitePages_All.aspx" Type="Ghostable" />

</Module>

</Elements>

Step 9-"CustSitePagesCls.cs" will be as follows-
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.SharePoint;
using System.Web.UI.WebControls;
using System.Web.UI;

namespace CustSitePagesClass
{
public class CustSitePagesCls : WebControl
{
protected override void RenderContents(HtmlTextWriter output)
{
SPWeb site = SPContext.Current.Web;
output.Write("Current Site: " + site.Title);
output.Write("<br/>");
output.Write("Current Site ID: " + site.ID.ToString());
}
}
}


Step 10-FeatureReceiver.cs will be as follows-
using System;
using System.Web.UI.WebControls.WebParts;
using System.Xml;
using Microsoft.SharePoint;
using Microsoft.SharePoint.WebControls;
using Microsoft.SharePoint.WebPartPages;
using Microsoft.SharePoint.Navigation;

namespace CustSitePagesClass
{
class FeatureReceiver : SPFeatureReceiver
{
public override void FeatureActivated(SPFeatureReceiverProperties properties)
{
// get a hold off current site in context of feature activation
SPWeb site = (SPWeb)properties.Feature.Parent;
SPNavigationNodeCollection topNav = site.Navigation.TopNavigationBar;

// create dropdown menu for custom site pages
SPNavigationNode DropDownMenu1 =
new SPNavigationNode("Custom Site Pages", "", false);
topNav[0].Children.AddAsLast(DropDownMenu1);
DropDownMenu1.Children.AddAsLast(
new SPNavigationNode("Site Page 1", "SitePages/Page01.aspx"));

DropDownMenu1.Children.AddAsLast(new SPNavigationNode("Site Page 2", "SitePages/Page02.aspx"));
DropDownMenu1.Children.AddAsLast(new SPNavigationNode("Site Page 3", "SitePages/Page03.aspx"));
DropDownMenu1.Children.AddAsLast(new SPNavigationNode("Site Page 4", "SitePages/Page04.aspx"));
DropDownMenu1.Children.AddAsLast(new SPNavigationNode("Site Page 5", "SitePages/Page05.aspx"));
DropDownMenu1.Children.AddAsLast(new SPNavigationNode("Site Page 6", "SitePages/Page06.aspx"));

// create dropdown menu for custom Web Part Pages
SPNavigationNode DropDownMenu2 = new SPNavigationNode("Custom Web Part Pages", "", false);
topNav[0].Children.AddAsLast(DropDownMenu2);
DropDownMenu2.Children.AddAsLast(new SPNavigationNode("Web Part Page 1", "SitePages/WebPartPage01.aspx"));
DropDownMenu2.Children.AddAsLast(new SPNavigationNode("Web Part Page 2", "SitePages/WebPartPage02.aspx"));
DropDownMenu2.Children.AddAsLast(new SPNavigationNode("Web Part Page 3", "SitePages/WebPartPage03.aspx"));

SPFile page = site.GetFile("SitePages/WebPartPage02.aspx");
SPLimitedWebPartManager mgr;
mgr = page.GetLimitedWebPartManager(PersonalizationScope.Shared);
// add Web Part to Left Zone
ContentEditorWebPart wp1 = new ContentEditorWebPart();
wp1.Title = "My Most Excellent Title";
wp1.ChromeType = PartChromeType.TitleOnly;
wp1.AllowClose = false;
XmlDocument doc = new XmlDocument();
string ns1 = "http://schemas.microsoft.com/WebPart/v2/ContentEditor";
XmlElement elm = doc.CreateElement("Content", ns1);
elm.InnerText = "This Web Part was added through code";
wp1.Content = elm;
mgr.AddWebPart(wp1, "Left", 0);
// add Web Part to Right Zone
ImageWebPart wp2 = new ImageWebPart();
wp2.ChromeType = PartChromeType.None;
wp2.ImageLink = @"/_layouts/images/IPVW.GIF";
mgr.AddWebPart(wp2, "Right", 0);

//code for CustomSitePages_ALL
//SPFile pageAll = site.GetFile("SitePages/WebPartPage02.aspx");
SPFile pageAll = site.GetFile("SitePages/CustomSitePages_ALL");
SPLimitedWebPartManager mgrAll;
mgrAll = pageAll.GetLimitedWebPartManager(PersonalizationScope.Shared);
// add Web Part to Left Zone
ContentEditorWebPart wpAll = new ContentEditorWebPart();
wpAll.Title = "My Most Excellent Title";
wpAll.ChromeType = PartChromeType.TitleOnly;
wpAll.AllowClose = false;
XmlDocument docAll = new XmlDocument();
string nsAll = "http://schemas.microsoft.com/WebPart/v2/ContentEditor";
XmlElement elmAll = docAll.CreateElement("Content", nsAll);
elmAll.InnerText = "This Web Part was added through code";
wpAll.Content = elmAll;
mgrAll.AddWebPart(wpAll, "Left", 0);
// add Web Part to Right Zone
ImageWebPart wp2All = new ImageWebPart();
wp2All.ChromeType = PartChromeType.None;
wp2All.ImageLink = @"/_layouts/images/IPVW.GIF";
mgrAll.AddWebPart(wp2All, "Right", 0);
}

public override void FeatureDeactivating(SPFeatureReceiverProperties properties)
{
SPWeb site = (SPWeb)properties.Feature.Parent;
// delete folder of site pages provisioned during activation
SPFolder sitePagesFolder = site.GetFolder("SitePages");
sitePagesFolder.Delete();

SPNavigationNodeCollection topNav = site.Navigation.TopNavigationBar;

for (int i = topNav[0].Children.Count - 1; i >= 0; i--)
{
if (topNav[0].Children[i].Title == "Custom Site Pages" ||
topNav[0].Children[i].Title == "Custom Web Part Pages")
{
// delete node
topNav[0].Children[i].Delete();
}
}
}

public override void FeatureInstalled(SPFeatureReceiverProperties properties)
{
// new NotImplementedException();
}

public override void FeatureUninstalling(SPFeatureReceiverProperties properties)
{
//throw new NotImplementedException();
}
}
}


Step 11-Copy the dll of CustSitePagesClass project to the GAC and copy the CustSitePages project files in the 12 hives as per the folder structure.

Step 12-Install & activate the feature "CustSitePages"
C:\Program Files\Common Files\Microsoft Shared\web server extensions\12\BIN>stsa
dm -o installfeature -name CustSitePages -force

Step 13-Browse the URL as follows-
http://vpc1:2010/sites/SharepointPoC/Sitepages/CustSitePages_All.aspx

Step 14-You can see the output as follows-


2011-02-08

Create a custom application page in sharepoint 2007

Step 1-Create a Asp.NET Web Application project "CustAppPage" and a class library project "CustAppPageClassLib" and make the folder structure as follows



Step 2-Feature.xml will be as follows-
<Feature xmlns="http://schemas.microsoft.com/sharepoint/"
Id="{E0A4DFA4-717D-44b0-8292-B46593E64B80}"
Title="My Feature-Cust App Page"
Description="Shows a navigation link in under site action menu and ECB menu"
Hidden="false"
Scope="Web"
ImageUrl="menuprofile.gif"
>
<ElementManifests >
<ElementManifest Location="Elements.xml"/>
</ElementManifests>

</Feature>

Step 3-Elements.xml will be as follows-
<Elements xmlns="http://schemas.microsoft.com/sharepoint/">
<!-- Add Command to Site Actions Dropdown -->
<CustomAction Id="CustomApplicationPage_StandardMenu"
GroupId="SiteActions"
ImageUrl="~/_layouts/images/menuprofile.gif"
Location="Microsoft.SharePoint.StandardMenu"
Sequence="2001"
Title="Cust Application Page 1"
Description="CustomApplicationPage under StandardMenu">
<UrlAction Url="~site/_layouts/MyCustAppPages/ApplicationPage1.aspx"/>
</CustomAction>

<!-- Per Item Dropdown (ECB) Link -->
<CustomAction Id="CustomApplicationPage_ECB"
RegistrationType="List"
RegistrationId="101"
ImageUrl="~/_layouts/images/menuprofile.gif"
Location="EditControlBlock"
Sequence="240"
Title="CustomApplicationPage under ECB" >
<UrlAction Url="~site/_layouts/MyCustAppPages/ApplicationPage1.aspx?ItemId={ItemId}&ListId={ListId}"/>
</CustomAction>

</Elements>

Step 4-"ApplicationPage1.aspx"(Code behind approach) will be as follows-
<%@ Assembly Name="Microsoft.SharePoint, Version=12.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c" %>
<%@ Assembly Name="CustAppPageClassLib, Version=1.0.0.0, Culture=neutral, PublicKeyToken=30534ee939de1c1d" %>

<%@ Page Language="C#" MasterPageFile="~/_layouts/application.master"
Inherits="CustAppPageClassLib.ApplicationPage1"
EnableViewState="false" EnableViewStateMac="false" %>

<asp:Content ID="Main" contentplaceholderid="PlaceHolderMain" runat="server">
<table border="1" cellpadding="4" cellspacing="0" style="font-size:12">
<tr>
<td>Site Title:</td>
<td><asp:Label ID="lblSiteTitle" runat="server" /></td>
</tr>
<tr>
<td>Site ID:</td>
<td><asp:Label ID="lblSiteID" runat="server" /></td>
</tr>
</table>
</asp:Content>

<asp:Content ID="PageTitle" runat="server"
contentplaceholderid="PlaceHolderPageTitle" >
Hello World
</asp:Content>

<asp:Content ID="PageTitleInTitleArea" runat="server"
contentplaceholderid="PlaceHolderPageTitleInTitleArea" >
Application Page 1: 'Hello World' with code behind
</asp:Content>

Step 5-"HelloWorld.aspx"(Inline c# code) will be as follows-
<%@ Assembly Name="Microsoft.SharePoint, Version=12.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c"%>
<%@ Page Language="C#" MasterPageFile="~/_layouts/application.master" Inherits="Microsoft.SharePoint.WebControls.LayoutsPageBase" %>

<%@ Import Namespace="Microsoft.SharePoint" %>

<script runat="server">
protected override void OnLoad(EventArgs e) {
//SPWeb site = SPContext.Current.Web;
SPWeb site = this.Web;
lblSiteTitle.Text = site.Title;
lblSiteID.Text = site.ID.ToString().ToUpper();
}
</script>

<asp:Content ID="Main" contentplaceholderid="PlaceHolderMain" runat="server">
<table border="1" cellpadding="4" cellspacing="0" style="font-size:12">
<tr>
<td>Site Title:</td>
<td><asp:Label ID="lblSiteTitle" runat="server" /></td>
</tr>
<tr>
<td>Site ID:</td>
<td><asp:Label ID="lblSiteID" runat="server" /></td>
</tr>
</table>
</asp:Content>

<asp:Content ID="PageTitle" contentplaceholderid="PlaceHolderPageTitle" runat="server">
Hello World
</asp:Content>

<asp:Content ID="PageTitleInTitleArea" runat="server"
contentplaceholderid="PlaceHolderPageTitleInTitleArea" >
The Quintessential 'Hello World' of Application Page
</asp:Content>

Step 6-"ApplicationPage1.cs" under "CustAppPageClassLib" will be as follows
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.SharePoint;
using Microsoft.SharePoint.WebControls;
using System.Web;
using System.Web.UI.WebControls;
using System.Web.UI;

namespace CustAppPageClassLib
{
public class ApplicationPage1 : LayoutsPageBase
{
// add control fields to match controls tags on .aspx page
protected Label lblSiteTitle;
protected Label lblSiteID;

protected override void OnLoad(EventArgs e)
{

// get current site and web
SPSite siteCollection = this.Site;
SPWeb site = this.Web;

// program against controls on .aspx page
lblSiteTitle.Text = site.Title;
lblSiteID.Text = site.ID.ToString().ToUpper();

if (Request.QueryString["ListId"] != null)
{
lblSiteID.Text = lblSiteID.Text + " ,List ID :" + Request.QueryString["ListId"].ToString();
}
if (Request.QueryString["ItemId"] != null)
{
lblSiteID.Text = lblSiteID.Text + " ,Item ID :" + Request.QueryString["ItemId"].ToString();
}

}
}
}

Step 7-Add the strong name to your project "CustAppPageClassLib" and install it in the GAC.

Step 8-Copy your aspx pages in the following folder
C:\Program Files\Common Files\Microsoft Shared\web server extensions\12\TEMPLATE\LAYOUTS\MyCustAppPages

and copy the others pages as the folder structure in your project

Step 9-Install the feature and activate it.

Step 10-click the "Cust Application Page 1" menu as follows and you can see the output as follows-


Step 11- Or click on the ECB menu on any list item


You can see the output as follows-


Step 12-You can type the URL and see your Helloworld.aspx page