Sitecore publish:end and publish:end:remote

In Sitecore, you have several ways of executing code after a publish. The publish:end and publish:end:remote events are the 2 most obvious choices.

There is a little confusion as to when in the publish pipeline these events are fired. In previous versions (prior to Sitecore 7.2), publish:end and publish:end:remote was fired for each language and each target, and publish:complete and publish:complete:remote was fired when the publish job was done. But in later versions, publish:end and publish:end:remote is also only fired once, when the current publish operation is completed.

The :remote events (publish:end:remote and publish:complete:remote) is fired on your remote (content delivery, or CD) servers.

Please note that the EventArgs are not the same for publish:end and publish:end:remote. So to properly handle publish events you need 2 different functions in your code.

To handle the publish:end event, you will need the following function:

public void PublishEnd(object sender, EventArgs args)
{
  var sitecoreArgs = args as Sitecore.Events.SitecoreEventArgs;
  if (sitecoreArgs == null)
    return;

  var publisher = sitecoreArgs.Parameters[0] as Publisher;
    return;

  var rootItem = publisher.Options.RootItem;
  
  // Do code
}

To handle the publish:end:remote event, you need the following function:

public void PublishEndRemote(object sender, EventArgs args)
{
  var sitecoreArgs = args as Sitecore.Data.Events.PublishEndRemoteEventArgs;
  if (sitecoreArgs == null)
    return;

  Item rootItem = Factory.GetDatabase("web").GetItem(new ID(sitecoreArgs.RootItemId));
  
  // Do code
}

And in the configuration you need to point to the proper method:

<sitecore>
  <events>
    <event name="publish:end">
      <handler type="MyNamespace, MyDll" method="PublishEnd"/>
    </event>
    <event name="publish:end:remote">
      <handler type="MyNamespace, MyDll" method="PublishEndRemote"/>
    </event>
  </events>
</sitecore>

MORE TO READ:

Advertisements
Posted in c#, General .NET, Sitecore 7, Sitecore 8, Sitecore 9 | Tagged , , | Leave a comment

Sitecore replace spaces with dashes in URL’s

In Sitecore, there is an easy of avoiding the %20 signs in your URL’s. To clarify: If you have an item with a space in the name, the space will appear in the URL as a %20 sign. For example, the item with name “read this” will appear as:

https://yourwebsite.com/read%20this

To avoid this, Sitecore have implemented a simple encodeNameReplacements function. In the sitecore.config, Sitecore have defined a list of character replacements:

<encodeNameReplacements>
  <replace mode="on" find="&amp;" replaceWith=",-a-," />
  <replace mode="on" find="?" replaceWith=",-q-," />
  <replace mode="on" find="/" replaceWith=",-s-," />
  <replace mode="on" find="*" replaceWith=",-w-," />
  <replace mode="on" find="." replaceWith=",-d-," />
  <replace mode="on" find=":" replaceWith=",-c-," />
</encodeNameReplacements>

To make a new replacement, simply add it to the list. In my example, I would like to replace space (” “) with a dash (“-“):

<replace mode="on" find=" " replaceWith="-" />

From now on, all my spaces will be replaced with a dash, and my “read this” page will now have this URL:

https://yourwebsite.com/read-this

BEWARE OF THE INFAMOUS MEDIA LIBRARY REPLACEMENT BUG

In certain versions of Sitecore 7.x and Sitecore 8.1, Sitecore have made a mistake where any item in the media library with a – in the item name will be reversely replaced internally to a space, thus making the URL invalid.

In other words: If your space/dash replacement suddenly breaks media library URL’s, try removing any dashes from the media library item name and see if the problem goes away.

Sitecore support have several bug fixes for this, depending of the Sitecore version.

MORE TO READ:

 

Posted in Sitecore 7, Sitecore 8, Sitecore 9 | Tagged , | 1 Comment

Using C# HttpClient from Sync and Async code

The .NEt 4.5 C# System.Net.Http.HttpClient() is a very nice http client implementation, but can be tricky to use if you (like me) are not a trained asynchronous programming coder. So here is a quick cheat sheet on how to work around the Task<>, async and await methods when using the HttpClient().

UPDATE 2018-01-19: Removed the HttpClient from the Using clause to avoid having to instantiate a new HttpClient for every request, as this can lead to socket exhaustion. For more information, read this Improper Instantiation antipattern article from Sitecore.

