Showing posts with label timer jobs. Show all posts
Showing posts with label timer jobs. Show all posts

Monday, April 16, 2012

Access SocialTerms or Tags in custom timer job

Share/Save/Bookmark


Though we thought this could make implementing the functionality very easy, it went through with a lot of research and lessons learnt.

So, what’s the issue?

When accessing the tags/terms(GetTerms) from SocialTagManager it always throw an error “Microsoft.Office.Server.UserProfiles.UserNotFoundException: An error was encountered while retrieving the user profile”. With a common sense we can see that timer jobs run in a different contextual process(owstimer.exe) which is by default configured to be run by networkservice account. So I thought maybe service accounts did not have user profiles and that’s why it threw error.
Now, I navigated to CA and tried to add user profile for networkservice account which threw another error. The whole point that I understand here is service accounts(system,networkservice) cannot have user profiles but only for domain accounts. [Lesson 0]

My common sense strikes again and asks why does it need a userprofile? I just asked to get all tags for a url on which service account cannot be used to Tag.
It’s time to review what MS has done. So I pulled the source revealer, Reflector from the ware house and found the below code in SocialTagManager class


public SocialTerm[] GetTerms(Uri url, int maximumItemsToReturn, SocialItemPrivacy socialItemPrivacy)

{
SocialTerm[] termArray2;
if (null == url)
{
throw new ArgumentNullException("url");
}

if ((maximumItemsToReturn < 0) || (maximumItemsToReturn > 0x3e8))
{
throw new ArgumentOutOfRangeException("maximumItemsToReturn");
}

bool flag = socialItemPrivacy == SocialItemPrivacy.IncludeAllPrivateData;

bool flag2 = socialItemPrivacy == SocialItemPrivacy.IncludeMyPrivateData;

if (flag && !base.IsSocialAdmin)
{
throw new UnauthorizedAccessException();
}

url = AlternateAccessMapping.GetSerializedUrl(url);
using (SqlCommand command = new SqlCommand("dbo.proc_SocialTags_GetTermsForUrl")) // Procedure to get all terms for url from DB
{

command.CommandType = CommandType.StoredProcedure;
command.Parameters.Add("@includePrivate", SqlDbType.Bit).Value = flag;
if (flag2)
{
command.Parameters.Add("@viewer_user_recordID", SqlDbType.BigInt).Value = base.GetCurrentUserProfileRecordId(); // Incudes current user private data
}

…..

….

}

What we can infer from the code is that, when a user attempts to read social data his/her private data(tags/notes) is included the reason why GetTerms(url) is looking for userprofile of the user(networkservice) running the code - [Lesson1]. Found the root cause but what is the solution?

Quickly impersonation came to the mind, and I passed the token of my domain account while instantiating SPSIte object, still no luck but the same error. Again reflecting the DLL’ s I found the below from UserProfiles.UserProfileGlobal class.

[SecurityPermission(SecurityAction.Assert, Flags=SecurityPermissionFlag.ControlPrincipal
internal static string GetCurrentUserName()
{

string user = string.Empty;
HttpContext current = HttpContext.Current; //GOTCHA 1

if (current != null)
{
SPUtility.EnsureAuthentication(SPControl.GetContextWeb(current));

user = current.User.Identity.Name;
if (!current.User.Identity.IsAuthenticated)
{
throw new UnauthorizedAccessException(StringResourceManager.GetString("Exception_UserProfileGlobal_cs35"));
}
}

if ((user == null) || (user.Trim().Length == 0))
{
user = WindowsIdentity.GetCurrent().Name.ToLower(CultureInfo.InvariantCulture); //GOTCHA 2
}

if (!IsWindowsAuth())
{
if (!IsClaimsAuth())
{
user = SPUtility.FormatAccountName(user);
}

else
{
if (!SPClaimProviderManager.IsEncodedClaim(user))
{
user = SPUtility.FormatAccountName(ClaimsProviderConstants.strClaimsAuthMembershipProviderName, user);
}
user = EnsureWindowsLegacyAndClaimsEquivalence(user);
}
}

if (string.IsNullOrEmpty(user))
{
throw new UserProfileException(StringResourceManager.GetString("Exception_UserProfileGlobal_cs36"));
}
return user;
}

Ah, so that is how it’s getting the current user, which has always been the windows identity(code line labeled, GOTCHA 2) responsible for running the OWSTIMER process because HttpContext is always null in this case. As HttPContext is null, the impersonation code introduced by us will never gonna work. – [Lesson 2]
Since then I hated networkService and the object model for SocialData, being said that I could not wind this up concluding it’s not possible.

With no other option left, I have configured(SharePoint 2010 Timer->properties->logon Tab) my domain account(layman terms, account that has sharepoint userprofile) to run the OWSTIMER.EXE under services.msc. Restart timer service and IIS.

With no surprise, an error again but a new one, this time it threw the below error while instantiating SocailTagManager itself.

“Object reference could not be found at - at Microsoft.Office.Server.Administration.UserProfileApplicationProxy.get_ApplicationProperties().”

Even after using reflector, I could not find a clue but after gooogling, I came to know that I missed restarting the application service. [Lesson 3]

Now the error makes some sense for me. With an excitement I restarted User Profile Application service(CA->Manage Services on Server) and BRAVO, I nailed all the errors and it’s working. If you still did not get it working, you may need to try changing the account(in inetmgr) that runs the application pool responsible for User profile service application.

Though I found it working, I’m not sure on the best practice or the impact of configuring a non-service account to run the services.

UPDATE : Lately i learnt that socialterms can be accessed from timer job/console application(where httpcontext is null by default) by populating the context explicitly as below.

HttpRequest request = new HttpRequest("", http://teamsite, "");

HttpContext.Current = new HttpContext(request,
new HttpResponse(new StringWriter(CultureInfo.CurrentCulture)));
HttpContext.Current.Items["HttpHandlerSPWeb"] = web;

WindowsIdentity wi = WindowsIdentity.GetCurrent();
typeof(WindowsIdentity).GetField("m_name", BindingFlags.NonPublic | BindingFlags.Instance)
.SetValue(wi, user.LoginName);
HttpContext.Current.User = new GenericPrincipal(wi, new string[0]);
WindowsIdentity wi2 = WindowsIdentity.GetCurrent();

SocialCommentManager socialCommentManager = new SocialCommentManager(
SPServiceContext.GetContext(HttpContext.Current));

Though i have not tried hands on, i see the above solution promising. Actual reference can be found here.
I appreciate MS for leaving such puzzles in the code ;) …LOL


Subscribe

Saturday, November 14, 2009

Default timer jobs for Office SharePoint Server 2007

Share/Save/Bookmark

The following table lists the default timer jobs for Microsoft Office SharePoint Server 2007.

Timer job titleDescriptionSchedule type

Application Server Administration Service Timer Job

Manages shared service instances that may perform highly privileged operations. Requires that the SharePoint Administration service is running. The Search service instance is managed by this job on deployments other than stand-alone server deployments.

Minutes

Application Server Timer Job

Manages shared service instances that do not perform highly privileged operations. The Search service instance is managed by this job on stand-alone server deployments.

Minutes

Bulk Workflow Task Processing

Processes bulk workflow task completion.

Daily

CEIP Data Collection

Gathers farm data for the Customer Experience Improvement Program.

Daily

Change Log

Documents changes to sites and pages in a Web application since the last time that the timer job was run.

Daily

Child Farm Content Source Discovery

Created on every farm but runs only on farms designated as child farms. Discovers Web applications on child farms, and registers them with the Shared Services Provider (SSP) database on the parent farm.

15 minutes

Database Statistics

Updates SQL Server query optimization statistics for content databases. This job was updated significantly in Microsoft Office SharePoint Server 2007 with Service Pack 2 (SP2) to also rebuild database indexes. The job performs the following tasks:

  • If you have not installed Office SharePoint Server 2007 with SP2, the job updates the query optimization statistics by performing a full scan of key tables every time that it runs, which can be resource-intensive.

  • If you have installed Office SharePoint Server 2007 with SP2:

    • The job updates the query optimization statistics by sampling key tables every time that it runs, instead of performing a full scan.

    • If you are running SQL Server 2005 or SQL Server 2008, the job rebuilds all indexes in the content databases every time that it runs.

    • If you are running an Enterprise edition of SQL Server 2005 or SQL Server 2008, the job rebuilds most indexes online.

    • If you are running a Standard edition of SQL Server 2005 or SQL Server 2008, the job rebuilds the indexes offline.

    • If you are running SQL Server 2000, the job does not rebuild any indexes.

Weekly

Dead Site Delete

When auto site cleanup is enabled, sites that have not been used in a certain period of time are deleted.

Daily

Disk Quota Warning

Looks for sites that have exceeded the storage quota.

Daily

Document Conversions

Schedules and begins the document conversions.

Minutes

Expiration Policy

Enumerates list items and looks for those with an expiration date that has already occurred. For those items, runs disposition processing. Disposition processing most often results in deleting items, but it can perform other actions, such as processing disposition workflows.

Daily

Hold Processing and Reporting

Generates a hold report by enumerating items in a hold and doing an update on them to remove them from hold, as appropriate.

Daily

Immediate Alerts

Sends out immediate and scheduled alerts.

Minutes

Indexing Schedule Manager on SQL Server

Starts scheduled crawls.

Minutes

Information Management Policy

Loops through all the lists in the site collections in a Web application and collects policy and usage data.

Daily

Licensing Synchronizer Job

Synchronizes trial expiration time licensing information to the configuration database.

Hourly

My Site Cleanup Job

When a user is deleted, starts a workflow on that user’s My Site. The default behavior is to send an e-mail message to the manager with a link to the deleted user’s site. The e-mail message contains a request to the manager to move any documents or data that the manager wants to preserve, because the site might be deleted in the future.

Hourly

Office SharePoint Server CEIP Data Collection

Gathers farm data for the Customer Experience Improvement Program.

Daily

Office SharePoint Usage Analytics Log Import

Imports the usage logs for each site.

Daily

Office SharePoint Usage Analytics Processing

Processes the logs and aggregates usage data for each site.

Minutes

Profile Synchronization

Synchronizes user information in content databases from user profile data.

Hourly

Quick Profile Synchronization

Synchronizes user information for newly added users in content databases from user profile data.

Minutes

Records Center Processing

Checks for records that have been added to a Records Center DropOffLibrary and routes files that have been saved there.

Daily

Recycle Bin

Looks for content in the Recycle Bins and moves it to the next stage or deletes it.

Daily

Scheduled Approval

Looks for content that is scheduled for approval and moves it to the next stage in the process.

Minutes

Scheduled Page Review

Looks for pages that are scheduled for review and moves them to the next stage in the process.

Daily

Scheduled Unpublish

Looks for content that is scheduled to be unpublished and removes it.

Minutes

Search and Process

Processes a search result that is scoped to a site collection and puts search results on hold.

Daily

Shared Services Provider Synchronizing Job

Automatically configures an SSP. If the status of the SSP is Provisioning, it changes the status to Online. If the status is Online, then it synchronizes.

Minutes

Shared Services Timer Job

Schedules jobs that are registered by SSPs. The job runs in the security context of the SSP Web service account.

Minutes

SharePoint Services Search Refresh

Validates the configuration of the WSS Search service.

Minutes

SharePoint Worker Process Group Update

Updates the WSS_ADMIN_WPG group.

One-time

SKU Type Synchronization Job

Synchronizes version-licensing information (Standard or Enterprise) to the configuration database.

Hourly

Synchronization Scheduler

Applies changes in configured schedules to the Profile Synchronization and Quick Profile Synchronization jobs.

Minutes

Usage Analysis

Processes the logs and aggregates usage data for each site.

Daily

Variations Propagate Page Job Definition

Creates or updates peer pages of the source page that has been approved or published in all target labels. The resulting peer pages are in an unpublished state.

Minutes

Variations Propagate Site Job Definition

Creates peer sites of the source site that has been created in all target labels.

Minutes

Windows SharePoint Services Watson Policy Update

Sets or removes a registry key to enable automatic Watson uploads.

One-time

Workflow

Processes workflow events that are in the scheduled items table, such as delays.

Minutes

Workflow Auto Cleanup

Deletes tasks and instances in the workflow instance table for workflows that have been marked completed more than ndays in the past, where n is specified in the workflow association. Crawls through tasks and the workflow instance table.

Daily

Workflow Failover

Processes events for workflows that have failed and are marked to be retried

Minutes

Site Collection: Delete

Added in the April Cumulative Update to perform gradual deletion of site collections. When an operation uses gradual deletion, a site collection is immediately marked as deleted, which prevents any further access to its content. The data in the deleted site collection is then deleted gradually over time by this timer job instead of all at once, which reduces its effect on Office SharePoint Server 2007 and SQL Server performance. Gradual deletion is available in the stsadm -o deletesite andstsadm -o mergecontentdbs operations.

Daily


Subscribe