Developer forum

Forum » Development » Check if inside DW context?

Check if inside DW context?

Kasper Laursen
Reply

Hi,

I'm sharing some of my code between DW and non-DW projects. Is there a proper way to check programmatically if I am inside a DW context? Everything I've tried to use in the Dynamicweb libraries throws null references.

I know I could put up try-catch statements, but I'd much prefer a simple bool or value that returns null or something similar.

A common situation is when i execute code where I want to log information. I'd prefer to log it to DW, but I pbviously can't when not running in DW context. I'd like to make a check for it rather than meet an exception that I need to handle.

Regards
Kasper


Replies

 
Nicolai Pedersen
Reply

I am not sure I understand your setup.

Are we talking frontend? You could check if Dynamicweb.Fronten.Pageview.Current is null - if it is, you are not in the Dynamicweb frontend.

BR Nicolai

 
Kasper Laursen
Reply

As always, thanks for the quick reply. This is a minor issue, but one that I'd expect would have a simple answer :)

I'm in the backend where I have different service classes. Some of these should be logging events and exceptions and so on to the DW log.

However, I also have a regular C# console project using some of those same services. Yes, I'm aware that I could be writing DW scheduled tasks, but right now that's not the case.

My code in the services are using the Dynamicweb.Logging.LogManager which throws the exception if I am accessing it through my console job. This isn't all that weird, but I'd just like to know if there was something else I could call to know if this exception would be thrown. Something like "Dynamicweb.Logging.LogManager.Current == null" or something general like "Dynamicweb.Context.Current == null" or perhaps "Dynamicweb.Context.IsValid".

More expansive code example:

if(???) // I'd expect to use something like LogManager.Current != null
{
    var logger = LogManager.Current.GetLogger("myLog");
    logger.Log("message123");
}
else
{
    FileLogger.Log("Message123");
}

Regards
Kasper

 
Nicolai Pedersen
Reply

Cant you just do:

var logger = LogManager?.Current?.GetLogger("myLog");

if(logger != null {

}
 
Kasper Laursen
Reply

Unfortunately not. LogManager.Current is a static function that throws the exception. It doesn't return null. It's the same for Dynamicweb.Context.Current and everything else that i tried.

It would be nice if .Current simply returned null rather than throwing.

Regards
Kasper

 

You must be logged in to post in the forum