Search This Blog

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

2011-02-07

Create a connected web part and activate through feature

Step 1-Create a class library project and make the folder structure as follows


Step 2-Connectedwebpart.cs will be as follows
using System;
using System.Collections.Generic;
//using System.Linq;
using System.Text;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;

namespace ConnectedWebPart
{
public interface ICustomerProvider
{
string CustomerID { get; }
string CustomerName { get; }
}
public class SimpleProviderExample : WebPart, ICustomerProvider
{
private string _customerID = "P1284";
private string _customerName = "Manab";

protected override void RenderContents(HtmlTextWriter writer)
{
writer.Write("Customer ID: " + this.CustomerID);
writer.Write("Customer Name: " + this.CustomerName);
}
public string CustomerID
{
get { return this._customerID; }
}
public string CustomerName
{
get { return this._customerName; }
}

[ConnectionProvider("Customer ID","Customer Name", AllowsMultipleConnections = true)]
public ICustomerProvider GetCustomerProvider()
{
return this;
}
}

public class SimpleConsumerExample : WebPart
{
private ICustomerProvider customerProvider;

[ConnectionConsumer("Customer ID", "Customer Name")]
public void RegisterCustomerProvider(ICustomerProvider provider)
{
this.customerProvider = provider;
}

protected override void RenderContents(HtmlTextWriter writer)
{
if (this.customerProvider != null)
{
writer.Write(this.customerProvider.CustomerID);
writer.Write(this.customerProvider.CustomerName);
}
else
writer.Write("No connection");
}
}
public class ConnectionWebPart
{
}
}

Step 3-SimpleConsumerExample.webpart will be as follows-
<webParts>
<webPart xmlns="http://schemas.microsoft.com/WebPart/v3">
<metaData>
<type name="ConnectedWebPart.SimpleConsumerExample" />
<importErrorMessage>Cannot import this Web Part.</importErrorMessage>
</metaData>
<data>
<properties>
<property name="AllowClose" type="bool">True</property>
<property name="Width" type="unit" />
<property name="AllowMinimize" type="bool">True</property>
<property name="AllowConnect" type="bool">True</property>
<property name="ChromeType" type="chrometype">Default</property>
<property name="TitleIconImageUrl" type="string" />
<property name="Description" type="string" />
<property name="Hidden" type="bool">False</property>
<property name="TitleUrl" type="string" />
<property name="AllowEdit" type="bool">True</property>
<property name="Height" type="unit" />
<property name="HelpUrl" type="string" />
<property name="Title" type="string">SimpleConsumerExample</property>
<property name="CatalogIconImageUrl" type="string" />
<property name="Direction" type="direction">NotSet</property>
<property name="ChromeState" type="chromestate">Normal</property>
<property name="AllowZoneChange" type="bool">True</property>
<property name="AllowHide" type="bool">True</property>
<property name="HelpMode" type="helpmode">Navigate</property>
<property name="ExportMode" type="exportmode">All</property>
</properties>
</data>
</webPart>
</webParts>

Step 4-SimpleProviderExample.webpart will be as follows-
<webParts>
<webPart xmlns="http://schemas.microsoft.com/WebPart/v3">
<metaData>
<type name="ConnectedWebPart.SimpleProviderExample" />
<importErrorMessage>Cannot import this Web Part.</importErrorMessage>
</metaData>
<data>
<properties>
<property name="AllowClose" type="bool">True</property>
<property name="Width" type="unit" />
<property name="AllowMinimize" type="bool">True</property>
<property name="AllowConnect" type="bool">True</property>
<property name="ChromeType" type="chrometype">Default</property>
<property name="TitleIconImageUrl" type="string" />
<property name="Description" type="string" />
<property name="Hidden" type="bool">False</property>
<property name="TitleUrl" type="string" />
<property name="AllowEdit" type="bool">True</property>
<property name="Height" type="unit" />
<property name="HelpUrl" type="string" />
<property name="Title" type="string">SimpleProviderExample</property>
<property name="CatalogIconImageUrl" type="string" />
<property name="Direction" type="direction">NotSet</property>
<property name="ChromeState" type="chromestate">Normal</property>
<property name="AllowZoneChange" type="bool">True</property>
<property name="AllowHide" type="bool">True</property>
<property name="HelpMode" type="helpmode">Navigate</property>
<property name="ExportMode" type="exportmode">All</property>
</properties>
</data>
</webPart>
</webParts>

