I need to fill HttpContext.Current.Application["Translations"] on OWIN startup, but HttpContext.Current is null there.
Should I use Application_Start() in Global.asax.cs or it is bad idea?
What alternatives do I have?
HttpContext is not available at start up as it cannot exist without a request. The Startup class only runs once for the application, not for each request.
Try accessing it in the BeginRequest handler in Global.asax.cs.
protected void Application_BeginRequest(object sender, EventArgs e) {
base.Application["Translations"] = "My value here";
}
Related
We have a global.asax.cs file which contains this code...
Approach One
public class WebApiApplication : System.Web.HttpApplication
{
TelemetryClient _telemetry = new TelemetryClient(new Microsoft.ApplicationInsights.Extensibility.TelemetryConfiguration() {
InstrumentationKey = EnvironmentHelper.InstrumentationKey,
ConnectionString = EnvironmentHelper.AppInsightsConnectionString
});
protected void Application_Start()
{
HttpConfiguration config = GlobalConfiguration.Configuration;
GlobalConfiguration.Configure(WebApiConfig.Register);
}
}
I am concerned that this will not log every and all exceptions to Insights. Would it be better to use this code?...
Approach Two
public class WebApiApplication : System.Web.HttpApplication
{
TelemetryClient _telemetry = new TelemetryClient(...);
protected void Application_Start()
{
HttpConfiguration config = GlobalConfiguration.Configuration;
config.Filters.Add(new CustomExceptionFilter()); // ADDED LINE
GlobalConfiguration.Configure(WebApiConfig.Register);
}
protected void Application_Error(Object sender, EventArgs e) // ADDED METHOD
{
Exception appException = Server.GetLastError();
_telemetry.TrackException(appException);
}
}
// ADDED CLASS
public class CustomExceptionFilter : ExceptionFilterAttribute
{
TelemetryClient _telemetry = new TelemetryClient(...);
public override void OnException(HttpActionExecutedContext actionExecutedContext)
{
_telemetry.TrackException(actionExecutedContext.Exception);
base.OnException(actionExecutedContext);
}
}
Are these approaches equal or is one more reliable?
Not sure what do you mean all exceptions get logged.
Actually, Application Insights will auto collect unhandled exceptions thrown in the controller methods automatically for WebAPI 2+, exception the following scenario:
Exceptions thrown from controller constructors.
Exceptions thrown from message handlers.
Exceptions thrown during routing.
Exceptions thrown during response content serialization.
Exception thrown during application start-up.
Exception thrown in background tasks.
And For the other exceptions which are handled by application, still need to be tracked manually. You can use the telemetryclient to track these exceptions.
The referenced doc is here.
I have these code, according to document from sitefinity:
protected void Application_Start(object sender, EventArgs e)
{
Bootstrapper.Initialized += new EventHandler<ExecutedEventArgs>(Bootstrapper_Initialized);
}
public void Bootstrapper_Initialized(object sender, ExecutedEventArgs args)
{
if (args.CommandName == "Bootstrapped")
{
EventHub.Subscribe<ICommentEvent>(evt => CommentsEvent.CommentEventHandler(evt));
}
}
And the handler:
public static void CommentEventHandler(ICommentEvent evt)
{
// My code here
}
The problem is this handler always runs twice when a comment event happens (post a comment or approve a comment).
Could you please tell me why this happens and any possible way to avoid this? (I don't believe static boolean is a good idea).
Thanks
ICommentEvent is a base interface that is implemented by multiple events such as ICommentCreatingEvent, ICommentCreatedEvent, ICommentUpdatingEvent, ICommentUpdatedEvent and some others.
In your case it is fired twice due to firing of both ICommentCreatingEvent and ICommentCreatedEvent.
You can subscribe to just one of them and it should fire just once.
I placed the following code in the global file to catch exception in my mvc application:
void Application_Error(Object sender, EventArgs e)
{
Exception ex = Server.GetLastError().GetBaseException();
log.Error("Exception", ex);
}
and the following to trace what controllers are called:
public override void OnActionExecuting(ActionExecutingContext filterContext)
{
if (log.IsDebugEnabled)
{
var loggingWatch = Stopwatch.StartNew();
filterContext.HttpContext.Items.Add(StopwatchKey, loggingWatch);
var message = new StringBuilder();
message.Append(string.Format("Executing controller: {0}, action: {1}",
filterContext.ActionDescriptor.ControllerDescriptor.ControllerName,
filterContext.ActionDescriptor.ActionName));
log.Debug(message);
}
}
Is there more I can do to catch errors involving db, security (like cannot connect to ldap), data issues/casting, etc..?
The second code snippet could be added to a global action filter (registered in global.asax). The first snippet could be added to a seperate IHttpModule implementation to remove it from global.asax.
Other than that you've added code to the two places where all exceptions will be caught. The first one will be invoked for all non-MVC related exceptions while the later one is for MVC exceptions only (routing excluded)
It's a little strange that my Windows Phone App will exit without any Warning by chance, most of the time it works fine.
Then I trace the Application_UnhandledException, find that the Exception message is:
[ExceptionMessage]:[NullReferenceException]
[StackTrace]:[
at wpapp.MainPage.<DispatcherLoad>b__1(Object sender, EventArgs e)
at MS.Internal.CoreInvokeHandler.InvokeEventHandler(Int32 typeIndex, Delegate handlerDelegate, Object sender, Object args)
at MS.Internal.JoltHelper.FireEvent(IntPtr unmanagedObj, IntPtr unmanagedObjArgs, Int32 argsTypeIndex, Int32 actualArgsTypeIndex, String eventName)
]
There is no detailed information for me to find out the cause of the exception. Has anybody met this exception before and got a solution for it?
Any suggestions will be appreciated.
From the look of it, it's likely that you have a DispatcherLoad method in your MainPage, and you're calling a lambda function in that method. Something like:
private void DispatcherLoad()
{
this.Dispatcher.BeginInvoke(() => Console.WriteLine("hello world;"));
}
The error is occuring in the lambda (in my sample: the Console.WriteLine("hello world;") part). So now you just have to find the right lambda, and find out why your code crashes.
Given the "object sender, EventArgs e" parameters, it's probably an event handler. Are you assigning a lambda to an event handler somewhere in the DispatcherLoad function? For instance:
private void DispatcherLoad()
{
this.Button.Click += (sender, e) => Console.WriteLine("hello world;");
}
Note: if there's many lambdas in your method and you can't figure which one is crashing, you can try opening your assembly with Reflector (http://www.reflector.net/). It will decompile your dll, and you can then see which lambda is called "<DispatcherLoad>b__1".
Is there a way to customize/edit the default template of the event handling methods in Visual Studios 2008/2010 such that upon creation, the event handler already has a try/catch block in it?
the default behavior is
private void button1_Click(object sender, EventArgs e)
{
}
I'd like to be able to set the development environment to do
private void button1_Click(object sender, EventArgs e)
{
try
{
///TODO: Add logic here
}
catch
{
throw;
}
finally
{
}
}
I've already edited the templates located in the ItemTemplates folder so that they meet the coding standard where I work, but I'd also like to edit the method templates if possible. I've searched the 'Net for the better part of a week and found nothing. Any assistance would be greatly appreciated.
![Snippet Manager1
Have you considered Editing Event method stub in the Code Snippet manager or adding a new snippet?