EXAMPLE 1: HTTPCLIENT GET WITH RETURN VALUE:

THE GET METHOD:

private static readonly HttpClient _httpClient= new HttpClient();

public static async Task<string> Get(string queryString)
{
  string authUserName = "user"
  string authPassword = "password"
  string url = "https://someurl.com";

  // If you do not have basic authentication, you may skip these lines
  var authToken = Encoding.ASCII.GetBytes($"{authUserName}:{authPassword}");
  httpClient.DefaultRequestHeaders.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Basic", Convert.ToBase64String(authToken));

  // The actual Get method
  using (var result = await _httpClient.GetAsync($"{url}{queryString}"))
  {
    string content = await result.Content.ReadAsStringAsync();
    return content;
  }
}

THE USAGE:

// From synchronous code
string queryString = "?hello=world";
string result = Get(queryString).Result;

// From asynchronous code
string queryString = "?hello=world";
string result = await Get(queryString);

 

EXAMPLE 2: HTTPCLIENT PUT “FIRE-AND-FORGET” WITHOUT RETURN VALUE:

THE PUT METHOD:

private static readonly HttpClient _httpClient = new HttpClient();

public static async Task Put(string postData)
{
  string authUserName = "user";
  string authPassword = "password"
  string url = "https://someurl.com";
        
  // If you have no basic authentication, you can skip thses lines
  var authToken = Encoding.ASCII.GetBytes($"{authUserName}:{authPassword}");
  httpClient.DefaultRequestHeaders.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Basic", Convert.ToBase64String(authToken));
    
  // The actual put method including error handling
  using(var content = new StringContent(postData))
  {
    var result = await _httpClient.PutAsync($"{url}", content);
    if (result.StatusCode == HttpStatusCode.OK)
    {
      return;
    }
    else
    {
      // Do something with the contents, like write the statuscode and
      // contents to a log file
      string resultContent = await result.Content.ReadAsStringAsync();
      // ... write to log
    }
  }
}

THE USAGE:

// You can call the method from asynchronous
// and it will actually run asynchronous. In this fire-and-forget 
// pattern, there is no need to wait for the answer
Put("data");

// ... but if you will wait, simply call ".Wait()":
Put("data").Wait();

MORE TO READ:

 

Posted in .net, c#, General .NET | Tagged , , | Leave a comment

Sitecore Postbacks not working? Contents not updated on button click? Try removing caching from your rendering

This is a classic Sitecore blunder – suddenly postbacks or button clicks have no effect, as if the web site no longer are connected to your webforms codebehind or the MVC renderings. And you have not changed any code.

But have you enabled caching of your rendering?

Sitecore Caching Settings

Sitecore Caching Settings

The Sitecore rendering cache is a true HTML cache. The output markup of the rendering is cached, and the contents of the cache is stored in one or more versions, depending of your choices:

  • Clear on Index Update: Cache cleared when the item is updated in the index
  • Vary By Data: One cache per URL
  • Vary By Device: One cache per device
  • Vary By Login: One cache for anonymous users, another for authenticated users
  • Vary By Parm: One cache per rendering parameter
  • Vary By Query String: One cache per query string parameter
  • Vary by User: On version per user

So a true HTML cache means that your code is called once, and the next time the rendering is rendered, the contents is a string-output operation of the markup stored in the cache. So there is no postbacks from Webforms. Or if you expect the MVC rendering to update the markup on a button click – that’s not going to happen.

Caching have 2 further properties:

  • Your caching settings can be overridden on the presentation details of an item.
  • If a cached rendering have a placeholder containing other renderings, the renderings in the placeholder is also cached.

BTW, you can always clear the cache: Check out the /sitecore/admin/cache.aspx page, or read about how to clear cache individually from code.

MORE TO READ:

 

Posted in Sitecore 5, Sitecore 6, Sitecore 7, Sitecore 8, Sitecore 9 | Tagged , | Leave a comment

Sitecore SOLR error: Invalid Date in Date Math String

There seems to be an issue with certain combinations of Sitecore, SOLR and the local machine datetime settings. This is the error:

