NullReferenceException when calling CustomerContext from Scheduled job

Patrick van Kleef
Member since: 2011
 

Hi,

I have an sceduledTask configured in EPiServer CMS 6.1.379.0 to export Customers from EPiServer Commerce 1 R2 SP2.
It doesn't matter which method i call on the CustomerContext, they all throw an NullReferenceException when i run this task from the EPiServer CMS backend by pressing the button to start the task manually.

StackTrace:
at Mediachase.BusinessFoundation.Data.Business.BusinessManager.Execute(Request request)
at Mediachase.BusinessFoundation.Data.Business.BusinessManager.List(String metaClassName, FilterElement[] filters)
at Mediachase.Commerce.Customers.CustomerContext.<InnerGetAllContacts>d__40.MoveNext()
at System.Linq.Buffer`1..ctor(IEnumerable`1 source)
at System.Linq.Enumerable.ToArray[TSource](IEnumerable`1 source)
at Mediachase.Commerce.Customers.CustomerContext.<GetAllContacts>b__3f()
at Mediachase.Commerce.Customers.CustomerContext.GetCachedValue(String key, TimeSpan timeout, Func`1 cachedValueGetter)
at Mediachase.Commerce.Customers.CustomerContext.GetAllContacts()
at EPiServer.Business.Commerce.Sample.SceduledTasks.ExportCustomers.Execute() in D:\xxxxx:line xx

My code snippet:

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Web;
using System.Xml;
using EPiServer.BaseLibrary.Scheduling;
using EPiServer.PlugIn;
using Mediachase.BusinessFoundation.Data;
using Mediachase.BusinessFoundation.Data.Business;
using Mediachase.Commerce.Customers;
using log4net;
using log4net.Repository.Hierarchy;

namespace EPiServer.Business.Commerce.Sample.SceduledTasks
{
	[ScheduledPlugIn(DisplayName = "Export customers")]
	public class ExportCustomers : JobBase
	{
		public ExportCustomers() : base()
		{
			IsStoppable = false;
		}

		public override string Execute()
		{
			IEnumerable<CustomerContact> searchResult = CustomerContext.Current.GetAllContacts();
		}
	}
}

I hope someone has a solution how to work around this NullReferenceException, but any help would be greatly appreciated!

Patrick

#65069 Jan 18, 2013 16:17
  • Hiep Dinh To
    Member since: 2010
     

    You need to initialize SqlContext like below before calling your code because in Episerver Schedule job, it's null.

    SqlContext.Current = new SqlContext(ConfigurationManager.ConnectionStrings["EcfSqlConnection"].ConnectionString);

    #65097 Jan 21, 2013 10:18
  • Patrick van Kleef
    Member since: 2011
     

    Thanks Hiep Dinh To! 

    Not only the SqlContext.Current was null but also the DataContext.Current.

    When i also added the following line i got my results as expected.

    DataContext.Current = new DataContext(ConfigurationManager.ConnectionStrings["EcfSqlConnection"].ConnectionString);

    Thanks again!

    Patrick

    #65114 Jan 21, 2013 14:06