MVC4 how to hook the OnSessionStart event? - asp.net-mvc-4

I start MVC4 project in VS2010,
In Global.asax.cs like :
public class MvcApplication : System.Web.HttpApplication
{
protected void Application_Start()
{
AreaRegistration.RegisterAllAreas();
WebApiConfig.Register(GlobalConfiguration.Configuration);
FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
RouteConfig.RegisterRoutes(RouteTable.Routes);
BundleConfig.RegisterBundles(BundleTable.Bundles);
AuthConfig.RegisterAuth();
}
}
how to register Session Start event ?

You can just add this to your Global.asax.cs like this:
protected void Session_Start(object sender, EventArgs e)
{
// event is raised each time a new session is created
}
protected void Session_End(object sender, EventArgs e)
{
// event is raised when a session is abandoned or expires
}
You should also probably check
http://msdn.microsoft.com/en-us/library/bb470252(v=vs.100).aspx
Cheers!

Related

Hangfire Recurring Job not firing OnPerformed method from JobFilter

I'm developing a custom JobFilter for my application but It seems that the method from a recurring job is not hitting the OnPerformed method (IServerFilter). When I create a background job manually this works just fine. Does someone knows how to monitor if a job (all types) is complete?
public class CustomJobAttribute : JobFilterAttribute, IClientFilter, IServerFilter
{
public void OnCreating(CreatingContext filterContext)
{
}
public void OnCreated(CreatedContext filterContext)
{
}
public void OnPerforming(PerformingContext filterContext)
{
}
public void OnPerformed(PerformedContext filterContext)
{
}
}

How can I stop IDisposable invokes while render the page in blazor server-side?

