Take the 2-minute tour ×
SharePoint Stack Exchange is a question and answer site for SharePoint enthusiasts. It's 100% free, no registration required.

I have configured connection string in my IIS since I'm reusing it through my sharepoint solutions and custom services running next to sharepoint sites.

I'm using following snippet throughout my solutions, which works very well:

var connectionStrings = ConfigurationManager.ConnectionStrings;
connectionString = connectionStrings["FooDB"].ConnectionString;

But unfortunately that doesn't work for my custom sharepoint job, throwing exception Object reference not set to an instance of an object.. I suppose it is happening because job is executed by OWSTIMER process and not w3wp. How one can get around this issue?

share|improve this question
add comment

3 Answers 3

up vote 1 down vote accepted

You can open web.config in your timer job. How could you do it you can read this post. But the approach with property of timer job is easily. )

share|improve this answer
    
I like this approach more, since for it's more flexible. When I decide to change connection string, I don't have to manually update job properties. Whenever web.config gets updated, change is available in job. –  jjczopek Feb 1 '12 at 2:09
add comment

You can use job properties to pass connection string. In FeatureActivated you can install and set your job schedule, also you can set job properties like this:

YOUR_JOB_OBJECT.Properties.Add("connectionString", YOUR_CONNECTIONSTRING_OBJECT);

and then in your job class (the one that inherits from SPJobDefinition) you can get this property in Execute method like this:

public override void Execute(Guid targetInstanceId) {

      string _cString=this.Properties["connectionString"].ToString();   

    }
share|improve this answer
add comment

Since your code is executing in the timer process, the CongfigurationManager instance isn't pulling from the web.config of the web application. It is pulling from the config for the timer service. This config file is located at {SharePointRoot}\BIN\OWSTIMER.EXE.CONFIG. You could put your connection strings in here as well and your above code should work.

There is another method you can use but I am less familiar with it. If you get the SPWebApplication instance, you can use the IisSettings property to find the path on disk to the web.config. You could either read it as XML or pass into the ConfigurationManager constructor (I believe it's an option).

share|improve this answer
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.