Step 5-feature.xml will be as follows-
<Feature
Id="FE016E00-8639-4839-925D-B40F659458A9"
Title="Sample Connected Web Parts"
Description="This demoware was created for Inside Windows SharePoint Services (Pattison/Larson)"
Hidden="FALSE"
Scope="Site"
ImageUrl="TPG/canteen.gif"
xmlns="http://schemas.microsoft.com/sharepoint/">

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

</Feature>

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

<Module Name="LitwareWebParts"
List="113"
Url="_catalogs/wp"
Path="dwp"
RootWebOnly="true">
<File Url="SimpleConsumerExample.webpart" Type="GhostableInLibrary" >
<Property Name="Group" Value="Litware Web Parts" />
</File>
<File Url="SimpleProviderExample.webpart" Type="GhostableInLibrary" >
<Property Name="Group" Value="Litware Web Parts" />
</File>
</Module>
</Elements>

Step 7-Copy the dll to GAC and others files to the respective folder of 12 hives

Step 8-Make a safecontrol entry to the web config of your site
<SafeControl Assembly="ConnectedWebPart, Version=1.0.0.0, Culture=neutral, PublicKeyToken=30534ee939de1c1d" Namespace="ConnectedWebPart" TypeName="*" Safe="True" />

Step 9-Activate your feature from the site collection features


Step 10-Add it to your web part zone and make the connection between two web parts

2011-02-05

Create a simple webpart

Step 1-Create a website "Website1"
Step 2-Add reference "windows sharepoint service"
Step 3-Add a Web user control "SampleUserControl.ascx" in your project
Step 4-HTML code of the user control will be as follows
<%@ Control Language="C#" AutoEventWireup="true" CodeFile="SampleUserControl.ascx.cs"
Inherits="SampleUserControl" %>
<table>
<tr>
<td>
Put a URL of your Site :
</td>
<td>
<asp:TextBox ID="txtSiteUrl" Text="http://vpc1:2010/sites/SharepointPoC" runat="server"></asp:TextBox>
</td>
</tr>
<tr>
<td colspan="2">
<asp:Button ID="btnSPList" runat="server" Text="Find Splist"
onclick="btnSPList_Click" />
</td>
</tr>
<tr>
<td colspan="2">
<asp:TextBox ID="txtOutput" runat="server" Text="output Window"
TextMode="MultiLine" Width="100%"></asp:TextBox>
</td>
</tr>
<tr>
<td colspan="2">
File Viewer Control
</td>
</tr>
<tr>
<td colspan="2">
<asp:TreeView NodeStyle-HorizontalPadding="6" ID="treeSitesFiles" runat="server" EnableViewState="false" />
</td>
</tr>
</table>



The C# code will be as follows


using System;
using System.Collections.Generic;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Microsoft.SharePoint;

public partial class SampleUserControl : System.Web.UI.UserControl
{
protected void Page_Load(object sender, 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);
}


}
protected void btnSPList_Click(object sender, EventArgs e)
{
txtOutput.Text = "";
string sitePath = txtSiteUrl.Text;
// enter object model through site collection.
SPSite siteCollection = new SPSite(sitePath);
// obtain reference to top-level site.
SPWeb site = siteCollection.RootWeb;
txtOutput.Text = "Site Url is " + site.Url + "\n";
// enumerate through lists of site
foreach (SPList list in site.Lists)
{
txtOutput.Text = txtOutput.Text + "\n" + list.Title;
//Console.WriteLine(list.Title);
}
// clean up by calling Dispose.
site.Dispose();
siteCollection.Dispose();

}
}


