Subscribe:

Labels

Sunday, December 11, 2011

check the condition the group in exist or not


these 2 metod are using for check the condition the group in exist or not

private bool isGroupAlreadyExist(SPWeb web, string groupName)
        {
            bool isExist = false;

            try
            {
                SPGroup group = web.SiteGroups[groupName];
                isExist = true;
            }
            catch (SPException)
            {
                isExist = false;
            }
            catch (Exception)
            {
                isExist = false;
            }
            return isExist;
        }


if (!isGroupAlreadyExist(web, groupName))
                {
                   
                }


get spsuer using object model

this is for get spuser... code using object model

 /// <summary>
        /// Returns the SPUser Object built based on the OOTB people or groups field type of sharepoint.
        /// Get SPUser Object from a SharePoint list item people or group field value.
        /// Can be used to get the user object properties, e.g. email of the user.
        /// </summary>
        /// <param name="spListItem">Source list item</param>
        /// <param name="fieldName">column/field name, e.g., "PersResponsible"</param>
        /// <returns></returns>

        public SPUser GetSPUserObject(SPListItem spListItem, String fieldName)
        {
            SPUser spUser = null;
            try
            {
                if (fieldName != string.Empty)
                {
                    SPFieldUser field = spListItem.Fields[fieldName] as SPFieldUser;
                    if (field != null && spListItem[fieldName] != null)
                    {
                        SPFieldUserValue fieldValue = field.GetFieldValue(spListItem[fieldName].ToString()) as SPFieldUserValue;
                        if (fieldValue != null)
                        {
                            spUser = fieldValue.User;

                        }
                    }
                }
            }
            catch (Exception ex)
            {
              
            }

            return spUser;
        }

Customize Top Navigation Bar - Horizontal Orientation for second level


Add Css in core4.css

.s4-toplinks {
    padding-bottom: 20px; /* create space to fit the 2nd level nav */
    position: relative;
}
 
.s4-toplinks .s4-tn li {
    position: static !important; /* 2nd level will be positioned relative to .s4-toplinks container */
float:left;
}
 


Add this in Master page 


<SharePoint:AspMenu
 ID="TopNavigationMenuV4"
 Runat="server"
 EnableViewState="false"
 DataSourceID="topSiteMap"
 AccessKey="<%$Resources:wss,navigation_accesskey%>"
 UseSimpleRendering="true"
 UseSeparateCss="false"
 Orientation="Horizontal"
 StaticDisplayLevels="2"
 MaximumDynamicDisplayLevels="4"
 SkipLinkText=""
 CssClass="s4-tn"/>

<Template_Controls>
<asp:SiteMapDataSource
 ShowStartingNode="true"(change here)
 SiteMapProvider="SPSiteMapProvider"(change here)
 id="topSiteMap"
 runat="server"
 />



Create a mysite(personal site) Using the Object Model

Below code is using object model creating the my sites dynamically.


            SPSite site = new SPSite("http://win-rgqt3bch3nk:22929/sites/Test");

            SPWeb web = site.OpenWeb();
            // SPWeb web = SPContext.Current.Web;


            web.AllowUnsafeUpdates = true;

         
            if (ApproveitemId > 0)
            {
                SPList thislist = web.Lists["Requests"];
                SPListItem item = thislist.Items.GetItemById(ApproveitemId);
                string AStatus = item["Approval_Status"].ToString();
                string strYes = "Yes";
                if (AStatus == strYes)
                {
                    string mysiteusername = item["Username"].ToString();
                     //SPUser mysiteuname = web.AllUsers[mysiteusername];

                    SPSecurity.RunWithElevatedPrivileges(delegate()
                         {
                             using (SPSite spSite = new SPSite("http://win-rgqt3bch3nk:38562"))
                             {
                                 spSite.AllowUnsafeUpdates = true;
                                 SPContext.Current.Web.AllowUnsafeUpdates = true;
                                 SPServiceContext siteContext = SPServiceContext.GetContext(spSite);
                                 //UserProfileManager up = new UserProfileManager(siteContext,true);
                                 UserProfileManager up = new UserProfileManager(siteContext);
                                 //string sAccount = "WIN-RGQT3BCH3NK\\test1";
                                 //UserProfile uprof = up.GetUserProfile(sAccount.Trim());
                                 UserProfile uprof = up.GetUserProfile(mysiteusername);
                                 uprof.CreatePersonalSite();
                             }
                         });
                }
            }
         
        }

