コード例 #1
0
ファイル: TimerJob.cs プロジェクト: gandjustas/sp-samples
 public override void ProcessSite(SPSite site, SPJobState jobState)
 {
     tju = new TimerJobUtility(Constants.TimerJobName, jobState);
     tju.DisableEventFiring      = false;
     tju.CancellationGranularity = IterationGranularity.List;
     tju.ResumeGranularity       = IterationGranularity.List;
     tju.ProcessSite(site, ProcessSite);
 }
コード例 #2
0
ファイル: SubWorkItemJob.cs プロジェクト: wkmalek/SPSolution
        protected override bool ProcessWorkItem(SPContentDatabase contentDb, SPWorkItemCollection workItems,
                                                SPWorkItem workItem, SPJobState jobState)
        {
            if (workItem == null)
            {
                throw new ArgumentException("workItem is null");
            }
            try
            {
                using (SPSite site = new SPSite(workItem.SiteId))
                {
                    using (SPWeb web = site.OpenWeb(workItem.WebId))
                    {
                        try
                        {
                            //TODO CODE HERE
                            SPList     list     = web.Lists[workItem.ParentId];
                            SPListItem listItem = list.GetItemByUniqueId(workItem.ItemGuid);

                            SPList subList  = web.Lists["SubscriberList"];
                            SPList elements = web.Lists["SubscribeElementList"];
                            //TODO Rewrite to caml
                            for (int i = 0; i < subList.ItemCount; i++)
                            {
                                SPListItem item = subList.Items[i];
                                if (workItem.UserId == (int)item["User"])
                                {
                                    SPListItem newSubItem = elements.Items.Add();
                                    newSubItem["User"]   = workItem.UserId;
                                    newSubItem["NewsID"] = listItem["ID"];
                                    newSubItem["Readed"] = false;
                                    newSubItem.Update();
                                }
                            }
                        }
                        catch (Exception e)
                        {
                            throw e;
                        }
                        finally
                        {
                            workItems.SubCollection(site, web, 0, (uint)workItems.Count).DeleteWorkItem(workItem.Id);
                        }
                    }
                }
            }
            catch (Exception e)
            {
                throw e;
            }

            return(true);
        }
コード例 #3
0
 /// <summary>
 /// Execute method implementation
 /// </summary>
 public override void Execute(SPJobState jobState)
 {
     ArgumentValidator.IsNotNull(jobState, "JobState");
     JobState = jobState;
     if (ServiceApplication.Status == SPObjectStatus.Online)
     {
         if (!jobState.ShouldStop)
         {
             DoExecute();
         }
     }
 }
コード例 #4
0
        protected override bool ProcessWorkItem(SPContentDatabase contentDatabase,
                                                Microsoft.SharePoint.SPWorkItemCollection workItems,
                                                Microsoft.SharePoint.SPWorkItem workItem, SPJobState jobState)
        {
            // process the workItem
            using (var site = new SPSite(workItem.SiteId))
            {
                using (var web = site.OpenWeb(workItem.WebId))
                {
                    //var logEntry = IronLogger.Entry.Base64Deserialize(workItem.TextPayload);

                    if (true)//logEntry.Level <= WebLogLevel(web))
                    {
                        SPDocumentLibrary logLib = null;
                        try
                        {
                            logLib = (SPDocumentLibrary)web.GetList(web.ServerRelativeUrl + "/" + IronConstant.IronLogsListPath);
                        }
                        catch (Exception ex)
                        {
                            throw new SPException("Couldn't find IronLog document library", ex);
                            throw ex;
                        }
                        if (logLib != null)
                        {
                            var logFileCandidates = logLib.GetItems(LogFileQuery(2));
                            if (logFileCandidates.Count > 0)
                            {
                                var logFile = logFileCandidates[0].File;
                                AppendToFile(logFile, workItem.TextPayload);
                            }
                            else
                            {
                                var url = DateTime.Now.ToString("s").Replace(":", "_");
                                url = string.Format("{0}.log", url);

                                logLib.RootFolder.Files.Add(url, GetBytes(workItem.TextPayload));
                            }
                        }
                    }
                    // delete the workItem after we've processed it
                    workItems.SubCollection(site, web, 0,
                                            (uint) workItems.Count).DeleteWorkItem(workItem.Id);
                }
            }

            // returning true allows the timer job to process additional items in the queue
            // returning false will end this occurance of the timer job
            return true;
        }
