0

How can I achive copying list items through timer job? I tried the below code with no success.

.cs file

        using System;
        using System.Collections.Generic;
        using System.Linq;
        using System.Text;
        using Microsoft.SharePoint;
        using Microsoft.SharePoint.Administration;
        namespace TimerCopyListItems
        {
            public class CopyListItems : SPJobDefinition
            {
                public const string JOB_NAME = "CopyItems";

                public CopyListItems() : base()
                { 

                }

                public CopyListItems(string jobName, SPService service, SPServer server, SPJobLockType targetType) : base(jobName, service, server, targetType)
                {
                }


                // public CopyListItems(string jobName, SPWebApplication webApp) : base(jobName, webApp, null, SPJobLockType.ContentDatabase) 
                // {
                //    this.Title = JOB_NAME;
                //}

                public CopyListItems(string jobName, SPWebApplication webApplication) : base(jobName, webApplication, null, SPJobLockType.ContentDatabase)
                { this.Title = JOB_NAME; }

                public override void Execute(Guid contentDbId)
                {
                    // System.Diagnostics.Debugger.Break();
                    //System.Diagnostics.Debug.Assert(false);

                    SPWebApplication webApplication = this.Parent as SPWebApplication; 
                    SPContentDatabase contentDb = webApplication.ContentDatabases[contentDbId];
                    SPList SourceList = contentDb.Sites[0].RootWeb.Lists["SourceList"];
                    SPList DestinationList = contentDb.Sites[0].RootWeb.Lists["DestinationList"];
         CopyList(SourceList, DestinationList);
                    //using (SPSite site = this.WebApplication.Sites[0])
                    //{
                    //    using (SPWeb oSPWeb = site.OpenWeb())
                    //    {

                    //        SPList SourceList = oSPWeb.Lists["SourceList"];
                    //        SPList DestinationList = oSPWeb.Lists["DestinationList"];
                    //        CopyList(SourceList, DestinationList);

                    //    }
                    //}
                }

                private static void CopyList(SPList SourceList, SPList DestinationList)
                {
                    foreach (SPListItem sourceItem in SourceList.Items)
                    {
                        if (DestinationList != null)
                        {
                            SPListItem destItem = DestinationList.Items.Add();

                            foreach (SPField field in sourceItem.Fields)
                            {
                                if (!field.ReadOnlyField && !field.Hidden && field.InternalName != "Attachments")
                                {
                                    if (destItem.Fields.ContainsField(field.InternalName))
                                    {
                                        destItem[field.InternalName] = sourceItem[field.InternalName];
                                    }
                                }
                            }

                            destItem.Update();
                        }
                    }
                }
            }
        }

Feature Receiver

    using System;
    using System.Runtime.InteropServices;
    using System.Security.Permissions;
    using Microsoft.SharePoint;
    using Microsoft.SharePoint.Security;
    using Microsoft.SharePoint.Administration;

    namespace TimerCopyListItems.Features.Feature1
    {
        /// <summary>
        /// This class handles events raised during feature activation, deactivation, installation, uninstallation, and upgrade.
        /// </summary>
        /// <remarks>
        /// The GUID attached to this class may be used during packaging and should not be modified.
        /// </remarks>

        [Guid("f1ca780c-d875-4260-a2ba-e8635de924bb")]
        public class Feature1EventReceiver : SPFeatureReceiver
        {
            // const string List_JOB_NAME = "MovingListItems";
            // 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;
                //remove the job if it already exists
                foreach (SPJobDefinition job in site.WebApplication.JobDefinitions)
                {
                    if (job.Name == CopyListItems.JOB_NAME)
                        job.Delete();
                }

                // create the job
                CopyListItems emailJob = new CopyListItems(CopyListItems.JOB_NAME, site.WebApplication);
                SPMinuteSchedule schedule = new SPMinuteSchedule();
                schedule.BeginSecond = 0;
                schedule.EndSecond = 59;
                schedule.Interval = 1;
                emailJob.Schedule = schedule;
                emailJob.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;
                foreach (SPJobDefinition job in site.WebApplication.JobDefinitions)
                {
                    if (job.Name == CopyListItems.JOB_NAME)
                        job.Delete();
                }
            }
        }
    }
1