Here is my code:
#page "/"
#using Microsoft.AspNetCore.Components.Server.Circuits
#inject CircuitHandler circuitHandler
#implements IDisposable
<h1>Hello, world!</h1>
Welcome to your new app.
#code{
protected override async Task OnAfterRenderAsync(bool firstRender)
{
if (firstRender)
{
Console.WriteLine("123");//do something
}
}
#region//circuitHandler
protected override void OnInitialized()
{
// Subscribe to the event handler
(circuitHandler as CircuitHandlerService).CircuitsChanged +=
HandleCircuitsChanged;
}
public void HandleCircuitsChanged(object sender, EventArgs args)
{
Console.WriteLine("123");//do something
}
public void Dispose()
{
(circuitHandler as CircuitHandlerService).CircuitsChanged -=
HandleCircuitsChanged;
}
#endregion
}
using Microsoft.AspNetCore.Components.Server.Circuits;
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
namespace BlazorApp2
{
public class CircuitHandlerService : CircuitHandler
{
public ConcurrentDictionary<string, Circuit> Circuits
{
get;
set;
}
public event EventHandler CircuitsChanged;
protected virtual void OnCircuitsChanged()
=> CircuitsChanged?.Invoke(this, EventArgs.Empty);
public CircuitHandlerService()
{
Circuits = new ConcurrentDictionary<string, Circuit>();
}
public override Task OnCircuitOpenedAsync(Circuit circuit,
CancellationToken cancellationToken)
{
Circuits[circuit.Id] = circuit;
//OnCircuitsChanged();
return base.OnCircuitOpenedAsync(circuit,
cancellationToken);
}
public override Task OnCircuitClosedAsync(Circuit circuit,
CancellationToken cancellationToken)
{
Circuit circuitRemoved;
Circuits.TryRemove(circuit.Id, out circuitRemoved);
OnCircuitsChanged();
return base.OnCircuitClosedAsync(circuit,
cancellationToken);
}
public override Task OnConnectionDownAsync(Circuit circuit,
CancellationToken cancellationToken)
{
return base.OnConnectionDownAsync(circuit,
cancellationToken);
}
public override Task OnConnectionUpAsync(Circuit circuit,
CancellationToken cancellationToken)
{
return base.OnConnectionUpAsync(circuit, cancellationToken);
}
}
}
I need the CircuitHandler to get to know whether the page is closed.
Now I met a strange problem. When the page is loaded, the IDisposable always invoke even the page is not closed.
What's more, there are several codes in OnAfterRenderAsync. When the IDisposable invokes, the codes in OnAfterRenderAsync which not runs finished will suddenly break without any error.
Someone told me to set the
#(await Html.RenderComponentAsync<App>(RenderMode.ServerPrerendered))
in _Host.cshtml to
#(await Html.RenderComponentAsync<App>(RenderMode.Server))
can solve this.
I tried, but the problem still here.
How can I solve this? Thank you.
the code snippet below is exactly like yours, and it works for me perfectly fine. The Dispose method is called only when a Circuit is closed. I'll post below the entire code I use, copy and run it, then I'll try to help with other issues you have.
<app>
#(await Html.RenderComponentAsync<App>(RenderMode.Server))
</app>
Note: I'm posting here entire files' content. You'll have to adjust the namespaces of my app with yours.
Code for CircuitHandlerService.cs
using Microsoft.AspNetCore.Components.Server.Circuits;
using System;
using System.Collections.Concurrent;
using System.Threading;
using System.Threading.Tasks;
namespace BlazorCircuitHandler.Services
{
public class CircuitHandlerService : CircuitHandler
{
public ConcurrentDictionary<string, Circuit> Circuits { get; set; }
public event EventHandler CircuitsChanged;
protected virtual void OnCircuitsChanged()
=> CircuitsChanged?.Invoke(this, EventArgs.Empty);
public CircuitHandlerService()
{
Circuits = new ConcurrentDictionary<string, Circuit>();
}
public override Task OnCircuitOpenedAsync(Circuit circuit, CancellationToken cancellationToken)
{
Circuits[circuit.Id] = circuit;
OnCircuitsChanged();
return base.OnCircuitOpenedAsync(circuit, cancellationToken);
}
public override Task OnCircuitClosedAsync(Circuit circuit, CancellationToken cancellationToken)
{
Circuit circuitRemoved;
Circuits.TryRemove(circuit.Id, out circuitRemoved);
OnCircuitsChanged();
return base.OnCircuitClosedAsync(circuit, cancellationToken);
}
public override Task OnConnectionDownAsync(Circuit circuit, CancellationToken cancellationToken)
{
return base.OnConnectionDownAsync(circuit, cancellationToken);
}
public override Task OnConnectionUpAsync(Circuit circuit, CancellationToken cancellationToken)
{
return base.OnConnectionUpAsync(circuit, cancellationToken);
}
}
}
Code for Index.razor
#page "/"
#using Microsoft.AspNetCore.Components.Server.Circuits
#using BlazorCircuitHandler.Services
#inject CircuitHandler circuitHandler
#implements IDisposable
<p>
Number of Circuits: #((circuitHandler as
BlazorCircuitHandler.Services.CircuitHandlerService).Circuits.Count)
<ul>
#foreach (var circuit in (circuitHandler as
BlazorCircuitHandler.Services.CircuitHandlerService).Circuits)
{
<li>#circuit.Key</li>
}
</ul>
</p>
#code {
protected override void OnInitialized()
{
(circuitHandler as CircuitHandlerService).CircuitsChanged +=
HandleCircuitsChanged;
}
public void Dispose()
{
(circuitHandler as CircuitHandlerService).CircuitsChanged -=
HandleCircuitsChanged;
}
public void HandleCircuitsChanged(object sender, EventArgs args)
{
InvokeAsync(() => StateHasChanged());
}
}
Also Startup class
public void ConfigureServices(IServiceCollection services)
{
// Removed for brevity....
services.AddSingleton<CircuitHandler>(new CircuitHandlerService());
}
And of course _Host.cshtml
<app>
#(await Html.RenderComponentAsync<App>(RenderMode.Server))
</app>
Please, don't fail to report ...

Revit Synchronization event