コード例 #5
0
        public override void Execute(SPJobState jobState)
        {
            string webUrl = String.Empty;
            try
            {
                if (this.Properties["webUrl"] == null)
                {
                    throw new ArgumentNullException("Properties['webUrl']","The 'webUrl' property is missing from timer job instance. Install job again.");
                }
                webUrl = this.Properties["webUrl"].ToString();
                var mediaProcessor = new MediaProcessor(webUrl, MediaConfig.FromConfigStore(webUrl));
                logger.LogToOperations(LogCategories.Media, EventSeverity.Information, "Executing Tellago-MediaProcessingTimerJob in webUrl '{0}' (Server: '{1}', Service '{2}', WebApplication: '{3}')", webUrl, Server, Service, WebApplication);
                mediaProcessor.ProcessMedia();
            }
            catch (Exception ex)
            {
                logger.LogToOperations(ex, LogCategories.Media, EventSeverity.Error, "Error executing TRS-MediaProcessingTimerJob in web '{0}'", webUrl);

                throw;
            }
        }
コード例 #6
0
 protected override bool ProcessWorkItem(SPContentDatabase contentDatabase, SPWorkItemCollection workItems, SPWorkItem workItem, SPJobState jobState)
 {
     tju = new TimerJobUtility(Constants.TimerJobName, jobState);
     return(tju.ProcessWorkItem(workItems, workItem, wiJobState, ProcessWorkItemCore));
 }