Hi i was able to acheive the same by following the below url. Hope it may help for some one (http://adicodes.com/timer-job-in-sharepoint-for-specific-site/).

Below is my code how i have acheive it. **

  • CS file

**

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.SharePoint;
using Microsoft.SharePoint.Administration;
using System.Data;
using System.IO;


namespace TaskMove
{
   public  class TaskMoveSchedular:SPJobDefinition
    {
       //public const string jobName = "CompletedProjectsJob";
       SPWeb mySiteWeb;
       string mySiteUrl = "";
       public TaskMoveSchedular() : base() 
       {

       }


       public TaskMoveSchedular(SPWebApplication webApplication)
           : base("TimerJob", webApplication, null, SPJobLockType.Job)
        {
            Title = "TimerJob";
        }



       public override void Execute(Guid targetInstanceId)
       {
           if (!string.IsNullOrEmpty(this.Properties["mySiteUrl"].ToString()))
           {
               mySiteUrl = this.Properties["mySiteUrl"].ToString();
           }

           if (!string.IsNullOrEmpty(mySiteUrl))
           {
               using (SPSite mySite = new SPSite(mySiteUrl))
               {
                   using (mySiteWeb = mySite.OpenWeb())
                   {
                       //provide your logic here for the site

                       SPList Sourcelist = mySiteWeb.Lists.TryGetList("MasterTask");
                       SPList DestinationList = mySiteWeb.Lists.TryGetList("Tasks");

                          CopyList(Sourcelist, DestinationList);
                   }
               }
           }

       }

       private static void CopyList(SPList SourceList, SPList DestinationList)
       {
           foreach (SPListItem sourceItem in SourceList.Items)
           {
               if (DestinationList != null)
               {
                   SPListItem destItem = DestinationList.Items.Add();
                   foreach (SPField field in sourceItem.Fields)
                   {
                       if (!field.ReadOnlyField && !field.Hidden && field.InternalName != "Attachments")
                       {
                           if (destItem.Fields.ContainsField(field.InternalName))
                           {
                               destItem[field.InternalName] = sourceItem[field.InternalName];

                               //if (destItem[field.InternalName].ToString() == "Title")
                               //{
                               //    DateTime currenttime = System.DateTime.Today;
                               //    destItem[field.InternalName] = sourceItem[field.InternalName]+currenttime.ToString();

                               //}
                           }
                       }
                   }
                   destItem.Update();
               }
           }
       }


    }
}

Event Reciver

using System;
using System.Runtime.InteropServices;
using System.Security.Permissions;
using Microsoft.SharePoint;
using Microsoft.SharePoint.Security;
using Microsoft.SharePoint.Administration;

namespace TaskMove.Features.Feature1
{
    /// <summary>
    /// This class handles events raised during feature activation, deactivation, installation, uninstallation, and upgrade.
    /// </summary>
    /// <remarks>
    /// The GUID attached to this class may be used during packaging and should not be modified.
    /// </remarks>

    [Guid("0669a7a2-586e-45c7-b327-5125381b6493")]
    public class Feature1EventReceiver : SPFeatureReceiver
    {


        public override void FeatureActivated(SPFeatureReceiverProperties properties)
        {
            try
            {

                SPSecurity.RunWithElevatedPrivileges(delegate()
                {
                    SPWeb web = properties.Feature.Parent as SPWeb;
                    web.AllowUnsafeUpdates = true;
                    SPWebApplication webApp = web.Site.WebApplication;
                    foreach (SPJobDefinition job in webApp.JobDefinitions)
                        if (job.Name == "TimerJob") job.Delete();

                    string key = "mySiteUrl";
                    string value = web.Url;

                    TaskMoveSchedular tmrJob = new TaskMoveSchedular(webApp);
                    //remove the key if already exists
                    bool isKeyExists = tmrJob.Properties.ContainsKey(key);
                    if (isKeyExists)
                    {
                        tmrJob.Properties.Remove(key);
                    }
                    tmrJob.Properties.Add(key, value);
                    SPMinuteSchedule schedule = new SPMinuteSchedule();

                    schedule.BeginSecond = 0; //to start immediately
                    schedule.EndSecond = 59; //use this if timer job is to end after some seconde
                    schedule.Interval = 5; //number of minutes
                    tmrJob.Schedule = schedule;
                    tmrJob.Update();

                    web.AllowUnsafeUpdates = false;
                });
            }
            catch (Exception ex)
            {
                //log exception if any
            }
        }

        public override void FeatureDeactivating(SPFeatureReceiverProperties properties)
        {
            try
            {
                //remove the scheduled job
                SPSecurity.RunWithElevatedPrivileges(delegate()
                 {
                     SPWeb web = properties.Feature.Parent as SPWeb;
                     web.AllowUnsafeUpdates = true;
                     SPWebApplication webApp = web.Site.WebApplication;
                     foreach (SPJobDefinition job in webApp.JobDefinitions)
                         if (job.Name == "TimerJob") job.Delete();
                     web.AllowUnsafeUpdates = false;
                 });
            }
            catch (Exception ex)
            {
                //log exception if any
            }
        }
    }
}
0

Plz try with Id instead of InternalName

Like this

destItem[field.Id] = sourceItem[field.Id];

Hope it helps

0

I would also wrap the destItem[fieldname] = sourceItem[fieldname]; line in a try/catch block. I don't see any reason off-hand why that would fail, but little weird things abound that can throw errors and, as it stands right now, one single failure to read one column will kill the entire program.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.