Tuesday, January 22, 2008

Sharepoint Timerjob: Read the web.config inside a Timer Job

There is no way to get a reference to a SPSite or SPWeb object inside a timerjob. So when you want to store configuration values in the web.config of your Web Application, there is no way to get the Web Application's name to open the web.config with the WebConfigurationManager. I programmed this workaround:

- In the FeatureReceiver of the Timer job, pass the SPSite instance of the site where the feature is activated on, to the constructor of your timer job class:

public override void FeatureActivated(SPFeatureReceiverProperties properties)
{
// Collect the reference to the site from the feature parent that can be SPSite/SPWeb.
using (SPSite site = properties.Feature.Parent.GetType() == typeof(SPSite) ? (SPSite)properties.Feature.Parent : (SPSite)((SPWeb)properties.Feature.Parent).Site)
{

...

MailDateAlertsJob mailDateAlertsTimerJob = new MailDateAlertsJob(SanofiConstants.JOB_NAME, site.WebApplication, properties.Definition.DisplayName, site);

...

}

}

- In the constructur of your Timer job class, you will have a SPSite parameter:

public MailDateAlertsJob(string jobName, SPWebApplication webApp, string featureName, SPSite site)
: base(jobName, webApp, null, SPJobLockType.Job)
{
this.Title = SanofiConstants.JOB_TITLE;
this._siteToHandleActionsOn = site.Url;
}

- The _siteToHandleActionsOn variable holds the url string of the site where your feature is activated on. This variable is defined like this (note the [Persisted] attribute!!):

[Persisted]
private string _siteToHandleActionsOn;

- In the Execute methods of your timer job, you now can open the web configuration of the site:

if (this._siteToHandleActionsOn != null)
{

using (SPSite site = new SPSite(this._siteToHandleActionsOn))
{

...

string appSettingValue = WebConfigurationManager.OpenWebConfiguration("/", site.WebApplication.Name).AppSettings.Settings["key"].Value;

}

}

}

If you have a better solution for this, please let me know ;-)

Saturday, January 5, 2008

Compare Dates in Sharepoint XSL

See http://sharethelearning.blogspot.com/2007/06/comparing-dates-in-sharepoint-xsl.html:

<xsl:if test="number(translate(substring-before(ddwrt:FormatDate(@Date_x0020_Raised ,1053 ,5), ' '), '-', ''))+2 < number(translate(substring-before(ddwrt:TodayIso(), 'T'), '-', ''))">
        <img src="_layouts/images/ewr210s.gif" />
</xsl:if>