コード例 #7
0
        protected override bool ProcessWorkItems(SPContentDatabase contentDatabase, SPWorkItemCollection workItems, SPJobState jobState)
        {
            foreach (SPWorkItem workItem in workItems)
            {
                if (workItem != null)
                {
                    try
                    {
                        SPSite site = new SPSite(workItem.SiteId);
                        IWebSiteControllerModule module = null;
                        WebSiteControllerRule    rule   = null;
                        bool _deleted = false;
                        //int ItemID = workItem.ItemId;

                        if (workItem.ItemId > 0)
                        {
                            rule = WebSiteControllerConfig.GetRule(contentDatabase.WebApplication, workItem.ItemGuid);
                        }
                        else
                        {
                            module = WebSiteControllerConfig.GetModule(contentDatabase.WebApplication, workItem.ItemGuid);
                        }

                        if (rule != null)
                        {
                            WebSiteControllerConfig.RemoveRule(rule.Id);
                            _deleted = true;
                        }

                        if (workItem.ItemId < 0 || _deleted)
                        {
                            string[] data                = workItem.TextPayload.Split(new char[] { '#' });
                            string   parameterRule       = data[0];
                            string   parameterProperties = data[1];
                            string[] rules               = parameterRule.Split(new char[] { ';' });

                            string url      = rules[0];
                            bool   disabled = bool.Parse(rules[1]);
                            bool   ssl      = bool.Parse(rules[2]);
                            int    sequence = int.Parse(rules[3]);

                            WebSiteControllerPrincipalType principalType = WebSiteControllerPrincipalType.None;

                            if (!String.IsNullOrEmpty(rules[4]))
                            {
                                principalType = (WebSiteControllerPrincipalType)Enum.Parse(typeof(WebSiteControllerPrincipalType), rules[4]);
                            }
                            string principal = rules[5];

                            string ruletype = string.Empty;

                            if (module != null || String.IsNullOrEmpty(rule.RuleType))
                            {
                                ruletype = module.RuleType;
                            }
                            else if (rule != null && ruletype == string.Empty)
                            {
                                ruletype = rule.RuleType;
                            }

                            string[]  properties = parameterProperties.Split(new char[] { ';' }, StringSplitOptions.RemoveEmptyEntries);
                            Hashtable props      = new Hashtable();

                            foreach (string prop in properties)
                            {
                                try
                                {
                                    if (!string.IsNullOrEmpty(prop))
                                    {
                                        string[] keyval = prop.Split(new char[] { ':' });
                                        props.Add(keyval[0], keyval[1]);
                                    }
                                }
                                catch { };
                            }

                            if (_deleted && workItem.ItemId != 1)
                            {
                                WebSiteControllerConfig.AddRule(contentDatabase.WebApplication,
                                                                site.Url + "/",
                                                                url,
                                                                rule.RuleType,
                                                                rule.Principal,
                                                                rule.PrincipalType,
                                                                disabled,
                                                                ssl,
                                                                sequence,
                                                                props
                                                                );
                            }

                            if (workItem.ItemId == -1)
                            {
                                WebSiteControllerConfig.AddRule(contentDatabase.WebApplication,
                                                                site.Url + "/",
                                                                url,
                                                                ruletype,
                                                                principal,
                                                                principalType,
                                                                disabled,
                                                                ssl,
                                                                sequence,
                                                                props
                                                                );
                            }
                        }
                    }
                    catch (Exception ex)
                    {
                        ex.ToString();
                        //throw (ex);
                    }
                    finally
                    {
                        DeleteWorkItem(workItems, workItem);
                        //using (SPSite site = new SPSite(workItem.SiteId))
                        //{

                        //    using (SPWeb web = site.OpenWeb(workItem.WebId))
                        //    {
                        //        SPWorkItemCollection deletableCollection = workItems.SubCollection(site, web, (uint)workItem.i, (uint)itemIndex + 1);
                        //        deletableCollection.DeleteWorkItem(currentItem.Id);

                        //        //workItems.CompleteInProgressWorkItems(workItem.ParentId, workItem.Type, workItem.BatchId);
                        //        //workItems.SubCollection(site, web, 0, (uint)workItems.Count).DeleteWorkItem(workItem.Id);

                        //    }

                        //}

                        ////workItems.DeleteWorkItem(workItem.Id);
                    }
                }
            }
            return(true);
        }
        protected override bool ProcessWorkItem(SPContentDatabase contentDatabase, SPWorkItemCollection workItems, SPWorkItem workItem, SPJobState jobState)
        {
            using (var site = new SPSite(workItem.SiteId))
            {
                using (SPWeb web = site.OpenWeb(workItem.WebId))
                {
                    workItems.SubCollection(site, web, 0, (uint)workItems.Count).DeleteWorkItem(workItem.Id);
                }
            }

            try
            {
                var stringSeparators = new string[] { "-#####-" };

                string[] cmds = workItem.TextPayload.Split(stringSeparators, StringSplitOptions.RemoveEmptyEntries);

                SPWebApplication webApp = SPWebApplication.Lookup(new Uri(cmds[0]));

                SPIisSettings iis = webApp.IisSettings[SPUrlZone.Default];

                string port;

                if (iis.ServerBindings.Count > 0)
                {
                    port = iis.ServerBindings[0].Port.ToString();
                }
                else
                {
                    string path = iis.Path.ToString();
                    port = path.Substring(path.LastIndexOf('\\') + 1);
                }

                if (!string.IsNullOrEmpty(port))
                {
                    port = ":" + port;
                }

                var reloadCacheTimerJob = new ReloadCacheTimerJob("Oceanik.ReloadCacheJob" + Guid.NewGuid(), webApp, null, SPJobLockType.None)
                {
                    Schedule = new SPOneTimeSchedule(DateTime.Now)
                };

                string command = "http://localhost" + port + cmds[1];
                reloadCacheTimerJob.Properties.Add("CMD", command);

                reloadCacheTimerJob.Update();

                SPSecurity.RunWithElevatedPrivileges(() => EventLog.WriteEntry("ReloadCacheJobDefinition.ProcessWorkItem.ExecuteCommand", command, EventLogEntryType.Information));
            }
            catch (Exception ex)
            {
                SPSecurity.RunWithElevatedPrivileges(() => EventLog.WriteEntry("ReloadCacheJobDefinition.ProcessWorkItem", ex.Message, EventLogEntryType.Error));
            }

            return(true);
        }
