Tuesday, September 27, 2011

How to programmatically send an email in SharePoint using C#


In this post I will discuss about Sending an e-mail in SharePoint 2010 using C#

public static bool SendMail(string Subject, string Body, bool IsBodyHtml, string From, string To, string Cc, string Bcc)
        {
            bool mailSent = false;
            try
            {
                SmtpClient smtpClient = new SmtpClient();
                smtpClient.Host = SPContext.Current.Site.WebApplication.
                OutboundMailServiceInstance.Server.Address;
                MailMessage mailMessage = new MailMessage(From, To, Subject, Body);
                if (!String.IsNullOrEmpty(Cc))
                {
                    MailAddress CCAddress = new MailAddress(Cc);
                    mailMessage.CC.Add(CCAddress);
                }
                if (!String.IsNullOrEmpty(Bcc))
                {
                    MailAddress BCCAddress = new MailAddress(Bcc);
                    mailMessage.Bcc.Add(BCCAddress);
                }
                mailMessage.IsBodyHtml = IsBodyHtml;
                smtpClient.Send(mailMessage);
                mailSent = true;
            }
            catch (Exception) { return mailSent; }
            return mailSent;
        }

Hope this helps..
Next Post- Programatically set the welcome page in Sharepoint

Wednesday, September 7, 2011

Swap page layout for page,sharepoint 2010

This exercise demonstrates how to change the pagelayout with the new pagelayout.



public static void SwapPageLayout(PublishingWeb publishingWeb, PageLayout oldPageLayout, PageLayout newPageLayout)
        {
            // Replace these variable values and input parameters
            // with your own values.
            //
            // The comment to set when the page is checked in, published, and
            // approved.
            string checkInComment = "Your comments";
            //
            // Validate the input parameters.
            if (null == publishingWeb)
            {
                throw new System.ArgumentNullException("publishingWeb");
            }
            if (null == oldPageLayout)
            {
                throw new System.ArgumentNullException("oldPageLayout");
            }
            if (null == newPageLayout)
            {
                throw new System.ArgumentNullException("newPageLayout");
            }
            // Confirm that the oldPageLayout and newPageLayout are compatible.
            if (oldPageLayout.AssociatedContentType.Id != newPageLayout.AssociatedContentType.Id)
            {
                throw new System.ArgumentException(
                    "The page layouts must render the same type of content",
                    "newPageLayout");
            }

            System.Guid oldPageLayoutId = oldPageLayout.ListItem.File.UniqueId;

            // Set the new PageLayout for all pages that use the old PageLayout.
            PublishingPageCollection publishingPages = publishingWeb.GetPublishingPages();
            foreach (PublishingPage publishingPage in publishingPages)
            {
                if (publishingPage.Layout.ListItem.UniqueId == oldPageLayoutId)
                {
                    if (publishingPage.ListItem.File.CheckOutStatus == SPFile.SPCheckOutStatus.None)
                    {
                        publishingPage.CheckOut();
                    }

                    publishingPage.Layout = newPageLayout;
                    publishingPage.Update();

                    // The PublishingPage has the same SPContentType as its PageLayout.
                    System.Diagnostics.Debug.Assert(
                        publishingPage.ContentType.Parent.Id ==
                        newPageLayout.AssociatedContentType.Id);

                    publishingPage.CheckIn(checkInComment);
                }
            }

        }

Date difference in months asp.net,C#

This exercise will teach how to get the months difference between  From date and  To date.


private static int monthDifference(DateTime startDate, DateTime endDate)
{
int monthsApart = 12 * (startDate.Year - endDate.Year) + startDate.Month - endDate.Month;
return Math.Abs(monthsApart);
}

Hope this helps...

Open Default page based on user rights sharepoint MOSS 2007


 In this exercise we will open a default page based on the user.
Eg:: If user is a Approver we will open review.aspx
and if user is a contributor we will open contribute.aspx

server side code

·         SPWeb spWeb = SPContext.Current.Web;
spWeb.AllowUnsafeUpdates = true;
SPFolder objFolder = spWeb.RootFolder;
objFolder.WelcomePage = "pages/myideas.aspx";
foreach(SPGroup group in spWeb.CurrentUser.Groups)
{
if(group.Name == "IGApprovers")
{
objFolder.WelcomePage = "pages/Review.aspx";
}
else if(group.Name == "IGContributor")
{
objFolder.WelcomePage = "pages/contribute.aspx";
}
}
objFolder.Update();
spWeb.AllowUnsafeUpdates = false;


Client side code:
use the spsecuritytrimmed control

This basically conditionally formats controls on the page dependent on their permission.

You need to copy the redirect page layout and then using Designer edit the copy .

You then need to wrap the each redirector control in spsecuritytrimmed control.  I've never seen this done using a group though(also think about setting the page mode so this only works when in display not in edit)

<SharePoint:SPSecurityTrimmedControl ID="SecurityControl" PermissionContext="CurrentSite"  Permissions="ManagePermissions" runat="server" >
<PublishingWebControls:RedirectControl SecondsBeforeRedirect="5" runat="server"/>
<SharePointWebControls:FormField id="RedirectUrlField" FieldName="RedirectURL" runat="server"/>
</SharePoint:SPSecurityTrimmedControl>



Tuesday, September 6, 2011

How to Create a Custom Timer Job in SharePoint 2010


Creating Custom Timer Job in SharePoint 2010