Step 5-Add a class library project "MyWebPartClass" to your solution
Step 6-Add reference "Windows sharepoint service"
Step 7-Add a class "MyWebprtClass.cs" to your project
Step 8-The code will be as follows
using System;
using System.Collections.Generic;
using System.Web;
using Microsoft.SharePoint.WebPartPages;

///
/// Summary description for MyWebprtClass
///

namespace MyWebPartClass
{
public class MyWebprtClass : WebPart
{
System.Web.UI.Control _myControl;
String err;
public MyWebprtClass()
{
//
// TODO: Add constructor logic here
//
}
protected override void CreateChildControls()
{
try
{
this.Controls.Clear();
_myControl = this.Page.LoadControl("~\\_layouts\\SampleUserControl.ascx");
this.Controls.Add(_myControl);
}
catch (Exception ex)
{

}


}
protected override void Render(System.Web.UI.HtmlTextWriter writer)
{
try
{
// _myControl = this.Page.LoadControl("~\\_layouts\\SampleUserControl.ascx");
_myControl.RenderControl(writer);
}
catch (Exception ex)
{
writer.Write(ex.Message.ToString());
}

}
}
}

Step 9-Add a xml "MyWebPartClass.xml" to your project and add the following line of code-
<?xml version="1.0" encoding="utf-8" ?>
<webParts>
<webPart xmlns="http://schemas.microsoft.com/WebPart/v3">
<metaData>
<type name="MyWebPartClass.MyWebprtClass, MyWebPartClass, Version=1.0.0.0, Culture=neutral, PublicKeyToken=30534ee939de1c1d" />
<importErrorMessage>Cannot import this Web Part.</importErrorMessage>
</metaData>
<data>
<properties>
<property name="Title" type="string">SmartParticles Web Part</property>
<property name="Description" type="string">
A demonstration using WebParticles in
a SharePoint WebPart
</property>
<property name="ChromeType">TitleOnly</property>
<property name="ChromeState">Normal</property>
<property name="ItemLimit" type="int">15</property>
<property name="ItemStyle" type="string">Default</property>
</properties>
</data>
</webPart>
</webParts>


Step 10-Add a strong name to your calss library project,build it and install it to GAC
Step 11-Copy your aspx and cs page to the following folder
C:\Program Files\Common Files\Microsoft Shared\web server extensions\12\TEMPLATE\LAYOUTS
Step 11-Open the web config of your sharepoint site and paste the following line to your SafeControls node

<SafeControl Assembly="MyWebPartClass, Version=1.0.0.0, Culture=neutral, PublicKeyToken=30534ee939de1c1d" Namespace="MyWebPartClass" TypeName="*" Safe="True" />

Step 12-Go to Site Settings->Galleries ->Web Parts
Click upload and browse the "MyWebPartClass.xml" ,click OK

Then go to any web part zone and add your webpart "MyWebPartClass.xml" from the custom section.

Output will be as follows-

Create A Simple Feature

Step 1-Create A class library project "MyFeature" in C#
Step 2-Add reference "Windows Sharepoint Services"
Step 3-Create a folder "Features" under the class library and a a folder "MyFeature" under the "Features" folder
Step 4-Add a XML file "Feature.xml" under "MyFeature" folder
Step 5-Add a schema file to your XML from the following path-
C:\Program Files\Common Files\Microsoft Shared\web server extensions\12\TEMPLATE\XML\wss.xsd
Step 6-The content of the feature.xml will be as follows
<Feature xmlns="http://schemas.microsoft.com/sharepoint/"
Id="0222472A-0CF1-46bc-8B65-3F319C7B3DBE"
Title="My Feature"
Description="This is my first feature"
Hidden="false"
Scope="Web"
ImageUrl="menuprofile.gif"
ReceiverClass="MyFeature.MyFeatureReceiver"
ReceiverAssembly="MyFeature, Version=1.0.0.0, Culture=neutral, PublicKeyToken=30534ee939de1c1d"
>
<ElementManifests >
<ElementManifest Location="Elements.xml"/>
</ElementManifests>
</Feature>