コード例 #9
0
        protected override bool ProcessWorkItem(SPContentDatabase contentDatabase, 
            SPWorkItemCollection workItems, SPWorkItem workItem, SPJobState jobState)
        {
            Stopwatch sw = Stopwatch.StartNew(); //used to time how long the export took
            bool processingAlready = false;
            
            try
            {
                if (workItem != null)
                {
                    //process the workItem
                    using (SPSite site = new SPSite(workItem.SiteId))
                    {
                        using (SPWeb web = site.OpenWeb(workItem.WebId))
                        {
                            // processing logic
                            // 1. SET GlymaExport list Item to ExportStatus.Processing
                            // 2. START export based on type in GlymaExport list item
                            // 3. STORE the export in the GlymaExport list against the item as an attachment
                            // 4. SET GlymaExport list item to ExportStatus.Completed
                            SPList exportsList = null;
                            SPListItem exportItem = null;
                            try
                            {
                                exportsList = web.Lists[workItem.ParentId];
                                exportItem = exportsList.GetItemByUniqueId(workItem.ItemGuid);
                                if (exportItem != null)
                                {
                                    string exportStatus = exportItem["ExportStatus"] as string;
                                    if (exportStatus == ExportStatus.Scheduled.ToString())
                                    {
                                        // If the export was still marked as scheduled then set it to processing
                                        WriteExportStatus(workItem, ExportStatus.Processing);

                                        exportItem = exportsList.GetItemByUniqueId(workItem.ItemGuid);

                                        if (exportItem != null)
                                        {
                                            // read the type of export that we should produce
                                            ExportType exportType = (ExportType)Enum.Parse(typeof(ExportType), exportItem["ExportType"] as string);
                                            MapType mapType = (MapType)Enum.Parse(typeof(MapType), exportItem["MapType"] as string);

                                            Dictionary<string, string> exportProperties = null;
                                            string exportPropertiesStr = exportItem["ExportProperties"] as string;
                                            if (!string.IsNullOrEmpty(exportPropertiesStr) && exportPropertiesStr.Trim() != string.Empty)
                                            {
                                                try
                                                {
                                                    ExportPropertiesDictionary exportDict = new ExportPropertiesDictionary(exportPropertiesStr);
                                                    exportProperties = exportDict as Dictionary<string, string>;
                                                }
                                                catch (XmlSchemaValidationException)
                                                {
                                                    exportProperties = null;
                                                }
                                            }

                                            bool useVerboseLogging = false;
                                            if (exportProperties != null)
                                            {
                                                if (exportProperties.ContainsKey("Verbose"))
                                                {
                                                    if (exportProperties["Verbose"].ToLower() == "true")
                                                    {
                                                        useVerboseLogging = true;
                                                    }
                                                }
                                            }

                                            if (useVerboseLogging)
                                            {
                                                LogMessage(workItem, "Creating Map Manager for the web: {0}.", web.Url);
                                            }

                                            // create the appropriate IExportUtility for the ExportType
                                            MapManagerFactory mapManagerFactory = new MapManagerFactory();
                                            IMapManager mapManager = mapManagerFactory.GetMapManager(web);
                                            if (mapManager != null)
                                            {
                                                if (useVerboseLogging)
                                                {
                                                    LogMessage(workItem, "Created Map Manager for the web: {0}.", web.Url);
                                                }

                                                ExportUtilityFactory exportUtilityFactory = new ExportUtilityFactory(mapManager);
                                                IExportUtility exportUtility = exportUtilityFactory.CreateExportUtility(mapType, exportType);

                                                if (exportUtility != null)
                                                {
                                                    if (useVerboseLogging)
                                                    {
                                                        LogMessage(workItem, "Created Export Utility for {0} map type to {1}.", mapType.ToString(), exportType.ToString());
                                                    }

                                                    exportItem = exportsList.GetItemByUniqueId(workItem.ItemGuid);
                                                    if (exportItem != null)
                                                    {
                                                        Guid rootMapUid = Guid.Empty;
                                                        Guid domainUid = Guid.Empty;
                                                        try
                                                        {
                                                            string rootMapUidValue = exportItem["RootMapUid"] as string;
                                                            string domainUidValue = exportItem["DomainUid"] as string;
                                                            domainUid = new Guid(domainUidValue);
                                                            rootMapUid = new Guid(rootMapUidValue);
                                                        }
                                                        catch (Exception ex)
                                                        {
                                                            //The GUIDs were not parsed correctly
                                                        }
                                                        if (rootMapUid != Guid.Empty && domainUid != Guid.Empty)
                                                        {
                                                            //The export utility will do the grunt work and provide a URL to the temp file created
                                                            GlymaExportUserState userState = new GlymaExportUserState(workItem);
                                                            userState.UseVerboseLogging = useVerboseLogging; //store the level of logging to use in the event handlers
                                                            exportUtility.ExportCompleted += exportUtility_ExportCompleted;
                                                            exportUtility.ProgressChanged += exportUtility_ProgressChanged;
                                                            exportUtility.ExceptionRaised += exportUtility_ExceptionRaised;

                                                            if (useVerboseLogging)
                                                            {
                                                                LogMessage(workItem, "Starting export.");
                                                            }

                                                            exportUtility.ExportMap(domainUid, rootMapUid, exportProperties, new List<Guid>(), userState);

                                                            if (useVerboseLogging)
                                                            {
                                                                LogMessage(workItem, "Waiting for export to complete.");
                                                            }

                                                            // Wait for the export to complete (up to the timeout)
                                                            bool signalled = userState.Completed.WaitOne(TIMEOUT_MS);
                                                            if (!signalled)
                                                            {
                                                                if (useVerboseLogging)
                                                                {
                                                                    LogMessage(workItem, "The export timed out after {0}ms", TIMEOUT_MS);
                                                                }
                                                                // The timeout occurred so don't process the completed or progress changed events
                                                                exportUtility.ExportCompleted -= exportUtility_ExportCompleted;
                                                                exportUtility.ProgressChanged -= exportUtility_ProgressChanged;
                                                                exportUtility.ExceptionRaised -= exportUtility_ExceptionRaised;
                                                            }
                                                        }
                                                        else
                                                        {
                                                            throw new Exception(string.Format("The DomainUid and/or RootMapUid were not valid Guid's. DomainUid: {0} RootMapUid: {1}.", domainUid.ToString(), rootMapUid.ToString()));
                                                        }
                                                    }
                                                }
                                                else
                                                {
                                                    throw new Exception(string.Format("Unable to create export utility for the export type: {0}.", exportType.ToString()));
                                                }
                                            }
                                            else
                                            {
                                                throw new Exception(string.Format("Unable to build an IMapManager for the current SPWeb. {0}", mapManagerFactory.ErrorMessage));
                                            }
                                        }
                                    }
                                    else if (exportStatus == ExportStatus.Processing.ToString())
                                    {
                                        //shouldn't do anything unless it's scheduled.
                                        processingAlready = true;
                                    }
                                }
                                else
                                {
                                    throw new Exception("The Export Job did not exist in the list.");
                                }
                            }
                            catch (TargetInvocationException tiex)
                            {
                                if (workItem != null)
                                {
                                    WriteExportStatus(workItem, ExportStatus.Error);
                                    LogMessage(workItem, "Error during export: {0}", tiex.Message);

                                    if (tiex.InnerException != null)
                                    {
                                        LogMessage(workItem, "Inner Exception({0}): {1}.\r\nStackTrace: {2}", tiex.InnerException.GetType().ToString(), tiex.InnerException.Message, tiex.InnerException.StackTrace);
                                    }
                                }
                            }
                            catch (Exception ex)
                            {
                                //exception handling
                                if (workItem != null)
                                {
                                    WriteExportStatus(workItem, ExportStatus.Error);
                                    LogMessage(workItem, "Error during export: {0}.", ex.Message);
                                }
                            }
                            finally
                            {
                                if (!processingAlready)
                                {
                                    // delete the workItem after we've processed it
                                    workItems.SubCollection(site, web, 0, (uint)workItems.Count).DeleteWorkItem(workItem.Id);
                                }

                                //Update the progress of the timer job
                                Progress += (100 / workItems.Count); //estimate only, some maps will export faster than others and different types may export faster
                                if (Progress > 100)
                                {
                                    Progress = 100;
                                }
                                this.UpdateProgress(Progress); //The base classes timer job's overall progress
                                
                                if (!processingAlready) //this is if the timer job ran and started processing the item that was already being processed
                                {
                                    exportItem = exportsList.GetItemByUniqueId(workItem.ItemGuid);
                                    if (exportItem != null)
                                    {
                                        string exportStatus = exportItem["ExportStatus"] as string;
                                        if (exportStatus == ExportStatus.Processing.ToString())
                                        {
                                            //if it's still processing and at this point then something has failed.
                                            WriteExportStatus(workItem, ExportStatus.Error);
                                            LogMessage(workItem, "The export failed as it was still in a processing state when it had apparently completed.");
                                        }

                                        LogMessage(workItem, "Completed in {0:0.000}s.", sw.Elapsed.TotalSeconds);//add in a metric for how long the export took (successful or failure)
                                    }
                                 }
                            }
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                //exception handling
                throw new Exception("Failed to while processing Glyma Export Work Item Timer Job.", ex);
            }

            return true;
        }
コード例 #10
0
 protected override bool ProcessWorkItems(SPContentDatabase contentDatabase,
     SPWorkItemCollection workItems, SPJobState jobState)
 {
     Progress = 0;
     return base.ProcessWorkItems(contentDatabase, workItems, jobState);
 }
コード例 #11
0
        protected override bool ProcessWorkItem(SPContentDatabase contentDatabase,
                                                Microsoft.SharePoint.SPWorkItemCollection workItems,
                                                Microsoft.SharePoint.SPWorkItem workItem, SPJobState jobState)
        {
            // process the workItem
            using (var site = new SPSite(workItem.SiteId))
            {
                using (var web = site.OpenWeb(workItem.WebId))
                {
                    //var logEntry = IronLogger.Entry.Base64Deserialize(workItem.TextPayload);

                    if (true)//logEntry.Level <= WebLogLevel(web))
                    {
                        SPDocumentLibrary logLib = null;
                        try
                        {
                            logLib = (SPDocumentLibrary)web.GetList(web.ServerRelativeUrl + "/" + IronConstant.IronLogsListPath);
                        }
                        catch (Exception ex)
                        {
                            throw new SPException("Couldn't find IronLog document library", ex);
                            throw ex;
                        }
                        if (logLib != null)
                        {
                            var logFileCandidates = logLib.GetItems(LogFileQuery(2));
                            if (logFileCandidates.Count > 0)
                            {
                                var logFile = logFileCandidates[0].File;
                                AppendToFile(logFile, workItem.TextPayload);
                            }
                            else
                            {
                                var url = DateTime.Now.ToString("s").Replace(":", "_");
                                url = string.Format("{0}.log", url);

                                logLib.RootFolder.Files.Add(url, GetBytes(workItem.TextPayload));
                            }
                        }
                    }
                    // delete the workItem after we've processed it
                    workItems.SubCollection(site, web, 0,
                                            (uint)workItems.Count).DeleteWorkItem(workItem.Id);
                }
            }

            // returning true allows the timer job to process additional items in the queue
            // returning false will end this occurance of the timer job
            return(true);
        }
コード例 #12
0
        protected override bool ProcessWorkItem(SPContentDatabase contentDatabase,
                                                SPWorkItemCollection workItems, SPWorkItem workItem, SPJobState jobState)
        {
            Stopwatch sw = Stopwatch.StartNew(); //used to time how long the export took
            bool      processingAlready = false;

            try
            {
                if (workItem != null)
                {
                    //process the workItem
                    using (SPSite site = new SPSite(workItem.SiteId))
                    {
                        using (SPWeb web = site.OpenWeb(workItem.WebId))
                        {
                            // processing logic
                            // 1. SET GlymaExport list Item to ExportStatus.Processing
                            // 2. START export based on type in GlymaExport list item
                            // 3. STORE the export in the GlymaExport list against the item as an attachment
                            // 4. SET GlymaExport list item to ExportStatus.Completed
                            SPList     exportsList = null;
                            SPListItem exportItem  = null;
                            try
                            {
                                exportsList = web.Lists[workItem.ParentId];
                                exportItem  = exportsList.GetItemByUniqueId(workItem.ItemGuid);
                                if (exportItem != null)
                                {
                                    string exportStatus = exportItem["ExportStatus"] as string;
                                    if (exportStatus == ExportStatus.Scheduled.ToString())
                                    {
                                        // If the export was still marked as scheduled then set it to processing
                                        WriteExportStatus(workItem, ExportStatus.Processing);

                                        exportItem = exportsList.GetItemByUniqueId(workItem.ItemGuid);

                                        if (exportItem != null)
                                        {
                                            // read the type of export that we should produce
                                            ExportType exportType = (ExportType)Enum.Parse(typeof(ExportType), exportItem["ExportType"] as string);
                                            MapType    mapType    = (MapType)Enum.Parse(typeof(MapType), exportItem["MapType"] as string);

                                            Dictionary <string, string> exportProperties = null;
                                            string exportPropertiesStr = exportItem["ExportProperties"] as string;
                                            if (!string.IsNullOrEmpty(exportPropertiesStr) && exportPropertiesStr.Trim() != string.Empty)
                                            {
                                                try
                                                {
                                                    ExportPropertiesDictionary exportDict = new ExportPropertiesDictionary(exportPropertiesStr);
                                                    exportProperties = exportDict as Dictionary <string, string>;
                                                }
                                                catch (XmlSchemaValidationException)
                                                {
                                                    exportProperties = null;
                                                }
                                            }

                                            bool useVerboseLogging = false;
                                            if (exportProperties != null)
                                            {
                                                if (exportProperties.ContainsKey("Verbose"))
                                                {
                                                    if (exportProperties["Verbose"].ToLower() == "true")
                                                    {
                                                        useVerboseLogging = true;
                                                    }
                                                }
                                            }

                                            if (useVerboseLogging)
                                            {
                                                LogMessage(workItem, "Creating Map Manager for the web: {0}.", web.Url);
                                            }

                                            // create the appropriate IExportUtility for the ExportType
                                            MapManagerFactory mapManagerFactory = new MapManagerFactory();
                                            IMapManager       mapManager        = mapManagerFactory.GetMapManager(web);
                                            if (mapManager != null)
                                            {
                                                if (useVerboseLogging)
                                                {
                                                    LogMessage(workItem, "Created Map Manager for the web: {0}.", web.Url);
                                                }

                                                ExportUtilityFactory exportUtilityFactory = new ExportUtilityFactory(mapManager);
                                                IExportUtility       exportUtility        = exportUtilityFactory.CreateExportUtility(mapType, exportType);

                                                if (exportUtility != null)
                                                {
                                                    if (useVerboseLogging)
                                                    {
                                                        LogMessage(workItem, "Created Export Utility for {0} map type to {1}.", mapType.ToString(), exportType.ToString());
                                                    }

                                                    exportItem = exportsList.GetItemByUniqueId(workItem.ItemGuid);
                                                    if (exportItem != null)
                                                    {
                                                        Guid rootMapUid = Guid.Empty;
                                                        Guid domainUid  = Guid.Empty;
                                                        try
                                                        {
                                                            string rootMapUidValue = exportItem["RootMapUid"] as string;
                                                            string domainUidValue  = exportItem["DomainUid"] as string;
                                                            domainUid  = new Guid(domainUidValue);
                                                            rootMapUid = new Guid(rootMapUidValue);
                                                        }
                                                        catch (Exception ex)
                                                        {
                                                            //The GUIDs were not parsed correctly
                                                        }
                                                        if (rootMapUid != Guid.Empty && domainUid != Guid.Empty)
                                                        {
                                                            //The export utility will do the grunt work and provide a URL to the temp file created
                                                            GlymaExportUserState userState = new GlymaExportUserState(workItem);
                                                            userState.UseVerboseLogging    = useVerboseLogging; //store the level of logging to use in the event handlers
                                                            exportUtility.ExportCompleted += exportUtility_ExportCompleted;
                                                            exportUtility.ProgressChanged += exportUtility_ProgressChanged;
                                                            exportUtility.ExceptionRaised += exportUtility_ExceptionRaised;

                                                            if (useVerboseLogging)
                                                            {
                                                                LogMessage(workItem, "Starting export.");
                                                            }

                                                            exportUtility.ExportMap(domainUid, rootMapUid, exportProperties, new List <Guid>(), userState);

                                                            if (useVerboseLogging)
                                                            {
                                                                LogMessage(workItem, "Waiting for export to complete.");
                                                            }

                                                            // Wait for the export to complete (up to the timeout)
                                                            bool signalled = userState.Completed.WaitOne(TIMEOUT_MS);
                                                            if (!signalled)
                                                            {
                                                                if (useVerboseLogging)
                                                                {
                                                                    LogMessage(workItem, "The export timed out after {0}ms", TIMEOUT_MS);
                                                                }
                                                                // The timeout occurred so don't process the completed or progress changed events
                                                                exportUtility.ExportCompleted -= exportUtility_ExportCompleted;
                                                                exportUtility.ProgressChanged -= exportUtility_ProgressChanged;
                                                                exportUtility.ExceptionRaised -= exportUtility_ExceptionRaised;
                                                            }
                                                        }
                                                        else
                                                        {
                                                            throw new Exception(string.Format("The DomainUid and/or RootMapUid were not valid Guid's. DomainUid: {0} RootMapUid: {1}.", domainUid.ToString(), rootMapUid.ToString()));
                                                        }
                                                    }
                                                }
                                                else
                                                {
                                                    throw new Exception(string.Format("Unable to create export utility for the export type: {0}.", exportType.ToString()));
                                                }
                                            }
                                            else
                                            {
                                                throw new Exception(string.Format("Unable to build an IMapManager for the current SPWeb. {0}", mapManagerFactory.ErrorMessage));
                                            }
                                        }
                                    }
                                    else if (exportStatus == ExportStatus.Processing.ToString())
                                    {
                                        //shouldn't do anything unless it's scheduled.
                                        processingAlready = true;
                                    }
                                }
                                else
                                {
                                    throw new Exception("The Export Job did not exist in the list.");
                                }
                            }
                            catch (TargetInvocationException tiex)
                            {
                                if (workItem != null)
                                {
                                    WriteExportStatus(workItem, ExportStatus.Error);
                                    LogMessage(workItem, "Error during export: {0}", tiex.Message);

                                    if (tiex.InnerException != null)
                                    {
                                        LogMessage(workItem, "Inner Exception({0}): {1}.\r\nStackTrace: {2}", tiex.InnerException.GetType().ToString(), tiex.InnerException.Message, tiex.InnerException.StackTrace);
                                    }
                                }
                            }
                            catch (Exception ex)
                            {
                                //exception handling
                                if (workItem != null)
                                {
                                    WriteExportStatus(workItem, ExportStatus.Error);
                                    LogMessage(workItem, "Error during export: {0}.", ex.Message);
                                }
                            }
                            finally
                            {
                                if (!processingAlready)
                                {
                                    // delete the workItem after we've processed it
                                    workItems.SubCollection(site, web, 0, (uint)workItems.Count).DeleteWorkItem(workItem.Id);
                                }

                                //Update the progress of the timer job
                                Progress += (100 / workItems.Count); //estimate only, some maps will export faster than others and different types may export faster
                                if (Progress > 100)
                                {
                                    Progress = 100;
                                }
                                this.UpdateProgress(Progress); //The base classes timer job's overall progress

                                if (!processingAlready)        //this is if the timer job ran and started processing the item that was already being processed
                                {
                                    exportItem = exportsList.GetItemByUniqueId(workItem.ItemGuid);
                                    if (exportItem != null)
                                    {
                                        string exportStatus = exportItem["ExportStatus"] as string;
                                        if (exportStatus == ExportStatus.Processing.ToString())
                                        {
                                            //if it's still processing and at this point then something has failed.
                                            WriteExportStatus(workItem, ExportStatus.Error);
                                            LogMessage(workItem, "The export failed as it was still in a processing state when it had apparently completed.");
                                        }

                                        LogMessage(workItem, "Completed in {0:0.000}s.", sw.Elapsed.TotalSeconds);//add in a metric for how long the export took (successful or failure)
                                    }
                                }
                            }
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                //exception handling
                throw new Exception("Failed to while processing Glyma Export Work Item Timer Job.", ex);
            }

            return(true);
        }
コード例 #13
0
 protected override bool ProcessWorkItems(SPContentDatabase contentDatabase,
                                          SPWorkItemCollection workItems, SPJobState jobState)
 {
     Progress = 0;
     return(base.ProcessWorkItems(contentDatabase, workItems, jobState));
 }
コード例 #14
0
        protected override bool ProcessWorkItems(SPContentDatabase contentDatabase, SPWorkItemCollection workItems, SPJobState jobState)
        {
            foreach (SPWorkItem workItem in workItems)
            {
                if (workItem != null)
                {
                    if (workItem.ItemGuid != Guid.Empty)
                    {
                        WebSiteControllerConfig.RemoveModule(contentDatabase.WebApplication, workItem.ItemGuid);
                    }

                    if (!String.IsNullOrEmpty(workItem.TextPayload))
                    {
                        try
                        {
                            string[] param = workItem.TextPayload.Split(new char[] { ';' });

                            Assembly assembly   = System.Reflection.Assembly.Load(param[1]);
                            Type     moduletype = null;
                            Type[]   types      = assembly.GetTypes();

                            foreach (Type type in types)
                            {
                                string name = type.FullName;
                                if (name.Equals(param[0]))
                                {
                                    moduletype = type;
                                    break;
                                }
                            }

                            if (moduletype != null)
                            {
                                SPWebApplication WebApp = contentDatabase.WebApplication;
                                //WebSiteControllerConfig config = WebApp.GetChild<WebSiteControllerConfig>(WebSiteControllerConfig.OBJECTNAME);
                                IWebSiteControllerModule module = (IWebSiteControllerModule)Activator.CreateInstance(moduletype);
                                WebSiteControllerConfig.AddModule(WebApp, module, param[0] + "," + param[1]);
                            }
                        }
                        catch (Exception ex)
                        {
                            ex.ToString();
                            //throw (ex);
                        }
                        finally
                        {
                            DeleteWorkItem(workItems, workItem);

                            /*
                             * using (SPSite site = new SPSite(workItem.SiteId))
                             * {
                             *
                             *  using (SPWeb web = site.OpenWeb(workItem.WebId))
                             *  {
                             *      workItems.CompleteInProgressWorkItems(workItem.ParentId, workItem.Type, workItem.BatchId);
                             *      //workItems.SubCollection(site, web, 0, (uint)workItems.Count).DeleteWorkItem(workItem.Id);
                             *
                             *  }
                             *
                             * }
                             */
                        }
                    }
                }
            }
            return(true);
        }