Fire just once a Thread in Asp.net WebSite Global.asax - asp.net

I've a legacy application using Asp.Net WebSite (winforms...) and I need run a background thread that collect periodically some files.
But this thread must run just one time!
My problem start when I put a method in Application_Start:
void Application_Start(object sender, EventArgs e) {
SetConnection();
SetNHibernate();
SetNinject();
SetExportThread();
}
So I start my application on Visual Studio and three threads start to run.
I need some singleton? or something?

Try creating a static method and variable:
private static bool _inited = false;
private static object _locker = new object();
private static void Init()
{
if (!_inited)
{
lock(_locker)
{
// Have to check again because the first check wasn't thread safe
if (!_inited)
{
SetConnection();
SetNHibernate();
SetNinject();
SetExportThread();
_inited = true;
}
}
}
}
void Application_Start(object sender, EventArgs e)
{
Init();
}

Related

Events from COM: works fine in WinForms/WPF but doesn't work in ASP.Net

Please tell me why does the following work fine in WinForms/WPF and not in ASP.Net.
We have a class library targeted for .Net 3.5. It has an interop referenced (generated from TLB).
public class MyClass
{
public delegate void ChangedEventHandler(string newStatus);
public event ChangedEventHandler Changed;
private ComObject objCom = new ComObject();
public void Init()
{
//Com events.
objCom.AvailabilityChanged += objCom_AvailabilityChanged;
//Start session to the h/w device.
//When finished, AvailabilityChanged event is fired with new h/w status.
objCom.StartSession("DeviceName");
}
void objCom_AvailabilityChanged(ComStatus status)
{
//Fired when session is started.
Changed(status.ToString());
}
}
And then i have a WinForms/WPF application (targeted for .Net 4.5) that creates a new instance of MyClass, subscribes to the Changed event and calls Init().
This works perfectly.
I'm trying to do the same in ASP.Net web forms application. The Init() method is being called, but the objCom_AvailabilityChanged event in MyClass is never fired.
public partial class WebForm1 : System.Web.UI.Page
{
private MyClass test = new MyClass();
protected void Page_Load(object sender, EventArgs e)
{
}
protected void Button1_Click(object sender, EventArgs e)
{
test.Changed += test_Changed;
test.Init();
}
void test_Changed(string newStatus)
{
TextBox1.Text = newStatus;
}
}
Please explain what am i doing wrong.
Thanks a lot!

How to use ServiceStack Logging but have it delivered through the IOC container

Title about sums up what I'm looking to achieve, although now that I'm posting some code I would also like to know if the LogFactory in the correct place.
Thank you,
Stephen
public class ContactAppHost : AppHostBase
{
//Tell Service Stack the name of your application and where to find your web services
public ContactAppHost() : base("Contact Web Services", typeof (ContactService).Assembly)
{
// Built into the framework without the IOC
LogManager.LogFactory = new NLogFactory();
}
public override void Configure(Funq.Container container)
{
//register any dependencies your services use, e.g:
container.Register<ICacheClient>(new MemoryCacheClient());
}
}
protected void Application_Start(object sender, EventArgs e)
{
new ContactAppHost().Init();
}
protected void Application_Error(object sender, EventArgs e)
{
}
ServiceStack only supports the configuration of a single logger which should ideally be specified before the AppHost is initialized, so all static ILog initalizers for all classes in ServiceStack use the configured logger, e.g:
protected void Application_Start(object sender, EventArgs e)
{
LogManager.LogFactory = new NLogFactory();
new ContactAppHost().Init();
}

how to create scheduler application for mail in asp.net?