Starting with this...
https://github.com/jeremytammik/RevitLookup/blob/master/CS/EventTrack/Events/ApplicationEvents.cs
I'm trying to add an event listener for a synchronization event. the code below throws an error stating that the m_app is null. Can i not subscribe to this event while Revit is starting up?
I was able to do this before with application.ViewActivated += ..... Im wondering if this has something to do with DB vs UI driven events and when they are allowed to be subscribed to? I just don't know.
namespace RevitModelHealth
{
public class checkHealth : IExternalApplication
{
// Document doc;
static public Autodesk.Revit.ApplicationServices.Application m_app = null;
public Result OnShutdown(UIControlledApplication application)
{
return Result.Succeeded;
}
public Result OnStartup(UIControlledApplication application)
{
m_app.DocumentSynchronizingWithCentral += new EventHandler<DocumentSynchronizingWithCentralEventArgs>(m_app_DocumentSavingToCentral);
return Result.Succeeded;
}
void m_app_DocumentSavingToCentral(object sender, Autodesk.Revit.DB.Events.DocumentSynchronizingWithCentralEventArgs e)
{
MessageBox.Show("asd","asd");
}
}
}
Here is updated code reflecting my response to the first answer. The message box opens when the document is loaded. No errors are thrown when I try to initialize the synchronization event handlers, however, neither of the message boxes open before or after a synchronization event.
public class checkHealth : IExternalApplication
{
// Document doc;
static public Autodesk.Revit.ApplicationServices.Application m_app;
public Result OnShutdown(UIControlledApplication application)
{
return Result.Succeeded;
}
public Result OnStartup(UIControlledApplication application)
{
application.ControlledApplication.DocumentOpened += new EventHandler<DocumentOpenedEventArgs>(app_DocOpened);
return Result.Succeeded;
}
public void app_DocOpened(object sender, DocumentOpenedEventArgs args)
{
MessageBox.Show("asd","asd");
m_app.DocumentSynchronizingWithCentral += new EventHandler<DocumentSynchronizingWithCentralEventArgs>(m_app_DocumentSavingToCentral);
m_app.DocumentSynchronizedWithCentral += new EventHandler<Autodesk.Revit.DB.Events.DocumentSynchronizedWithCentralEventArgs>(m_app_DocumentSavedToCentral);
}
void m_app_DocumentSavingToCentral(object sender, Autodesk.Revit.DB.Events.DocumentSynchronizingWithCentralEventArgs e)
{
MessageBox.Show("sync", "sync");
}
void m_app_DocumentSavedToCentral(object sender, Autodesk.Revit.DB.Events.DocumentSynchronizedWithCentralEventArgs e)
{
MessageBox.Show("Doone", "Done");
}
}
this worked.... Thanks largely in part to the SDK sample project EventsMonitor
namespace RevitModelHealth
{
public class checkHealth : IExternalApplication
{
public Result OnShutdown(UIControlledApplication application)
{
return Result.Succeeded;
}
public Result OnStartup(UIControlledApplication application)
{
application.ControlledApplication.DocumentSynchronizingWithCentral += new EventHandler<DocumentSynchronizingWithCentralEventArgs>(app_syncStart);
application.ControlledApplication.DocumentSynchronizedWithCentral += new EventHandler<DocumentSynchronizedWithCentralEventArgs>(app_syncOver);
return Result.Succeeded;
}
public void app_syncStart(object o ,DocumentSynchronizingWithCentralEventArgs args)
{
MessageBox.Show("","Stasrting");
}
public void app_syncOver(object o,DocumentSynchronizedWithCentralEventArgs args)
{
MessageBox.Show("", "Over");
}
}
}
Try
application.ControlledApplication.DocumentSynchronizingWithCentral += new EventHandler<DocumentSynchronizingWithCentralEventArgs>(m_app_DocumentSavingToCentral)
in your OnStartup() method.
The call is failing because instance member m_app is initialized to null.
The UIApplication.ControlledApplication object that raises the DocumentSynchronizingWithCentralEventArgs is being accessible from the parameter to OnStartup.
You can try this:
public void app_DocOpened(object sender, DocumentOpenedEventArgs args)
{
MessageBox.Show("asd","asd");
Autodesk.Revit.ApplicationServices.Application m_app = args.Document.Application;
m_app.DocumentSynchronizingWithCentral += new EventHandler<DocumentSynchronizingWithCentralEventArgs>(m_app_DocumentSavingToCentral);
m_app.DocumentSynchronizedWithCentral += new EventHandler<Autodesk.Revit.DB.Events.DocumentSynchronizedWithCentralEventArgs>(m_app_DocumentSavedToCentral);
}

