using Microsoft.SharePoint;
using Microsoft.SharePoint.Administration;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Configuration;
using System.Web;
using System.Collections.Specialized;
namespace NGOFileDumpProcess
{
class NGOFileDumpTimmerJob: SPJobDefinition
{
public NGOFileDumpTimmerJob()
: base()
{ }
public NGOFileDumpTimmerJob(string jobName, SPService service)
: base(jobName, service,null, SPJobLockType.None)
{
this.Title
= "NGO File Dump Process";
}
public NGOFileDumpTimmerJob(string jobName, SPWebApplication webapp)
: base(jobName,
webapp, null, SPJobLockType.ContentDatabase)
{
this.Title
= " NGO File Dump Process";
}
#region Excute
Method Of Timer Jobs
//
string
qq=System.Configuration.ConfigurationManager.AppSettings["siteURL"];
string siteurl1
= "";
string UrlandDumpLocation
= string.Empty;
public override void Execute(Guid targetInstanceId)
{
try
{
SPWebApplication webApplication
= this.Parent as SPWebApplication;
//
get a reference to the current site collection's content database
SPContentDatabase contentDb
= webApplication.ContentDatabases[targetInstanceId];
//
get a reference to the "site" list in the RootWeb of the first
sitecollection in the content database
string weburl
= contentDb.Sites[0].RootWeb.Url;
//Getting
the List from the Current All Webs
SPList timeerJobList
= webApplication.Sites[0].AllWebs["/GET"].Lists["FileDumpConfigurationSettings"];
//Getting
the SPListItemCollection
SPListItemCollection itemcollection
= timeerJobList.GetItems();
foreach (SPListItem spListItem in itemcollection)
{
if (UrlandDumpLocation
== "")
{
UrlandDumpLocation = spListItem["Title"].ToString().Trim()
+ "|" + spListItem["DumpLocationPath"].ToString().Trim()
+ "|" + spListItem["LibraryName"].ToString().Trim();
}
}
SPSecurity.RunWithElevatedPrivileges(delegate ()
{
DownLoadFiles(UrlandDumpLocation);
});
}
catch (IOException ex)
{
WriteLog(UrlandDumpLocation, " Error in
Function Execute :" + ex.Message);
}
}
public void DownLoadFiles(string UrlandDumpLocation)
{
if (UrlandDumpLocation!="")
{
string siteUrl
= UrlandDumpLocation.Split('|')[0].ToString();
string filePath
= UrlandDumpLocation.Split('|')[1].ToString();
string LibraryName
= UrlandDumpLocation.Split('|')[2].ToString();
//
getting Record of Curret month
//
string Month = DateTime.Now.AddMonths(-1).ToString("MM");
string Month
= DateTime.Now.ToString("MM");
string Year
= DateTime.Now.ToString("yyyy");
//
SPSecurity.RunWithElevatedPrivileges(delegate ()
{
using (SPSite site
= new SPSite(siteUrl))
{
using (SPWeb web
= site.OpenWeb())
{
//
get the required document library
SPList docLib
= web.Lists[LibraryName];
SPListItemCollection items
= docLib.GetItems();
//
code to download documents
//
loop through each item or document in the document library
Boolean Varicreatefile
= false;
if(items.Count>0)
{
foreach (SPListItem item in items)
{
string FolderPathLocation
= "";
//
Access the file
SPFile file
= item.File;
string fileCreationdateMonth
=Convert.ToDateTime(item["Created"].ToString()).ToString("MM");
string fileCreationdateYear
=Convert.ToDateTime(item["Created"].ToString()).ToString("yyyy");
if (Month
== fileCreationdateMonth && Year == fileCreationdateYear)
{
if (file != null)
{
//
retrieve the file as a byte array
try
{
//SPFieldLookupValueCollection
values = new SPFieldLookupValueCollection(item["Location"].ToString());
//
foreach (SPFieldLookupValue value in values)
// {
Varicreatefile
= true;
//Directory.CreateDirectory(filePath
+ value.LookupValue);
Directory.CreateDirectory(filePath);
byte[]
bArray = file.OpenBinary();
//
FolderPathLocation = Path.Combine(filePath + value.LookupValue, file.Name);
FolderPathLocation = Path.Combine(filePath,
file.Name);
//open
the file stream and write the file
using (FileStream fs
= newFileStream(FolderPathLocation, FileMode.Create, FileAccess.ReadWrite))
{
fs.Write(bArray, 0, bArray.Length);
}
// }
}
catch (IOException ex)
{
WriteLog(UrlandDumpLocation, " Error in
DownLoadFiles()" + ex.Message);
}
}
}
}
if (Varicreatefile
== true)
{
WriteLog(UrlandDumpLocation,"File
Dump Process is Successfully");
}
else
{
WriteLog(UrlandDumpLocation, "No Item for
File Dumpimg Process");
}
}
else
{
WriteLog(UrlandDumpLocation, "No Item for
File Dumpimg Process");
}
}
}
});
}
}
public void WriteLog(string UrlandDumpLocation, string strLog)
{
if (UrlandDumpLocation
!= "")
{
string siteurl
= UrlandDumpLocation.Split('|')[0].ToString();
//
Added Code by Ram Vinay Singh on 1 Aug 2016
SPSecurity.RunWithElevatedPrivileges(delegate()
{
using (SPSite oSPsite
= new SPSite(siteurl))
{
//
WriteLog("oSPsite", "oSPsite For WriteLog() Method
");
using (SPWeb oSPWeb
= oSPsite.OpenWeb())
{
//
WriteLog("oSPWeb", "oSPWeb For WriteLog() Method
");
oSPWeb.AllowUnsafeUpdates = true;
//
Fetch the List
SPList list
= oSPWeb.Lists["ErrorLogList"];
//Add
a new item in the List
//
WriteLog("Before Add", "Site Url For WriteLog()
Method ");
SPListItem itemToAdd
= list.Items.Add();
itemToAdd["Title"] = "ErrorLog
_" + System.DateTime.Today.ToString("dd-MM-yyyy");
itemToAdd["ErrorDescription"] =
strLog;
itemToAdd.Update();
//WriteLog("After
Update", "Site Url For WriteLog() Method ");
oSPWeb.AllowUnsafeUpdates = false;
}
}
});
}
}
}
}
#endregion
Add Event Reciever in Feature
using System;
using System.Runtime.InteropServices;
using System.Security.Permissions;
using Microsoft.SharePoint;
using Microsoft.SharePoint.Administration;
namespace NGOFileDumpProcess.Features.NGOFileDumpProcessTimmerJob
{
/// <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("d38cdefb-0535-410c-bcc8-d515748fc7e4")]
public class NGOFileDumpProcessTimmerJobEventReceiver : SPFeatureReceiver
{
const string JobName
= "NGO File Dump Process";
public override void FeatureActivated(SPFeatureReceiverProperties properties)
{
try
{
SPSecurity.RunWithElevatedPrivileges(delegate ()
{
SPWebApplication parentWebApp
= (SPWebApplication)properties.Feature.Parent;
SPSite site
= properties.Feature.Parent as SPSite;
CreateJob(parentWebApp);
});
}
catch (Exception ex)
{
throw ex;
}
}
private bool CreateJob(SPWebApplication site)
{
bool jobCreated
= false;
try
{
NGOFileDumpTimmerJob job
= new NGOFileDumpTimmerJob(JobName,
site);
SPMinuteSchedule schedule
= new SPMinuteSchedule();
schedule.BeginSecond = 0;
schedule.EndSecond = 59;
schedule.Interval = 15;
job.Schedule = schedule;
job.Update();
}
catch (Exception)
{
return jobCreated;
}
return jobCreated;
}
public bool DeleteExistingJob(string jobName, SPWebApplication site)
{
bool jobDeleted
= false;
try
{
foreach (SPJobDefinition job in site.JobDefinitions)
{
if (job.Name
== jobName)
{
job.Delete();
jobDeleted = true;
}
}
}
catch (Exception)
{
return jobDeleted;
}
return jobDeleted;
}
public override void FeatureDeactivating(SPFeatureReceiverProperties properties)
{
lock (this)
{
try
{
SPSecurity.RunWithElevatedPrivileges(delegate ()
{
SPWebApplication parentWebApp
= (SPWebApplication)properties.Feature.Parent;
DeleteExistingJob(JobName, parentWebApp);
});
}
catch (Exception ex)
{
throw ex;
}
}
}
//
Uncomment the method below to handle the event raised after a feature has been
activated.
//public
override void FeatureActivated(SPFeatureReceiverProperties properties)
//{
//}
//
Uncomment the method below to handle the event raised before a feature is
deactivated.
//public
override void FeatureDeactivating(SPFeatureReceiverProperties properties)
//{
//}
//
Uncomment the method below to handle the event raised after a feature has been
installed.
//public
override void FeatureInstalled(SPFeatureReceiverProperties properties)
//{
//}
//
Uncomment the method below to handle the event raised before a feature is
uninstalled.
//public
override void FeatureUninstalling(SPFeatureReceiverProperties properties)
//{
//}
//
Uncomment the method below to handle the event raised when a feature is
upgrading.
//public
override void FeatureUpgrading(SPFeatureReceiverProperties properties, string
upgradeActionName, System.Collections.Generic.IDictionary<string, string>
parameters)
//{
//}
}
}
No comments:
Post a Comment