Thursday, November 24, 2011

Retention Policy for document library in SharePoint 2010


One of the major improvements in SharePoint 2010 compared to prior version is the improvements in information management policies. SharePoint 2010 can apply the expiration policy in multiple stages, where each stage can do some specific actions such as deleting draft versions, deleting previous versions, deleting the record etc. In SharePoint 2010 you can apply the retention policy to a content type, to a list or document library, to a folder.
How to create own retention policies on a Document Library
1. If a document is not modified for 2 years delete its previous versions
2. Any document created here to be deleted after 3 years.
Here are the steps to navigate to the “Shared Documents” document library to set the retention policy.
Before doing Retention policies, it requires some Configuration settings in Site and SharePoint Central Administration.
Essentially, you have to Activate the "Content Organizer" feature at the Site Level. Once that is done, you get the "Drop off Library" as well as 2 new options in the Site Settings. Content Organizer Rules and Content Organizer Settings. In that, you can take the .asmx link and then paste it in the Central Admin Configure Send to Connections. After that, the routing should work fine. Using the Rules and that is mostly using Content Types, you can route the document to the right library instead of letting it stay in the Drop off Library.

In the SharePoint Central Administration, under General Application Settings
External Service Connections, select Configure send to connections.

Here you have to configure the “Send to Connections”. After giving the URL, check to verify whether it is valid or not.

From the top ribbon, navigate to the Library tab, and then click on Library settings.
It will be navigated to the document library settings page. Click on the Information management policy settings from this page.


By default a library will inherit its policies from the content type, so that the policies set for the content type will be applied. You can change this by overriding “Source of retention for this library” property. set up retention policy for “Shared Documents” library . Click on the “change source” link.
 
You will reach the configuration page for the retention schedule. Select the libraries and folders radio button. You will receive a warning alert stating the content type retention policy will be ignored. Click ok here.
You can see the configuration options available for document library/list here. Click on “add a retention stage" link
Based on Created and Modified, a Document can be Moved to Recycle or Delete or can be transferred to another locationas shown



Based on the requirement we can create the Retention Policies. 

Thursday, November 3, 2011

Sandbox Solutions in SharePoint 2010

Sandbox solution is a new feature introduced in SharePoint 2010. It's a secured wrapper around webparts and other elements with limitations. There is no thumb rule that every webpart in SharePoint 2010 belongs to Sandbox Solution. But it's recommended to develop webparts with Sandbox solution. It allows administrators to monitor the solutions and control as required. SharePoint Site Collection administrators can view the resource utilization of each solution and can block if it consumes too much resources. Usually when sites working slow, developers complain the server is slow whereas site/server administrators blame on Develepor code/solutions. Now Microsoft put a Full Stop to that.


SharePoint solutions run in seperate worker processes and not in w3wp.exe. So It doesn't require IIS Reset or Application Pool Recycling. Without disturbing the SharePoint site, Sandbox solutions can be deployed. Only thing while deploying new version of Sandbox solution over existing solution, SharePoint will display No Solution found error in Sandbox Webparts on the page. However within seconds sandbox solutions getting deployed and it'll start working. In SharePoint 2007, only farm administrators can install/deploy developer solutions. But Now site collection administrators can deploy solutions with web based interface. This reduces the dependency of Farm Administrator and improves rapid deployment.


