Wednesday, January 29, 2014

Insert time stamp into the list, when feature is activated

Hello All,
Today I am going to show how to insert time stamp into list when feature is activated or deactivated.
Steps:
1. Add a sharepoint empty project and add a webpart to it.
In the web part insert the following code.
1
2
3
4
5
6
7
8
9
10
11
[ToolboxItemAttribute(false)]
 
public class MyWebPart : WebPart
{
protected override void CreateChildControls()
{
Label lbl = new Label();
lbl.Text = "Feature Activated";
Controls.Add(lbl);
}
}
2. Now right click on the feature and select the “Add Event Receiver
Uncomment the FeatureActivated block and insert the following code.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
 public override void FeatureActivated(SPFeatureReceiverProperties properties)
 {
 SPSite site = properties.Feature.Parent as SPSite;
 SPWeb web = site.RootWeb;
 
SPList list = web.Lists["Features Tracker"];
 if (list == null)
 {
 Guid listid = web.Lists.Add("Features Tracker", "Trakcs the feature activation time", SPListTemplateType.GenericList);
 web.Lists[listid].Fields.Add("Activated Time", SPFieldType.DateTime, true);
 SPView myview = web.Lists[listid].DefaultView;
 myview.ViewFields.Add("Activated Time");
 myview.Update();
 list.Update();
 }
 SPListItem listitem = list.Items.Add();
 listitem["Activated Time"] = DateTime.Now;
 listitem.Update();
 list.Update();
 }
you can see the time stamps as below after deployment.

No comments:

Post a Comment