Quantcast
In this post I will show you how to create Custom Timer Job in SharePoint 2010 but you must know this post is based on Creating Custom SharePoint Timer Jobs ,So let us start
Create Custom List and name it  ListTimerJob

Open Visual Studio 2010 >File > New >Project >SharePoint 2010>Empty SharePoint Project. >Name it Custom_TimerJob>Ok

Check Deploy as farm solution>Finish

create a class that inherits from the Microsoft.SharePoint.Administration.SPJobDefinition class. To implement this class, you need to create a few constructors and override the Execute() method as following

01
namespace DotnetFinder
02
{


03
    class ListTimerJob : SPJobDefinition
04
    {


05
         public ListTimerJob()
06
  


07
            : base()
08
        {


09
  
10
        }

11
  
12
        public ListTimerJob(string jobName, SPService service, SPServer server, SPJobLockType targetType)

13
  
14
            : base(jobName, service, server, targetType)

15
        {
16
  


17
        }
18
  


19
        public ListTimerJob(string jobName, SPWebApplication webApplication)
20
  


21
            : base(jobName, webApplication, null, SPJobLockType.ContentDatabase)
22
        {


23
  
24
            this.Title = "List Timer Job";

25
  
26
        }

27
  
28
        public override void Execute(Guid contentDbId)

29
        {
30
  


31
            // get a reference to the current site collection's content database
32
  


33
            SPWebApplication webApplication = this.Parent as SPWebApplication;
34
  


35
            SPContentDatabase contentDb = webApplication.ContentDatabases[contentDbId];
36
  


37
            // get a reference to the "ListTimerJob" list in the RootWeb of the first site collection in the content database
38
  


39
            SPList Listjob = contentDb.Sites[0].RootWeb.Lists["ListTimerJob"];
40
  


41
            // create a new list Item, set the Title to the current day/time, and update the item
42
  


43
            SPListItem newList = Listjob.Items.Add();
44
  


45
            newList["Title"] = DateTime.Now.ToString();
46
  


47
            newList.Update();
48
  


49
        }
50
}


51
}
As you can see this job just add a new item to a ListTimerJob list every time it’s executed
Now that you have the job built> Right click on the Features >Add Feature

Right click on the Feature1 ” you can rename the Feature1 to any name” > Add Event Receiver

As you can see the event Receiver class inherits from the Microsoft.SharePoint.SPFeatureReceiver and This class handles events raised during feature activation, deactivation, installation, uninstallation, and upgrade. But we only need FeatureActivated & FeatureDeactivated event handler to install/uninstall our custom timer job as following

01
namespace DotnetFinder.Features.Feature1
02
{


03
[Guid("9a724fdb-e423-4232-9626-0cffc53fb74b")]
04
public class Feature1EventReceiver : SPFeatureReceiver

05
    {
06
        const string List_JOB_NAME = "ListLogger";

07
        // Uncomment the method below to handle the event raised after a feature has been activated.
08
  


09
        public override void FeatureActivated(SPFeatureReceiverProperties properties)
10
        {


11
            SPSite site = properties.Feature.Parent as SPSite;
12
  


13
            // make sure the job isn't already registered
14
  


15
            foreach (SPJobDefinition job in site.WebApplication.JobDefinitions)
16
            {


17
  
18
                if (job.Name == List_JOB_NAME)

19
  
20
                    job.Delete();

21
  
22
            }

23
  
24
            // install the job

25
  
26
            ListTimerJob listLoggerJob = new ListTimerJob(List_JOB_NAME, site.WebApplication);

27
  
28
            SPMinuteSchedule schedule = new SPMinuteSchedule();

29
  
30
            schedule.BeginSecond = 0;

31
  
32
            schedule.EndSecond = 59;

33
  
34
            schedule.Interval = 5;

35
  
36
            listLoggerJob.Schedule = schedule;

37
  
38
            listLoggerJob.Update();

39
  
40
        }

41
  
42
        // Uncomment the method below to handle the event raised before a feature is deactivated.

43
  
44
        public override void FeatureDeactivating(SPFeatureReceiverProperties properties)

45
        {
46
            SPSite site = properties.Feature.Parent as SPSite;

47
  
48
            // delete the job

49
  
50
            foreach (SPJobDefinition job in site.WebApplication.JobDefinitions)

51
            {
52
  


53
                if (job.Name == List_JOB_NAME)
54
  


55
                    job.Delete();
56
  


57
            }
58
  


59
}
60
  

61
   }
Before Deploying you should select the right scope of the Feature in other words in which scope you will activate the Feature(Farm,Site,Web,WebApplication) in our case we will activate Feature1 on Site which is mean Site Collection.

Note : if you trying to activate the feature in the wrong scope will get the following error

Now let us deploy our custom timer job >Right Click on Custom_TimerJob project > Click Deploy

Open now your SharePoint site and select ListTimerJob List and you should see something similar to the following image


Our custom timer job is working fine now you can go and check it and modify the schedule as following
Go to SharePoint 2010 central administration >Monitoring >in the Timer Jobs Section Select Review Job Definitions
and you should See our Custom Timer Job

Click on it and you should see Edit Timer Job Page ,Modify Timer Job schedule based on your requirement
Note : you can also modify schedule of your custom Timer Job from the code but you need to add one of the following class in FeatureActviated Event Handler as following

After Specific Minutes use SPMinuteSchedule class
Hourly use SPHourlySchedule class
Daily use SPDailySchedule class
Weekly use SPWeeklySchedule class
Monthly use SPMonthlySchedule class

Hope this helps...

Popular Posts