The Id Value must be unique and will be generated from Tools->Guid Generator".Title ,description and image will be displayed in the feature list of your web site.Scope can be Farm,WebApplication,Site,Web depending on the scenario.
ReceiverClass and ReceiverAssembly will be explain in the next section.
ElementManifests element will call another xml.

Step 6-Add "Elements.xml" under "MyFeature" folder.
The content of the Elements.xml will be as follows-
<Elements xmlns="http://schemas.microsoft.com/sharepoint/">
<Module Name="MyModule" Path="" Url="">
<File Url="MyModule.aspx"
Type="Ghostable"
IgnoreIfAlreadyExists="FALSE">
</File>
</Module>
<CustomAction Id="SiteActionsToolbar"
GroupId="SiteActions"
Location="Microsoft.SharePoint.StandardMenu"
Sequence="1000"
Title="Go To MyModule"
ImageUrl="~/_layouts/images/menuprofile.gif">
<UrlAction Url="~site/MyModule.aspx"/>
</CustomAction>
</Elements>

CustomAction element defines where the feature will be displayed after activation.
UrlAction element defines the url of the aspx page.But to access the url we first need to define File url.

Step 7-Add a text file "MyModule.aspx" under the "MyFeature" folder.The content will be as follows
<%@ Page Language="C#" MasterPageFile="~masterurl\default.master" %>
<asp:Content ContentPlaceHolderID="PlaceHolderMain" runat="server">
<h2>Hello , This is my test page</h2>
</asp:Content>

Step 8-Add a class file under the class library
"MyFeatureReceiver.cs"


The content will be as follows
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.SharePoint;

namespace MyFeature
{
public class MyFeatureReceiver:SPFeatureReceiver
{
public override void FeatureActivated(SPFeatureReceiverProperties properties)
{
SPWeb site = (SPWeb)properties.Feature.Parent;
// SPWeb site = SPContext.Current.Web;//when the scope of the feature is site
// track original site Title using SPWeb property bag
site.Properties["OriginalTitle"] = site.Title;
site.Properties.Update();
// update site title
site.Title = "My Feature has been activated";
site.Update();
}

public override void FeatureDeactivating(SPFeatureReceiverProperties properties)
{
// reset site Title back to its original value
SPWeb site = (SPWeb)properties.Feature.Parent;
//SPWeb site = SPContext.Current.Web;//when the scope of the feature is site
site.Title = site.Properties["OriginalTitle"];
site.Update();

}

public override void FeatureInstalled(SPFeatureReceiverProperties properties)
{
}

public override void FeatureUninstalling(SPFeatureReceiverProperties properties)
{
}
}
}


Step 9-Add a strong name to your class library ,build it and copy the dll to GAC
Step 10-Open the Feature.xml and write the ReceiverClass,ReceiverAssembly according to your "MyFeatureReceiver.cs"

Your solution structure will be as follows-


Step 11-Copy your "MyFeature" folder (which is under the "Features" folder) to the following location
C:\Program Files\Common Files\Microsoft Shared\web server extensions\12\TEMPLATE\FEATURES

Step 12-Install your feature by the following command in the command prompt-
stsadm -o InstallFeature -name MyFeature -force

Stsadm exe will be found in the following path
C:\Program Files\Common Files\Microsoft Shared\web server extensions\12\BIN\STSADM.EXE

Step 13-Activate your feature from the site setting->site features


Step 14-After activation , you will find the title and label under the menu


Step 15-Click on the "Go To MyModule" ,you will be navigated to your MyModule.aspx



Step 16-After deactivation of your feature ,all of these thing will be undone.