Creating Workspaces without a HttpContext

This section explains how to create MatchPoint Workspaces which depend on the HttpContext.Current via custom PowerShell scripts or from timer jobs.

Motivation

Sometimes it's not possible to create MatchPoint Workspaces without a HttpContext. This is for example the case when the corresponding workspace template contains expressions which use SPHelper.GetCurrentWeb() or similar calls which depend on the current context. However, by using the MPContextFaker it is possible to fake / emulate the HttpContext.Current, the SPContext.Current and the MPInstanceScope.Current with a custom URL.

MPContextFaker class

This class creates a fake HttpContext.Current with a passed in request URL and also opens and sets the current SPSite / SPWeb (SPContext.Current) with this URL.

The class contains various constructors which allows to create the fake contexts in different ways. See the API documentation for details.

Since the class is disposable, all assignments to the "current contexts" (e.g. HttpContext.Current) as well the opening of the site / web will be reverted / disposed upon disposal of the instance.

C# example

It is recommended to use using(IDisposable) block to handle MPContextFaker lifecycle and revert all changes automatically.

using (var context = new MPContextFaker(requestUrl))
{
  var template = WorkspaceTemplateConfiguration.GetTemplate(templateId, MPInstance.Current);

  Workspace workspace = new Workspace(template)
    {
      ["Title"] = "Fake context created workspace",
      ["CreationDate"] = DateTime.Now,
    };

  // set a global "expression variable" (this is useful if expressions within
  // the template contain this variable and therefore won't work without it)
  context.SetGlobalVariable("MyVariable", "Foo");

  workspace.Update();
}

The example above presents method to create workspace in a custom TimerJob. Please note that although WorkspaceTemplateConfiguration.GetTemplate method requires MPInstance.Current as a parameter, it is already taken care of during MPContextFaker initialization and it is possible to access its instance via static field.

PowerShell example

$context = New-Object -TypeName Colygon.MatchPoint.Core.MPContextFaker $requestUrl

$template = [Colygon.MatchPoint.Workspaces.Configuration.WorkspaceTemplateConfiguration] `
  ::GetTemplate($templateId, [Colygon.MatchPoint.Core.MPInstance]::Current)

$workspace = New-Object -TypeName Colygon.MatchPoint.Workspaces.Model.Workspace $template

$workspace["Title"] = "Fake context created workspace"
$workspace["CreationDate"] = [System.DateTime]::Now

# set a global "expression variable" (this is useful if expressions within
# the template contain this variable and therefore won't work without it)
$context.SetGlobalVariable("MyVariable", "Foo");

$workspace.Update()

$context.Dispose()

This PowerShell snippet provides the same functionality as the C# one.

results matching ""

    No results matching ""