my question is, I have to send mail at specific time daily, is there any way to do this in asp.net ?
give me appropriate suggestions.
Note : i don't want to run windows application or windows scheduler.
code which i used in global.asax
private static CacheItemRemovedCallback OnCacheRemove = null;
void Application_Start(object sender, EventArgs e)
{
// Code that runs on application startup
AddTask("Remoder", 5);
}
void Application_End(object sender, EventArgs e)
{
// Code that runs on application shutdown
}
void Application_Error(object sender, EventArgs e)
{
// Code that runs when an unhandled error occurs
}
void Session_Start(object sender, EventArgs e)
{
// Code that runs when a new session is started
}
void Session_End(object sender, EventArgs e)
{
// Code that runs when a session ends.
// Note: The Session_End event is raised only when the sessionstate mode
// is set to InProc in the Web.config file. If session mode is set to StateServer
// or SQLServer, the event is not raised.
}
private void AddTask(string name, int seconds)
{
OnCacheRemove = new CacheItemRemovedCallback(CacheItemRemoved);
HttpRuntime.Cache.Insert(name, seconds, null,
DateTime.Now.AddSeconds(seconds), Cache.NoSlidingExpiration,
CacheItemPriority.NotRemovable, OnCacheRemove);
}
public void CacheItemRemoved(string k, object v, CacheItemRemovedReason r)
{
// do stuff here if it matches our taskname, like WebRequest
// re-add our task so it recurs
AddTask(k, Convert.ToInt32(v));
}
public void Remoder()
{
HttpContext.Current.Response.Write("Hello Start");
}
Have a look at http://quartznet.sourceforge.net/
I think this technique from Jeff Himself is what you need:
https://blog.stackoverflow.com/2008/07/easy-background-tasks-in-aspnet/
I tried the hack ... turning your application global.asax into a virtual scheduler. It was my choice, because my server admin department simply refuses (because they don't understand) to do it with windows, or a database job.
If I had my druthers though, I'd use a database "job", since sql-server can send mail directly. Not sure what db you're using, but if you have the necessary access, I'd recommend looking for a solution like that, instead of trying to fool your asp.net app.

Action after 10 minutes ASP.NET

In ASP.NET C# how to make a action after 10 minutes? It must be without the use of browser... Obviously an server side action...
You could set a timer in Global.asax to fire every 10 minutes:
private static Timer m_MailUpdateTimer;
protected void Application_Start(object sender, EventArgs e)
{
m_MailUpdateTimer = new Timer(MailUpdateTimer_Check, null, TimeSpan.Zero, TimeSpan.FromMinutes(10));
}
private static void MailUpdateTimer_Check(object state)
{
// Do something here.
}
protected void Application_End(object sender, EventArgs e)
{
if (m_MailUpdateTimer != null)
m_MailUpdateTimer.Dispose();
}
Of course, this will only fire if the web application is active, so if there is no usage for a while and IIS unloads it from memory, then the timer will not fire.
You may also want to consider using a Windows service or a scheduled job, which might be better suited for your needs.

Ninject : ninject.web - How to apply on a regular ASP.Net Web (!MVC)

What I am looking is something similar to the below (http://github.com/ninject/ninject.web.mvc):
README.markdown
This extension allows integration between the Ninject core and ASP.NET MVC projects. To use it, just make your HttpApplication (typically in Global.asax.cs) extend NinjectHttpApplication:
public class YourWebApplication :
NinjectHttpApplication { public
override void OnApplicationStarted()
{
// This is only needed in MVC1
RegisterAllControllersIn("Some.Assembly.Name");
}
public override IKernel
CreateKernel() {
return new StandardKernel(new SomeModule(), new SomeOtherModule(),
...);
// OR, to automatically load modules:
var kernel = new StandardKernel();
kernel.AutoLoadModules("~/bin");
return kernel; } }
Once you do this, your controllers will be activated via Ninject, meaning you can expose dependencies on their constructors (or properties, or methods) to request injections.
Just want share how did I solved it using Visual Studio 2008
For those of you guys been to www.tekpub.com code below is kinda familiar, Yes! your correct code below is from Mastering ASP.NET MVC 2.0 series, and a demonstration of how to use NLog
Needed Reference:
Ninject.dll
Ninject.Web
NLog.dll
Global.asax :
<%# Application Language="C#" Inherits ="Ninject.Web.NinjectHttpApplication" %>
<%# Import Namespace="App_Code.Infrastructure.Logging"%>
<%# Import Namespace="Ninject.Modules"%>
<%# Import Namespace="Ninject"%>
<script runat="server">
void Application_Start(object sender, EventArgs e)
{
// Code that runs on application startup
}
void Application_End(object sender, EventArgs e)
{
// Code that runs on application shutdown
}
void Application_Error(object sender, EventArgs e)
{
// Code that runs when an unhandled error occurs
}
void Session_Start(object sender, EventArgs e)
{
// Code that runs when a new session is started
}
void Session_End(object sender, EventArgs e)
{
// Code that runs when a session ends.
// Note: The Session_End event is raised only when the sessionstate mode
// is set to InProc in the Web.config file. If session mode is set to StateServer
// or SQLServer, the event is not raised.
}
protected override void OnApplicationStarted()
{
//base.OnApplicationStarted();
Container.Get<ILogger>().Info("Application Started");
}
protected override IKernel CreateKernel()
{
return Container;
}
static IKernel Container
{
get
{
return new StandardKernel(new SiteModule());
}
}
class SiteModule : NinjectModule
{
public override void Load()
{
Bind<ILogger>().To<NLogger>().InSingletonScope();
}
}
</script>
As you didnt rule it out in your question, I have to assume you're not aware of the WebForms equivalent of the one you cited
(Linked from the Ninject extensions index on the home site)

Resources