Sandbox Processes
Here the processes which required for Sandbox solutions.
  1. SPUCWorkerprocess.exe - Sandbox Worker process service which is a Seperate Service Application which actually executes Sandbox code. It should be started in every farm to use Sandbox solutions.
  2. SPUCWorkerProcessProxy.exe - Sandbox Worker process proxy which is working as a proxy for Worker process and takes care of Sandbox code execution. It can also serve to other farms if configured. Basically it helps site administrator for load balancing.
  3. SPUCHostService.exe - Sandbox User Code Service takes care of user code in Sandbox amd it can be started in the farms where to use Sandbox solutions.
Sandbox Limitations
 Sandbox is a secured wrapper and it has restrictions on code to run in SharePoint environment. Few Key limitations which developers should know are listed below.
  1. No Security Elevation - RunWithElevatedPrivileges which runs the specified block of code in application pool account(typically System Account) context is not allowed in Sandbox code. SPSecurity class also not allowed to use in Sandbox.
  2. No Email Support - SPUtility.SendMail method has been blocked explicitly in Sandbox, However .Net mail classes can be used to send mails. Additionaly sandbox won't allow to read Farm SMTP address. So developers has to specify the SMTP address in code itself(may be some other workaround).
  3. No Support to WebPartPages Namespace - Sandbox won't allow to use Microsoft.SharePoint.WebPartPages namespace.
  4. No Support to external Webservice - Internet web service calls are not allowed to ensure security in Sandbox solutions. Allow Partially Trusted code also can't be accessed within Sandbox.
  5. No GAC Deployment - Sandbox solutions are not stored in File System(Physical path) and assemblies can't be deployed to Global Assembly Cache(GAC). But it's available on C:\ProgramData\Microsoft\SharePoint\UCCache at runtime. Note the ProgramData is a hidden folder.
  6. No Visual Webparts - Visual Studio 2010 by default won't allow to create Visual Webparts to deploy as sandbox solution. But with Visual Studio PowerTools extensions(downloadable from Microsoft MSDN website) Visual Webparts can be developed and deployed as sandbox Solutions.
SharePoint Online which is SharePoint environment provided by Microsoft to manage SharePoint Sites in internet accepts only Sandbox solutions. Because SharePoint Online sites are Windows Servers at Microsoft Datacenters, Microsoft won't allow GAC deployment or file system access. In future Sandbox solution will give more features for developers. 

Configuring Sandboxed Solutions - Cannot start service SPUserCodeV4 on computer

When you built and deploy SharePoint 2010 solution using Farm it will deploy successfully.

But when you create a SharePoint 2010 solution using Sandboxed it may throw an Error

Error occurred in deployment step 'Activate Features': Cannot start service SPUserCodeV4 on computer 

The error can be easily resolved by starting the Microsoft SharePoint Foundation Sandboxed Code Service which can be accessed through the Central Administration site in SharePoint.   Open the Central Administration site and go to System Settings and click on Manage Service on server:

image

Check to see if Microsoft SharePoint Foundation Sandboxed Code Service  is running

image

If it is Stopped, then Start the Service and Deploy the Sandboxed Solutions.

Sharepoint webpart maintenance page

Some times while working with the Sharepoint pages ,we are unable to open/edit the page in the sharepoint designer if there is a problem with the webparts(generally script included webparts) . In such cases if we want to remove the issue caused webpart we will go for this webpart maintenance page.

This is a small way/trick to find the webparts on a page in sharepoint with their status.

If your page url is  http://myserver:5485/default.aspx

add ?contents=1 at the end of the url i.e http://myserver:5485/default.aspx?contents=1





From here you can find theat the webpart with name Demo2Tasks is on the page but it is in closed state.

Difference in adding assembly of custom webpart to GAC and BIN:

Before we add our custom webpart to the site we need to deploy the assembly of custom webpart to the BIN directory of Sharepoint site( in which we are going to use this webpart) or GAC.
What is the difference in Deploying the Assembly to GAC or BIN of the site directory?
To GAC (Global Assembly Cache):

Advantages:-
1.If we place our signed dll in GAC it will get full trusted levels by default.
2.And also it get deployed globally so that it can be used in many applications.