ManagedPoolThread #11 12:20:50 INFO Job started: Index_Update_IndexName=sitecore_master_index
ManagedPoolThread #11 12:20:50 ERROR Exception
Exception: System.Reflection.TargetInvocationException
Message: Exception has been thrown by the target of an invocation.
Source: mscorlib
at System.RuntimeMethodHandle.InvokeMethod(Object target, Object[] arguments, Signature sig, Boolean constructor)
at System.Reflection.RuntimeMethodInfo.UnsafeInvokeInternal(Object obj, Object[] parameters, Object[] arguments)
at System.Reflection.RuntimeMethodInfo.Invoke(Object obj, BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture)
at Sitecore.Reflection.ReflectionUtil.InvokeMethod(MethodInfo method, Object[] parameters, Object obj)
at Sitecore.Jobs.JobRunner.RunMethod(JobArgs args)
at (Object , Object[] )
at Sitecore.Pipelines.CorePipeline.Run(PipelineArgs args)
at Sitecore.Jobs.Job.ThreadEntry(Object state)

Nested Exception

Exception: SolrNet.Exceptions.SolrConnectionException
Message: <?xml version=”1.0″ encoding=”UTF-8″?>
<response>
<lst name=”responseHeader”><int name=”status”>400</int><int name=”QTime”>46</int></lst><lst name=”error”><str name=”msg”>Invalid Date in Date Math String:’2017-03-20T13.56.31Z'</str><int name=”code”>400</int></lst>
</response>

