DotNetNuke, HttpContext & Scheduler
This post resolves an issue with the HttpContext in a scheduled task. I had created a function that deleted the users from a portal. The problem was that I could not invoke to UserController because the application crash throwing an “Object reference not set to an instance of an object” Exception.
The reason is the invocation to UserController needs to get the HttpContext and it does not exist during the execution of a scheduler task. The solution consists is create an HttpContext and use it. In order to do I get the code from this post and translate to C#.
public class SchedulerHttpContext
{
private static string appPhysicalDir;
public static void setHttpContextWithSimulatedRequest()
{
string appVirtualDir = "/";
if (appPhysicalDir == null)
{
if (Thread.GetDomain().GetData(".appPath") != null)
{
appPhysicalDir = Thread.GetDomain().GetData(".appPath").ToString();
}
else
{
throw new Exception("Error 1: CRASH!");
}
}
if (appPhysicalDir.Length == 0)
{
if (Thread.GetDomain().GetData(".appPath") != null)
{
appPhysicalDir = Thread.GetDomain().GetData(".appPath").ToString();
}
else
{
throw new Exception("Error 2: CRASH!");
}
}
Thread.GetDomain().SetData(".appPath", null);
string page = ((string)(System.Web.HttpRuntime.AppDomainAppVirtualPath + "/default.aspx")).TrimStart("/".ToCharArray());
string query = "";
StringWriter output = new StringWriter();
SimpleWorkerRequest workerRequest = new SimpleWorkerRequest(appVirtualDir, appPhysicalDir, page, query, output);
HttpContext.Current = new HttpContext(workerRequest);
}
}
When I need to retrieve the user information I only have to invoke to SchedulerHttpContext.setHttpContextWithSimulatedRequest() at the beginning. Here you can see an example of a SchedulerClient:
public class CleanUsers : DotNetNuke.Services.Scheduling.SchedulerClient
{
public CleanUsers(DotNetNuke.Services.Scheduling.ScheduleHistoryItem objScheduleHistoryItem)
: base()
{
this.ScheduleHistoryItem = objScheduleHistoryItem;
}
public override void DoWork()
{
this.Progressing();
this.ScheduleHistoryItem.AddLogNote("Begin Task!");
SchedulerHttpContext.setHttpContextWithSimulatedRequest();
soSomething(); //doSomething can call to UserController methods
this.ScheduleHistoryItem.AddLogNote("Finished Task");
this.ScheduleHistoryItem.Succeeded = true;
}
}