how to create scheduler application for mail in asp.net? - 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.

Related

ASP.NET initialization of array

I have website with array (list) of 1000 objects, these objects are loading from json to array every website refresh. I would like to load these objects from json to array only once and keep it in RAM for others users. Because everytime read file is much slower than read it from RAM.
I am using ASP.NET Web Forms
How is it posssible?
I would recommend to define the array as an static member of a class and then initialize it with help of Global.asax, use the Application_Start event handler.
to add Global.asax to you project in Visual Studio:
File -> New -> File -> Global Application Class
Here is a sample C# code for Global.asax.cs:
public class Global : HttpApplication
{
protected void Application_Start(object sender, EventArgs e)
{
// ... Your initialization of the array done here ...
}
protected void Session_Start(object sender, EventArgs e)
{
}
protected void Application_BeginRequest(object sender, EventArgs e)
{
}
protected void Application_AuthenticateRequest(object sender, EventArgs e)
{
}
protected void Application_Error(object sender, EventArgs e)
{
}
protected void Session_End(object sender, EventArgs e)
{
}
protected void Application_End(object sender, EventArgs e)
{
}
}
Are these values static, i.e., do they stay constant while your application is running? In that case, the easiest way is to cache those values.
You can use static variables for that, but the recommended way is to use the thread-safe Cache object provided by ASP.NET. It can be accessed with the Cache property of the Page or of the HttpContext.
Example:
var myList = (MyListType)Cache["MyList"];
if (myList == null)
{
myList = ...; // Load the list
Cache["MyList"] = myList; // Store it, so we don't need to load it again next time.
}
Further reading:
Caching Application Data

WCF\ASP.NET interoperability

I have a server application written in WCF using asynchronous callbacks, and a webforms application in ASP.NET.
All of the communication is fine between the 2 applications, I can call the exposed functions in the server via the web application, and the server can send callbacks to the web application, however sometimes the functions within the callback work, and other times, they don't.
For example, I would like a login button on the web app to send a username and password to the server, the server checks this against the database, and if the login information is correct, it should send a callback, which opens a new page in the web app.
Here is the relevant server code:
public void Login(String username, String password)
{
//DoCheckAgainstDatabase(username, password);
ICallback callback = OperationContext.Current.GetCallbackChannel<ICallback>();
callback.LoginSuccess();
}
and the web application code:
private InstanceContext _instanceContext;
private ServiceClient _service;
public CallbackHandler MyCallbackHandler = new CallbackHandler();
protected void Page_Load(object sender, EventArgs e)
{
_instanceContext = new InstanceContext(MyCallbackHandler);
_backEnd = new ServiceClient(_instanceContext, "NetTcpBinding_IAU", "net.tcp://localhost/MyService/Service");
_backEnd.Open();
MyCallbackHandler.LoginSucceeded += OnLoginSucceeded;
}
protected void LoginButton_Click(object sender, EventArgs e)
{
_backEnd.Login(UsernameTextBox.Text, PasswordTextBox.Text);
}
private void OnLoginSucceeded(object sender, EventArgs e)
{
ScriptManager.RegisterStartupScript(this.Page, Page.GetType(), "OpenClientWindow", "window.open('Client.aspx','_self');", true);
}
I can put in breakpoints, and see that everything is working fine, it's just that the code 'ScriptManager.RegisterStartupScript...' does not execute properly all the time.
Could this be something to do with threading? Could anyone suggest a way to fix this please?
Thanks in advance!
David
It occurs to me that it's possible your page life cycle may be ending - or at least getting to the Render stage, which is where the start up script would be written to the output - before the callback is called.
Is it possible to call your service synchronously, and not proceed out of LoginButton_Click until the service call returns?
I think you are missing script tag - wrap your window.oppen with it, like
ScriptManager.RegisterStartupScript(this.Page, Page.GetType(), "OpenClientWindow", "<script>window.open('Client.aspx','_self');</script>", true);
Thank you Ann L. for guidance on this. I have added a ManualResetEvent, and then in the button click method, I wait until I have received the callback, then proceed with opening the new page:
private InstanceContext _instanceContext;
private ServiceClient _service;
public CallbackHandler MyCallbackHandler = new CallbackHandler();
private ManualResetEvent _resetEvent = new ManualResetEvent(false);
protected void Page_Load(object sender, EventArgs e)
{
_instanceContext = new InstanceContext(MyCallbackHandler);
_backEnd = new ServiceClient(_instanceContext, "NetTcpBinding_IAU", "net.tcp://localhost/MyService/Service");
_backEnd.Open();
MyCallbackHandler.LoginSucceeded += OnLoginSucceeded;
}
protected void LoginButton_Click(object sender, EventArgs e)
{
_backEnd.Login(UsernameTextBox.Text, PasswordTextBox.Text);
_resetEvent.WaitOne();
ScriptManager.RegisterStartupScript(this.Page, Page.GetType(), "OpenClientWindow", "window.open('Client.aspx','_self');", true);
}
private void OnLoginSucceeded(object sender, EventArgs e)
{
_resetEvent.Set();
}

How to log activity on Session Timeout or Window close

In my application, we want to log some activity and messages to the DB when the window is closed by the user or when the session timesout. Is there any tested code to do this? Is writing this code in Session_End method of Global.asax.cs the right way?
You may be able to do something like this for the session (note that there is no guaranteed way to check for a browser closing). This approach will only work if you are using inProc for your session.
In your global.asax.cs
protected void Session_Start(object sender, EventArgs e)
{
//a value must be present to call Session_End so we pre-seed it
Session["SeededValueToEnableSession_End"] = true;
}
protected void Session_End(object sender, EventArgs e)
{
//handle session ending
}

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.

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

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();
}

Resources