FileSystemWatcher in an AspNetCore 2.1 BackgroundService\IHostedService

I am trying to use an implementation of the BackgroundService in an AspNet Core 2.1 application. I create a FileSystemWatcher in ExecuteAsync and link the associated events,however, the fsw events are either never fired (unreachable? already disposed?) or its some thing I am doing wrong with this being async or the scope is messed up. I can't seem to figure it out. Following is the relevant code.
public class FSWImpl : BackgroundService
{
private readonly IHostingEnvironment _env;
private readonly ILogger<LiftAndShift> _logger;
private FileSystemWatcher _fsw;
public LiftAndShift(IHostingEnvironment env, ILogger<FSWImpl> logger)
{
_env = env;
_logger = logger;
}
protected override Task ExecuteAsync(CancellationToken stoppingToken)
{
_logger.LogInformation("Creating new FSW");
var path = Path.Combine(_env.ContentRootPath, "WebData");
_fsw = new FileSystemWatcher(path,"*.json");
_fsw.Created += _fsw_Created;
_fsw.Changed += _fsw_Changed;
_fsw.Renamed += _fsw_Renamed;
_fsw.Error += _fsw_Error;
return Task.CompletedTask;
}
private void _fsw_Error(object sender, ErrorEventArgs e) => _logger.LogInformation("File error");
private void _fsw_Renamed(object sender, RenamedEventArgs e) => _logger.LogInformation("File Renamed");
private void _fsw_Changed(object sender, FileSystemEventArgs e) => _logger.LogInformation("File changed");
private void _fsw_Created(object sender, FileSystemEventArgs e) => _logger.LogInformation("File created");
}
I register this service in startup as services.AddHostedService<FSWImpl>();
For enabling FileSystemWatcher, you need to set EnableRaisingEvents as True.
Demo Code:
protected override Task ExecuteAsync(CancellationToken stoppingToken)
{
_logger.LogInformation("Creating new FSW");
var path = Path.Combine(_env.ContentRootPath, "WebData");
_fsw = new FileSystemWatcher(path, "*.json");
_fsw.Created += _fsw_Created;
_fsw.Changed += _fsw_Changed;
_fsw.Renamed += _fsw_Renamed;
_fsw.Error += _fsw_Error;
_fsw.EnableRaisingEvents = true;
return Task.CompletedTask;
}
FileSystemWatcher.cs
//
// Summary:
// Gets or sets a value indicating whether the component is enabled.
//
// Returns:
// true if the component is enabled; otherwise, false. The default is false. If
// you are using the component on a designer in Visual Studio 2005, the default
// is true.
//
// Exceptions:
// T:System.ObjectDisposedException:
// The System.IO.FileSystemWatcher object has been disposed.
//
// T:System.PlatformNotSupportedException:
// The current operating system is not Microsoft Windows NT or later.
//
// T:System.IO.FileNotFoundException:
// The directory specified in System.IO.FileSystemWatcher.Path could not be found.
//
// T:System.ArgumentException:
// System.IO.FileSystemWatcher.Path has not been set or is invalid.
public bool EnableRaisingEvents { get; set; }

Why Won't the Silverlight ChildWindow Display?

I have a simple Silverlight 4 application and have added a child window to it. I am using the below code to open it on a button click. This seems like it should work, does it not?
public void btnAbout_Click(object sender, RoutedEventArgs e)
{
About aboutThis = new About();
aboutThis.Show();
}
The "About" class looks like this:
public partial class About : ChildWindow
{
public About()
{
InitializeComponent();
}
private void OKButton_Click(object sender, RoutedEventArgs e)
{
this.DialogResult = true;
}
private void CancelButton_Click(object sender, RoutedEventArgs e)
{
this.DialogResult = false;
}
}
I don't see any reason why it should not work.
Samples:
http://www.tanguay.info/web/index.php?pg=codeExamples&id=135
http://www.silverlighttoys.com/Tutorials.aspx?tutorial=2
What is your XAML like?
Try setting the Width and Height to 600px by 600px of your About Childwindow from xaml.