Source: SolrNet
at SolrNet.Impl.SolrConnection.PostStream(String relativeUrl, String contentType, Stream content, IEnumerable`1 parameters)
at SolrNet.Impl.SolrConnection.Post(String relativeUrl, String s)
at SolrNet.Impl.SolrBasicServer`1.SendAndParseHeader(ISolrCommand cmd)
at Sitecore.ContentSearch.SolrProvider.SolrBatchUpdateContext.AddRange(IEnumerable`1 group, Int32 groupSize)
at Sitecore.ContentSearch.SolrProvider.SolrBatchUpdateContext.Commit()
at Sitecore.ContentSearch.AbstractSearchIndex.PerformUpdate(IEnumerable`1 indexableInfo, IndexingOptions indexingOptions)

Nested Exception

Exception: System.Net.WebException
Message: The remote server returned an error: (400) Bad Request.
Source: System
at System.Net.HttpWebRequest.GetResponse()
at HttpWebAdapters.Adapters.HttpWebRequestAdapter.GetResponse()
at SolrNet.Impl.SolrConnection.GetResponse(IHttpWebRequest request)
at SolrNet.Impl.SolrConnection.PostStream(String relativeUrl, String contentType, Stream content, IEnumerable`1 parameters)

The error is thrown by SOLR when a datetime string have an invalid format. SOLR only allows datetime strings in the format of YYYY-MM-DDThh:mm:ssZ.

Please note that in the error message above, the format is in fact wrong, as the time contains . instead of :

  • Wrong: 2017-03-20T13.56.31Z
  • Correct: 2017-03-20T13:56:31Z

My machine is configured so the time format contains . not :, and that is why SOLR gets the wrong format.

2017-10-25_13-10-27-3Sitecore have addressed this in patch 178247, where they modify the default System.DateTime converter to ignore any local culture info. The configuration change is simple:

<configuration xmlns:patch="http://www.sitecore.net/xmlconfig/" xmlns:set="http://www.sitecore.net/xmlconfig/set/">
  <sitecore>
    <contentSearch>
      <indexConfigurations>
        <defaultSolrIndexConfiguration>
          <indexFieldStorageValueFormatter>
            <converters>
              <converter handlesType="System.DateTime" typeConverter="Sitecore.ContentSearch.Converters.IndexFieldUTCDateTimeValueConverter, Sitecore.ContentSearch" set:typeConverter="Sitecore.Support.ContentSearch.Converters.IndexFieldUTCDateTimeValueConverter, Sitecore.Support.178247"/>
            </converters>
          </indexFieldStorageValueFormatter>
        </defaultSolrIndexConfiguration>
      </indexConfigurations>
    </contentSearch>
  </sitecore>
</configuration>

And the code change very small:

namespace Sitecore.Support.ContentSearch.Converters
{
  public class IndexFieldUTCDateTimeValueConverter : IndexFieldUtcDateTimeValueConverter
  {
    public override object ConvertTo(ITypeDescriptorContext context, CultureInfo culture, object value, Type destinationType)
    {
      culture = CultureInfo.InvariantCulture;
      return base.ConvertTo(context, culture, value, destinationType);
    }
  }
}

Thanks to Sitecore support for the patch.

MORE TO READ:

Posted in Sitecore 6, Sitecore 7, Sitecore 8, Sitecore 9 | Tagged , , | 1 Comment

Sitecore separate users from CORE database – move membership provider to separate database

Since Sitecore 6, Sitecore have had the .NET membership tables in the CORE database. And since every instance of Sitecore needs access to the CORE database, it might seem as a good place to store them.

But separating the users from the CORE database will make upgrades easier, as you can have 2 instances of Sitecore running without disturbing user access. You also have more scalability options when separating the two.

The separation is easy:

STEP 1: MAKE A COPY OF THE CORE DATABASE

Get yourself a copy of your CORE database. Name the new database something user-membership-like, for example “Users“.

Never mind the Sitecore tables in the newly copied database. Unless you are in need of disk space, you can leave them. They will never be used.

STEP 2: ADD A CONNECTION STRING TO THE CONNECTIONSTRINGS.CONFIG FILE

In /App_Config/ConnectionStrings.Config, add a new connection string to your “Users” database:

<add name="Users" 
   connectionString="user id=*****;password=*****;Data Source=*****;Database=Users" />

STEP 3: MODIFY WEB.CONFIG

In the web.config, find the “membership“, “rolemanager” and “profile” sections, and modify the “connectionStringName” property from “core” to “Users“:

<membership defaultProvider="sitecore" hashAlgorithmType="SHA1">
  <providers>
    <clear />
    <add name="sitecore" type="Sitecore.Security.SitecoreMembershipProvider, Sitecore.Kernel" realProviderName="sql" providerWildcard="%" raiseEvents="true" />
    <add name="sql" type="System.Web.Security.SqlMembershipProvider" connectionStringName="Users" applicationName="sitecore" minRequiredPasswordLength="1" minRequiredNonalphanumericCharacters="0" requiresQuestionAndAnswer="false" requiresUniqueEmail="false" maxInvalidPasswordAttempts="5" />
    <add name="switcher" type="Sitecore.Security.SwitchingMembershipProvider, Sitecore.Kernel" applicationName="sitecore" mappings="switchingProviders/membership" />
  </providers>
</membership>
<roleManager defaultProvider="sitecore" enabled="true">
  <providers>
    <clear />
    <add name="sitecore" type="Sitecore.Security.SitecoreRoleProvider, Sitecore.Kernel" realProviderName="sql" raiseEvents="true" />
    <add name="sql" type="System.Web.Security.SqlRoleProvider" connectionStringName="Users" applicationName="sitecore" />
    <add name="switcher" type="Sitecore.Security.SwitchingRoleProvider, Sitecore.Kernel" applicationName="sitecore" mappings="switchingProviders/roleManager" />
  </providers>
</roleManager>
<profile defaultProvider="sql" enabled="true" inherits="Sitecore.Security.UserProfile, Sitecore.Kernel">
  <providers>
    <clear />
    <add name="sql" type="System.Web.Profile.SqlProfileProvider" connectionStringName="Users" applicationName="sitecore" />
    <add name="switcher" type="Sitecore.Security.SwitchingProfileProvider, Sitecore.Kernel" applicationName="sitecore" mappings="switchingProviders/profile" />
  </providers>
  <properties>
    <clear />
    <add type="System.String" name="SC_UserData" />
  </properties>
</profile>

MORE TO READ:

 

Posted in Sitecore 6, Sitecore 7, Sitecore 8 | Tagged , | 3 Comments

Sitecore Rule – Personalize based on any field in any facet in your Contact

This Sitecore Personalization Rule was developed by my colleague Martin Rygaard with the purpose of being able to personalize on any field in any facet on a contact.

Contact Facet Rule Set Editor

Contact Facet Rule Set Editor

STEP 1: CREATE THE CONDITION

Create a new “Condition” below /sitecore/system/Settings/Rules/Definitions/Elements/???

The text of the Condition is:

where the [facetpath,,,facetpath] has [facetvalue,,,facetvalue]

STEP 2: CREATE A WHENCONDITION

This condition traverses the Contact path and returns true if the value matches the value described:

using System.Collections;
using Sitecore.Analytics;
using Sitecore.Analytics.Model.Framework;
using Sitecore.Analytics.Tracking;
using Sitecore.Diagnostics;
using Sitecore.Rules;
using Sitecore.Rules.Conditions;

namespace MyNamespace
{
  public class ContactFacetHasValue<T> : WhenCondition<T> where T : RuleContext
  {
    public string FacetValue { get; set; }
    
    public string FacetPath { get; set; }

    protected override bool Execute(T ruleContext)
    {
        Contact contact = Tracker.Current.Session.Contact;

        if (contact == null)
        {
          Log.Info(this.GetType() + ": contact is null", this);
          return false;
        }

        if (string.IsNullOrEmpty(FacetPath))
        {
          Log.Info(this.GetType() + ": facet path is empty", this);
          return false;
        }

        var inputPropertyToFind = FacetPath;

        string[] propertyPathArr = inputPropertyToFind.Split('.');
        if (propertyPathArr.Length == 0)
        {
          Log.Info(this.GetType() + ": facet path is empty", this);
          return false;
        }

        Queue propertyQueue = new Queue(propertyPathArr);
        string facetName = propertyQueue.Dequeue().ToString();
        IFacet facet = contact.Facets[facetName];
        if (facet == null)
        {
          Log.Info(string.Format("{0} : cannot find facet {1}", this.GetType(), facetName), this);
          return false;
        }

        var datalist = facet.Members[propertyQueue.Dequeue().ToString()];
        if (datalist == null)
        {
          Log.Info(string.Format("{0} : cannot find facet {1}", this.GetType(), facetName), this);
          return false;
        }
        
        if(typeof(IModelAttributeMember).IsInstanceOfType(datalist))
        {
          var propValue = ((IModelAttributeMember)datalist).Value;
          return (propValue != null ? propValue.Equals(FacetValue) : false);
        }
        if(typeof(IModelDictionaryMember).IsInstanceOfType(datalist))
        {
          var dictionaryMember = (IModelDictionaryMember) datalist;

          string elementName = propertyQueue.Dequeue().ToString();
          IElement element = dictionaryMember.Elements[elementName];
          if (element == null)
          {
            Log.Info(string.Format("{0} : cannot find element {1}", this.GetType(), elementName), this);
            return false;
          }

          string propertyToFind = propertyQueue.Dequeue().ToString();
          var prop = element.Members[propertyToFind];
          if (prop == null)
          {
            Log.Info(string.Format("{0} : cannot find property {1}", this.GetType(), propertyToFind), this);
            return false;
          }

          var propValue = ((IModelAttributeMember) prop).Value;
          return (propValue != null ? propValue.Equals(FacetValue) : false);
        }
        if (typeof(IModelCollectionMember).IsInstanceOfType(datalist))
        {
          var collectionMember = (IModelCollectionMember)datalist;
          var propertyToFind = propertyQueue.Dequeue().ToString();
          for (int i = 0; i < collectionMember.Elements.Count; i++)
          {
            IElement element = collectionMember.Elements[i];
            var prop = element.Members[propertyToFind];
            if (prop == null)
            {
              Log.Info(string.Format("{0} : cannot find property {1}", this.GetType(), propertyToFind), this);
              return false;
            }
            var propValue = ((IModelAttributeMember) prop).Value;
            if (propValue.Equals(FacetValue))
              return true;
          }
        }

      return false;
    }
  }
}

STEP 3: TEST IT

This is an example of a Contact, with facets, among these is the “Personal” facet with the “FirstName” attribute:

Facet

Facet

When creating a Personalization rule where “Personal.FirstName” has “Brian” and applying it to my page:

Contact Facet Rule Set Editor

Contact Facet Rule Set Editor

Rule In Use

Rule In Use

I should only be able to see this title when logged in as a user which contact facet FirstName is “Brian”:

Yes, I am a Brian

Yes, I am a Brian

MORE TO READ:

 

 

Posted in .net, c#, Sitecore 7, Sitecore 8 | Tagged , , , , | 1 Comment

C# Using Newtonsoft and dynamic ExpandoObject to convert one Json to another

The scenario where you convert one input Json format to another output Json is not uncommon. Before C# dynamic and ExpandoObject you would serialize the input Json to POCO model classes and use a Factory class to convert to another set of POCO model classes, that then would be serialized to Json.

With the dynamic type and the ExpandoObject you have another weapon of choice, as you can deserialize the input Json to a dynamic object, and convert the contents to another dynamic object that is serialized. Imagine the following input and output Json formats:

Input format:

{
	"username": "someuser@somewhere.com",
	"timeStamp": "2017-09-20 13:50:16.560",
	"attributes": {
		"attribute": [{
			"name": "Brian",
			"count": 400
		},
		{
			"name": "Pedersen",
			"count": 100
		}]
	}
}

Output format:

{
	"table": "USER_COUNT",
	"users": [{
		"uid": "someuser@somewhere.com",
		"rows": [{
			"NAME": "Brian",
			"READ_COUNT": 400
		},
		{
			"NAME": "Pedersen",
			"READ_COUNT": 100
		}]
	}]
}

Converting from the input format to the output format can be achieved with a few lines of code:

// Convert input Json string to a dynamic object
dynamic input = JsonConvert.DeserializeObject(myQueueItem);

// Create a dynamic output object
dynamic output = new ExpandoObject();
output.table = "USER_COUNT";
output.users = new dynamic[1];
output.users[0] = new ExpandoObject();
output.users[0].uid = input.username;
output.users[0].rows = new dynamic[input.attributes.attribute.Count];
int ac = 0;
foreach (var inputAttribute in input.attributes.attribute)
{
    var row = output.users[0].rows[ac] = new ExpandoObject();
    row.NAME = inputAttribute.name;
    row.READ_COUNT = inputAttribute.count;
    ac++;
}

// Serialize the dynamic output object to a string
string outputJson = JsonConvert.SerializeObject(output);

I’ll try to further explain what happens. The Newtonsoft.Json DeserializeObject() method takes a json string and converts it to a dynamic object.

The output Json is created by creating a new dynamic object of the type ExpandoObject(). With dynamic ExpandoObjects we can create properties on the fly, like so:

// Create a dynamic output object
dynamic output = new ExpandoObject();
// Create a new property called "table" with the value "USER_COUNT"
output.table = "USER_COUNT";

This would, when serialized to a Json, create the following output:

{
"table": "USER_COUNT"
}

To create an array of objects, you need to first create a new dynamic array and then assign an ExpandoObject to the position in the array:

// Create a dynamic output object
dynamic output = new ExpandoObject();
// Create a new array called "users"
output.users = new dynamic[1];
// An an object to the "users" array
output.users[0] = new ExpandoObject();
// Create a new property "uid" in the "users" array
output.users[0].uid = input.username;

This generates the following Json output:

{
	"users": [{
		"uid": "someuser@somewhere.com"
		}]
}

MORE TO READ:

Posted in c#, General .NET | Tagged , , , | Leave a comment

.NET Session state is not thread safe

When working with the .NET session state you should bear in mind that the HttpContext.Current.Session cannot be transferred to another thread. Imagine that you, from the Global.asax would like to read the SessionID each time a session is started:

// This method inside Global.asax is called for every session start
protected void Session_Start(object sender, EventArgs e)
{
  MyClass.DoSomethingWithTheSession(HttpContext.Current);
}

To speed up performance you wish to use a thread inside DoSomethingWithTheSession. The thread will read the Session ID:

public class MyClass
{															   
  public static void DoSomethingWithTheSession(HttpContext context) 
  {
    if (context == null)  
	  return;

    // Here the context is not null
	ThreadPool.QueueUserWorkItem(DoSomethingWithTheSessionAsync, context);
  }

  private static void DoSomethingWithTheSessionAsync(object httpContext)
  { 
    HttpContext context = (HttpContext)httpContext;
	
	// Oops! Here the context is NULL
	string sessionID = context.Session.SessionID; 
  }
}

The code above will fail because the HttpContext is not thread safe. So in DoSomethingWithTheSession(), the context is set, but in DoSomethingWithTheSessionAsync, the context will null.

THE SOLUTION: TRANSFER THE SESSION VALUES INSTEAD OF THE SESSION OBJECT:

To make it work, rewrite the DoSomethingWithTheSessionAsync() method to reteieve the values needed, not the HttpContext object itself:

public class MyClass
{															   
  public static void DoSomethingWithTheSession(HttpContext context) 
  {
    if (context == null)  
      return;

    // Transfer the sessionID instead of the HttpContext and everything is fine
    ThreadPool.QueueUserWorkItem(DoSomethingWithTheSessionAsync, 
      context.Session.SessionID);
  }

  private static void LogReportFeatureflagsAsync(object session)
  { 
    // This works fine, as the string is thread safe.
    string sessionID = (string)session;
	
    // Do work on the sessionID
  }
}

MORE TO READ:

 

Posted in .net, c#, General .NET | Tagged , , , , , , | Leave a comment