Fixing Access Denied Errors With SharePoint 2010 Timer Jobs

It is important to realize before we get started that this error was also present within SharePoint 2007. When creating timer jobs, it is important to understand the relationships between the SPSecurity.RunWithElevatedPrivileges method and the associated SPWebApplication object. When using SPSecurity.RunWithElevatedPrivileges, it will not allow modification of the SPWebApplication since it is persisted to the configuration database. However, other proxy objects are exempt from this such as SPSite ‘s and SPWeb ‘s. SPSecurity.RunWithElevatedPrivileges allows the elevation to just the content database, NOT the configuration database (which has the SPWebApplication property bag) which is generally more locked down.

The easiest way to fix this is to impersonate the user account for proxy objects (assuming you are using a current context to reference the application property) with an account that has the wss_content_application_pools database role for the config database since this will have elevated rights for stored procedures and what not. This will allow you to modify your timer jobs easily. If you want to be really lazy, just use the same account as the central admin app pool which inherently provides the required access to the configuration database.

Share

Runtime Instance From Mole Types

This is more of a quick tip than anything in regards to moles. When using moles, sometimes you might be find yourself executing a safe cast, or trying to, between your Mole and runtime instance type. Why would this happen? Well consider the following simple code:

[csharp]
TypeX x = ReturnAType() as TypeX;
[/csharp]

Now this is a problem with moles, because the typecast will fail resulting in x being null. However, the solution is just to stick with variant types when using Moled types, each moled type will have a property representing the Instance (the property is actually the MoledType.Instance property) which will expose the runtime instance. The cool part is the case is built automagically by the compiler :-)

Share