Disadvantages:-
1.No site level security(Not to particular site).
2.If any changes made to assembly or rebuilt the assembly we need to force WSS to reload the assembly by restarting the ISS.
To BIN Directory:
Advantages:-
1. If we place the assembly in BIN directory , it is specific to that particular webapplication only.
2. By default this assembly run with partials security and low level CAS (Code Access Security)
3. Administrator can set the required CAS permission levels.For more information
: see
Securing Web Parts in Windows SharePoint Services

Disadvantages:-

1.In order to use the assembly across multiple sites this way will not work .We need to place the assembly in GAC.

Tuesday, November 1, 2011

Adding\Updating\Retriving\SPquery Lookup fields in Sharepoint

Adding a Lookup Item -
SPListItem listItem = myList.Items[0];
listItem["Departments"] = new SPFieldLookupValue(10, “Operations”); // Adding Operations as text and 10 as ID
listItem.Update();
Retrieving Lookup field for an item-
SPListItem listItem = myList.Items[0];
SPFieldLookupValue lookupFieldText = new SPFieldLookupValue(listItem["Departments"].ToString());
string lookUpValue = lookupFieldText .LookupValue;
Updating Lookup field for an item -
SPListItem listItem = myList.Items[0];
SPFieldLookupValue lookupFieldText = new SPFieldLookupValue(listItem ["Departments"].ToString());
lookupFieldText .LookupValue = 11; -> updates the value of the Lookup field for listItem
Retrieving all the values in the Lookup Field -
DropDownList res = new DropDownList();
SPWeb web = SPControl.GetContextWeb(Context);
web = web.ParentWeb;
SPLookupField myLookup = (SPLookupField)web.Fields[str];
SPSite site = web.Site;
SPWeb lookupWeb = site.AllWebs[myLookup.LookupWebId];
SPList lookupList = lookupWeb.Lists[myLookup.LookupList];
foreach(SPListItem lookupItem in lookupList.Items)
{
res.Items.Add(lookupItem[myLookup.LookupField];
}

Finally, SPquery for Lookup field by ID in sharepoint -
<Query>
<Where>
<Eq>
<FieldRef Name=’Departments’ LookupId=’TRUE’ />
<Value Type=’Lookup’>10</Value>
</Eq>
</Where>
</Query>

Monday, October 31, 2011

Create content Type Client object model Sharepoint 2010


1. To create a content type using the client object model in Visual Studio 2010, create a new project (File ➪ New ➪ Project) and select a Console project template.
2. After the project starts, you will add references to the Microsoft.SharePoint.Client.dll and Microsoft.SharePoint.Client.Runtime.dll assemblies located in the 14\ISAPI folder also listed under the .NET component listing in the Add References dialog box.
3. Next, write the code below in you main method. Please note that unlike, server object model, client object model makes use of an Information class that contains the template of the content type. The information class works in a similar manner to the SPContentType class with the exception of the parent ’ s reference; rather than pass in a reference to the parent ’ s content type, client object model code gets the parent ’ s ID.
static void Main(string[] args)
{
// Get a reference to the site collection
ClientContext clientContext = new ClientContext(“http://SPsite”);
Web web = clientContext.Web;
// Load reference to content type collection
ContentTypeCollection contentTypes = web.ContentTypes;
clientContext.Load(contentTypes);
clientContext.ExecuteQuery();
// Create a Content Type Information object
ContentTypeCreationInformation _customcontenttype = new ContentTypeCreationInformation();
customcontenttype.Name = “Custom Content type”;
customcontenttype.ParentContentType = contentTypes.GetById(“ADD PARENT CONTENT TYPE ID”);
customcontenttype.Group = “Custom content type group”;
// Create the content type
ContentType myContentType= contentTypes.Add(customcontenttype);
clientContext.ExecuteQuery();
}
4. After the Information object is completed, a ContentType object is added to the ContentTypes collection that you loaded with the ClientContext using the Information object.

Programmatically create a new content type in sharepoint 2010


Here is the code snippet for creating a content type in a document library using object model.
Public void CreateContentType(string _contentTypename, sting _fullFilePath,SPweb currentWeb)
{
SPFile myFile = currentWeb.GetFile(fullFilePath);
if (currentWeb.AvailableContentTypes[contentTypename] == null)
{
var myContentType = new SPContentType(currentWeb.AvailableContentTypes[new SPContentTypeId("0x0101")], currentWeb.ContentTypes, “contenttypename”)
{
DocumentTemplate = myFile.ServerRelativeUrl,
Description = “My custom Content type”
}
currentWeb.ContentTypes.Add(myContentType);
}
SPDocumentLibrary myDocLib = (SPDocumentLibrary) currentWeb.Lists["doclibname"];
myDocLib.ContentTypesEnabled = true;
myDocLib.ContentTypes.Add(currentWeb.AvailableContentTypes["contenttypename"]);
myDocLib.Update()
}

Enable\Disable Ribbon button by Users Group Sharepoint 2010

In this post we will see a detailed example of how to enable and disable a ribbon button according to the Logged in user’s group. The idea here is to enable the ribbon button if the current user is a part of a pre-specified group (say ListOwners) and disable the same if the user is not one of the added users of the group.
The example uses “EnabledScript” attribute of the CommandUIHandler of the ribbon button to decide whether the button should be enabled or disabled for the loggedin user.
Code Overview -
1.  The below example enables the ribbion button if the current user is a part of a pre-specified group (say ListOwners)
2. The button remains\gets disabled if the user does not exist in the specified group.
3. A separate JavaScript file CheckUserInGroup.js which is deployed in /_layouts/RibbonScripts contains the EnableIfUserInGroup() function. This function is called in EnabledScript and it executes to check if the user exists in the pre-specified group.
Lets Start with creating a Ribbon button first  -
Steps -
1. Create a empty project.
2. Deploy it as a Farm solution.
3. Right click on the feature and click “Add feature”.
4. Right click on the project and add a new “Empty Element” item.
5. Next add the below code to add a custom Ribbon button to your document library.
<Elements xmlns=”http://schemas.microsoft.com/sharepoint/” >
<CustomAction
Id=”ButtonForGroupUsersOnly”
Location=”CommandUI.Ribbon”
RegistrationId=”101″
RegistrationType=”List”
Title=”Owners Group Button”>
<CommandUIExtension>
<CommandUIDefinitions>
<CommandUIDefinition
Location=”Ribbon.Library.ViewFormat.Controls._children”>
<Button Id=”Ribbon.Library.ViewFormat.UsersBtn”
Command=”usersBtnCommand”
LabelText=”Group Users Button”
Image32by32=”/_layouts/1033/IMAGES/buttonIcon.jpg”
TemplateAlias=”o1″ />
</CommandUIDefinition>
</CommandUIDefinitions>
<CommandUIHandlers>
<CommandUIHandler
Command=”usersBtnCommand”
CommandAction=”javascript:OwnerBtnscript();“/> 
–> Refer Your Function here. This runs after your button is clicked
EnabledScript=”javascript:EnableIfUserInGroup();” -> Enable Ribbon function here
</CommandUIHandlers>
</CommandUIExtension>
</CustomAction>
//Referencing the Script
<CustomAction
Id=”OwnersButton.Script”
Location=”ScriptLink”
ScriptSrc =”/_layouts/RibbonScripts/CheckUserInGroup.js”/>
</Elements>
The Group Users Button created in the above code will be in the disabled mode on page load. The code inEnableIfUserInGroup(); will determine if the current  user is added to the specified group and the button needs to be enabled.
The CustomAction ScriptLink refers to the path of the CheckUserInGroup.js file which containsEnableIfUserInGroup(); and other JavaScript functions.
6. Next add a Javascript file in your project “CheckUserInGroup.js” and add it under Layouts -> RibbonScripts folder. Create Layouts folder using Add-> “Sharepoint Layouts Mapped Folder” .
7. Next, the following goes in your CheckUserInGroup.js file
<script src=”/_layouts/SP.js” type=”text/ecmascript”></script>
<script type=”text/javascript”>
// The below is called by EnabledScript in ribbon button
function EnableIfUserInGroup() {
var _userInGroup;
if (UserExistInGroup == null)
CheckUser();
else {
_userInGroup = UserExistInGroup;
UserExistInGroup = null;
return _userInGroup;
}
}
// The below checks if the user exists in the group
function CheckUser()
{
var clientContext = new SP.ClientContext();
var groupCollection = clientContext.get_web().get_siteGroups();
// Get the Our Group’s ID
var _group = groupCollection.getById(10); ->> ID of the Group that we are checking against e.g. ListOwners group
var users = _group.get_users(); ->> Get all Users of the group
clientContext.load(_group);
clientContext.load(users,’Include(loginName)’);
this._currentUser = clientContext.get_web().get_currentUser(); ->> Get current user
clientContext.load(this._currentUser,’Include(loginName)’);
clientContext.executeQueryAsync(Function.createDelegate(this, this.onQuerySucceeded), Function.createDelegate(this, this.onQueryFailed));
RefreshCommandUI(); ->> Refreshes the Ribbon again to pick up the new value for UserExistInGroup
}
//The below Checks  if User is the member of the specified group
function onQuerySucceeded() {
if(users.count >0)
{
UserExistInGroup = false;
for(var i=0; i < users.count; i++)
{
if(users[i].get_loginName() == this._currentUser.get_loginName())
{
UserExistInGroup = true;
}
}
}}
function onQueryFailed(sender, args) {
alert(‘Request failed. ‘ + args.get_message() + ‘\n’ + args.get_stackTrace());
}
</script>
8. Next Build and deploy.

Read a file from Sharepoint document library

The below Code snippet might be helpful when you want to read a text file or a csv file that you uploaded in your document library via code.
I had a csv file with three columns; and I wanted to extract the data and add them into a list as an new item.
Code : The code reads each line of the csv file and then split the entries(columns) by “,” . If you have a text file then you can either split by space or by characters whatever is your requirement.
string line;
StreamReader file;
string contents = string.Empty;
SPFile spfile = properties.ListItem.File;
if (spfile.Exists)
{
string filePath = oWeb.Url + spfile.ServerRelativeUrl; -> oWeb is SPWeb instance
file = new StreamReader(spfile.OpenBinaryStream());
while ((line = file.ReadLine()) != null) -> Reading line by line of the csv file
{
char[] splitter = { ‘,’ };
String[] Array = line.ToString().Split(splitter);
// Now my Array has all the columns of the first line. I then added it to a new list as an item
using (SPSite oSiteCollection = new SPSite(SiteID))
{
using (SPWeb oWeb = oSiteCollection.OpenWeb(WebID))
{
SPList myList = oWeb.Lists["My Custom List"];
SPItem newEntry = myList.Items.Add();
newEntry["Col1"] = Array[0];
newEntry["Col2"] = Array[1];
newEntry["Col3"] = Array[2];
newEntry.Update();
myList.Update();
}}

Create a Custom Timer Job in SharePoint 2010

1. Open Visual Studio 2010 and select File –> New –Project…image
2. In the New Project window, under Installed Templates, select SharePoint –> 2010 and select Empty SharePoint Project. Give the project a Name and click OK.image
3. Enter the URL for SharePoint local site, check the Deploy as a farm solution, and click Finish.image
4. Create a new class.  Right click on the project in the Solution Explorer window and select Add –New Item…image
5. In the Add New Item window, under Installed Templates, select Visual C# –Code and select Class.  Give the class a name and click OK.image
6. The new class needs to inherit from the Microsoft.SharePoint.Administration.SPJobDefinition class. Copy and paste the following code, which creates a the constructors, overrides the Execute() method, and inherits theSPJobDefinition class: (Note: In this code example, an item is added to a SharePoint list every time the Execute() method is called.  The list called “ListTimerJob” must reside within SharePoint.)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
using Microsoft.SharePoint;
using Microsoft.SharePoint.Administration;
 
namespace UpshotSP
{
    class ListTimerJob : SPJobDefinition
    {
         public ListTimerJob()
 
            : base()
        {
 
        }
 
        public ListTimerJob(string jobName, SPService service, SPServer server, SPJobLockType targetType)
 
            : base(jobName, service, server, targetType)
        {
 
        }
 
        public ListTimerJob(string jobName, SPWebApplication webApplication)
 
            : base(jobName, webApplication, null, SPJobLockType.ContentDatabase)
        {
 
            this.Title = "List Timer Job";
 
        }
 
        public override void Execute(Guid contentDbId)
        {
 
            // get a reference to the current site collection's content database
 
            SPWebApplication webApplication = this.Parent as SPWebApplication;
 
            SPContentDatabase contentDb = webApplication.ContentDatabases[contentDbId];
 
            // get a reference to the "ListTimerJob" list in the RootWeb of the first site collection in the content database
 
            SPList Listjob = contentDb.Sites[0].RootWeb.Lists["ListTimerJob"];
 
            // create a new list Item, set the Title to the current day/time, and update the item
 
            SPListItem newList = Listjob.Items.Add();
 
            newList["Title"] = DateTime.Now.ToString();
 
            newList.Update();
 
        }
    }
}
7. Add a Feature to the solution by right clicking on Features in the Solution Explorer window and selecting Add Feature.image
8. Right click on Feature1 and select Add Event Receiver.image
9.  A new class is created that handles the feature’s events.  Copy and paste the following code, which handles theFeatureActivated event, installing the custom timer job, and handles the FeatureDeactivating event, uninstalling the custom timer job:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
namespace UpshotSP.Features.Feature1
{
[Guid("9a724fdb-e423-4232-9626-0cffc53fb74b")]
public class Feature1EventReceiver : SPFeatureReceiver
    {
        const string List_JOB_NAME = "ListLogger";
        // Uncomment the method below to handle the event raised after a feature has been activated.
 
        public override void FeatureActivated(SPFeatureReceiverProperties properties)
        {
            SPSite site = properties.Feature.Parent as SPSite;
 
            // make sure the job isn't already registered
 
            foreach (SPJobDefinition job in site.WebApplication.JobDefinitions)
            {
 
                if (job.Name == List_JOB_NAME)
 
                    job.Delete();
 
            }
 
            // install the job
 
            ListTimerJob listLoggerJob = new ListTimerJob(List_JOB_NAME, site.WebApplication);
 
            SPMinuteSchedule schedule = new SPMinuteSchedule();
 
            schedule.BeginSecond = 0;
 
            schedule.EndSecond = 59;
 
            schedule.Interval = 5;
 
            listLoggerJob.Schedule = schedule;
 
            listLoggerJob.Update();
 
        }
 
        // Uncomment the method below to handle the event raised before a feature is deactivated.
 
        public override void FeatureDeactivating(SPFeatureReceiverProperties properties)
        {
            SPSite site = properties.Feature.Parent as SPSite;
 
            // delete the job
 
            foreach (SPJobDefinition job in site.WebApplication.JobDefinitions)
            {
 
                if (job.Name == List_JOB_NAME)
 
                    job.Delete();
 
            }
 
        }
 
    }
 
}
10. Select the appropriate scope where the new feature will be activated.  Double click Feature1.Feature in theSolution Explorer window and choose the desired Scope from the dropdown menu.image
11. Deploy the solution by right clicking on the project in the Solution Explorer window and selecting Deploy.image
12. Navigate to the SharePoint “ListTimerJob” list and verify that a new item has been added with the current day/time as the title. (Note: The custom timer job , and many other services, can be modified within Central Administration site.)
13. Finished!