Call ApplicationStart Method in Global.asax Without a Request - asp.net

I'm publishing my asp.net site with iis( my local machine has iis v8, server's iis v7 ).
But I want to start a function in Global.asax.cs immediately without calling a page.
*When I call a page, global.asax.cs Application_Start method launches. I want to launch it without a page call request.*
namespace ProductService.XmlFeed
{
public class Global : HttpApplication
{
protected void Application_BeginRequest(Object sender, EventArgs e)
{
FtpUploaderMain.RegisterCacheEntry(); //this method I want to start without page call
}
void Application_Start(object sender, EventArgs e)
{
SimpleLogger.WriteLog("Application Started without a page call","D:\\log.txt");
RegisterRoutes();
//FtpUploaderMain.RegisterCacheEntry();
}
private void RegisterRoutes()
{
RouteTable.Routes.Add(new ServiceRoute("Products", new WebServiceHostFactory(), typeof(ProductXmlFeedService)));
}
}
}

You can use PreLoad enabled feature of IIS8 -
For IIS 7.5 use application- initialization -
http://www.iis.net/downloads/microsoft/application-initialization

Related

SignalR and .NET Client does not work on ASP.NET WebForms page

I try to build notifications for dashboard in my WebForms application under .NET 4. I have downloaded SignalR version 1.2 (both .net client and server) and prepared a simple notification example. Unfortunatelly it does not work and I can't figure why. If I type http://myserver.com/notificationSample/signalr/hubs javascript proxy appears and it looks ok.
Take a look at the implementation below, does someone see any bug?
a) Hub implementation
[HubName("NewMessage")]
public class NewMessageNotifier : Hub
{
public void NotifyDashboards()
{
Clients.All.NewMessageCreated();
}
}
b) Notification caller (server) ~/Pages/NotificationCaller.aspx
public partial class NotificationCaller : Page
{
private HubConnection connection;
private IHubProxy proxy;
protected void Page_Load(object sender, EventArgs e)
{
connection = new HubConnection( "http://myserver.com/notificationSample" );
proxy = connection.CreateHubProxy( "NewMessage" );
connection.Start().Wait();
}
// it is handler for onclick event on Button control
protected void NotifyDashboard(object sender, EventArgs e)
{
proxy.Invoke( "NotifyDashboards" ).Wait();
}
}
c) Dashboard (client, listener) ~/Pages/Dashboard.aspx
public partial class Dashboard: BasePage
{
private HubConnection connection;
protected void Page_Load(object sender, EventArgs e)
{
connection = new HubConnection( "http://myserver.com/notificationSample" );
var proxy = connection.CreateHubProxy("NewMessage");
proxy.On("NewMessageCreated", ShowNotification);
connection.Start();
}
private void ShowNotification()
{
ShowAlert("New message added!");
}
}
you are using it in the wrong way
First
both b and c are clients, the server gets started by itself, all you need is to do is to add
RouteTable.Routes.MapHubs();
to the
Application_Start
method in global.asax
Second
if you are going to use a webpage as the client, you should do it from javascript, as what you are doing now will not work because the
connection.Start()
is async and the request will end before it does anything, and it will not wait for incoming connections because all will be disposed
Now how to do it? it will take many pages here, so here are a few links
A Simple Tutorial
The Hubs Server API
The Hubs JavaScript API
and in case you missed it, a video that explains what is SignalR, how it works and a simple app which you can find here

IIS turned off my application automatically?

I just noticed that IIS turned off my ASP.NET web application automatically after it idled 20 minutes. The website is hosted on Godaddy.com.
Below is the Global class which logs the Application_Start and Application_End methods. And the image I uploaded is the result that I saw.
It turned off at 2013-05-24 06:42:40 after the last call I did at 06:22:01. (20 minutes, hua...)
After one day, I did another call at 2013-05-25 03:05:27, the website was awakened.
Strange? I didn't want my website to sleep. Is there any way to keep it sane all the time?
public class Global : HttpApplication
{
private static readonly ILog log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
protected void Application_AuthenticateRequest(object sender, EventArgs e)
{
log.Debug("Application_AuthenticateRequest -> " + base.Context.Request.Url);
}
protected void Application_End(object sender, EventArgs e)
{
log.Info("Application_End");
}
protected void Application_Start(object sender, EventArgs e)
{
log.Info("Application_Start");
}
}
The IIS/asp.net is turn off the application if you do not have any request for some time to save resource.
Now this usually handle on server side if you wish to avoid it, but in your case you can't interfere with the IIS setup, so one trick is to create a timer that reads every 10 minutes or so one page.
You start it when application starts, and do not forget to stop it when application is go off.
// use this timer (no other)
using System.Timers;
// declare it somewhere static
private static Timer oTimer = null;
protected void Application_Start(object sender, EventArgs e)
{
log.Info("Application_Start");
// start it when application start (only one time)
if (oTimer == null)
{
oTimer = new Timer();
oTimer.Interval = 14 * 60 * 1000; // 14 minutes
oTimer.Elapsed += new ElapsedEventHandler(MyThreadFun);
oTimer.Start();
}
}
protected void Application_End(object sender, EventArgs e)
{
log.Info("Application_End");
// stop it when application go off
if (oTimer != null)
{
oTimer.Stop();
oTimer.Dispose();
oTimer = null;
}
}
private static void MyThreadFun(object sender, ElapsedEventArgs e)
{
// just read one page
using (System.Net.WebClient client = new System.Net.WebClient())
{
client.DownloadData(new Uri("http://www.yoururl.com/default.aspx"));
}
}
One note, do not use this trick unless you needed because you create one more thread living for ever. Usually google reads the web pages and keep it "warm", the auto turn off usually occurs if you have a very new site that google and other search engines did not start to index, or if you have one two page only that never change.
So I do not recomended to do it - and is not bad to close your site and save resource, and your site is clear from any forgotten open memory and start fresh...
Similar Articles.
Keep your ASP.Net websites warm and fast 24/7
Application Initialization Module for IIS 7.5
Auto-Start ASP.NET Applications (VS 2010 and .NET 4.0 Series)

Custom HTTP handler for URL rewriting + session and application variable

Currently my product page URL is like
http://www.localhost:80/products/default.aspx?code=productCode
I want to access product page with
http://www.localhost:80/productCode
I have used HTTP module for this.
public class UrlRewritingModule : IHttpModule
{
public void Dispose()
{
}
public void Init(HttpApplication context)
{
context.PreRequestHandlerExecute += new EventHandler(context_PreRequestHandlerExecute);
context.AuthorizeRequest += new EventHandler(context_AuthorizeRequest);
}
void context_AuthorizeRequest(object sender, EventArgs e)
{
HttpContext context = ((HttpApplication)sender).Context;
if (some condition)
{
context.RewritePath(url);
}
}
void context_PreRequestHandlerExecute(object sender, EventArgs e)
{
//We set back the original url on browser
HttpContext context = ((HttpApplication)sender).Context;
if (context.Items["originalUrl"] != null)
{
context.RewritePath((string)context.Items["originalUrl"]);
}
}
}
I have register it in web.config and it is working fine. But when I deploy it in IIS that session and application variables are not throwing null referent Exceptions.
Can anyone help me?
Edit: Do it require extra code to access session/ Application variable for rewritten URLs
?
Have you tried using HTTPContext.Current?
I was able to solve issue (accessing session and application variables in subsequent pages rewritten by custom handler) by adding runAllManagedModulesForAllRequests="true" attribute in modules in web.config.

Url routing Access denied at hosting

I'm using url routing in my asp.net website.I put colde in glocal.asax Application_Start event , void
Application_Start(object sender, EventArgs e)
{
// Code that runs on application startup
RouteTable.Routes.MapPageRoute("routedetail",
"alllist/special/{Name}",
"~/sub/mydetail.aspx");
RouteTable.Routes.MapPageRoute("routelist",
"alllist/special",
"~/sub/mylist.aspx");
RouteTable.Routes.MapPageRoute("routehtml", "alllist/myhtml.html", "~/sub/to.aspx");
}
Every thing is ok in my local development and iis7.The error is at online hosting
"routehtml" is not work.Access denied occour.Is it for .html extension ?How can i solved this problem.any suggession..
Try putting that into global.asax
void Application_BeginRequest(object sender, EventArgs e)
{
HttpApplication app = sender as HttpApplication;
if(app.Request.Path.IndexOf("FriendlyPage.html") > 0)
{
app.Context.RewritePath("/UnfriendlyPage.aspx?SomeQuery=12345");
}
}
You may want to check that your IIS 7 Application Pool is in Integrated mode on your host server. It will not work if it isn't.
Although you wouldn't need it, but you could also set RouteExistingFiles property to false at the top of your Application_Start event.

ASP.NET Mono: How to send SOAP instead of HTML?

I have an ASP.NET web service based on SOAP built on top of Mono.
If I throw exceptions inside the service, the exceptions remain on the HTTP+HTML level. What I'd like to do is send always all exceptions as SOAP responses, i.e. I don't have any normal aspx pages (everything should work with SOAP).
I've tried handling all exceptions in the Global.asax.cs file within the Application_Error() method, but it seems to always send the exceptions as HTML.
What I see is the generic ASP.NET error page.
My SOAP client, when pointed to the HTML, informs me that it cannot parse HTML.
Sending SOAP from the server works nicely when no exceptions are thrown.
I've studied various web sources and learned that Application_Error shouldn't be used for SOAP exception handling from this resource:
Handling and Throwing Exceptions in XML Web Services
Do I have to implement my own HTTP Module or
ExceptionUtility Class or HTTP Handler?
I am running this on my development machine:
Version information: Mono Runtime Version: 2.10.5 (Debian 2.10.5-1); ASP.NET Version: 4.0.30319.1
I am testing this with MonoDevelop's built-in xsp HTTP server inside Ubuntu 11.10.
Here is my test code:
Global.asax.cs:
using System;
using System.Collections;
using System.ComponentModel;
using System.Web;
using System.Web.SessionState;
using System.Web.Services.Protocols;
namespace SoapTaikina
{
public class Global : System.Web.HttpApplication
{
protected virtual void Application_Start (Object sender, EventArgs e)
{
Backend.Initialize();
}
protected virtual void Application_Error (Object sender, EventArgs e)
{
// This doesn't appear to be executed when Foo() throws an exception.
// I cannot catch the Foo() constructor exception here.
throw new SoapException("This is never reached.", null);
}
// These are not used in this example.
protected virtual void Session_Start (Object sender, EventArgs e) { }
protected virtual void Application_BeginRequest (Object sender, EventArgs e) { }
protected virtual void Application_EndRequest (Object sender, EventArgs e) { }
protected virtual void Application_AuthenticateRequest (Object sender, EventArgs e) { }
protected virtual void Session_End (Object sender, EventArgs e) { }
protected virtual void Application_End (Object sender, EventArgs e) { }
}
}
Foo.asmx.cs:
using System;
using System.Web;
using System.Web.Services;
namespace SoapTaikina
{
public class Foo : System.Web.Services.WebService
{
public Foo()
{
// This may throw an Exception which will not be caught in
// Application_Error().
//
// This is the problem spot.
Backend2.InitializeMoreStuff();
}
[WebMethod]
public bool DoStuff() {
// This works fine and returns a SOAP response.
return true;
}
}
}
First, theory
Application_Error is never fired according to .NET Framework requirements. This is because the pipeline that runs pages is different from the one that runs web services. Also, notice that throwing exceptions in Application_Error is a very bad idea.
I found that testing web services from the browser (where, and probably because, accept header is not set to application/soap+xml but to text/html) makes a plaintext message appear. If the client is a SOAP proxy (ie you generated in Visual Studio/MonoDevelop from the web service's WSDL) and inherits from SoapHttpClientProtocol then it is expected that the exception is always thrown as SOAP fault.
Second, practice.
You do var f = new Foo() from Application_Start. This is wrong because the web service skeleton class is instantiated fresh new on every HTTP/SOAP request, and should never be initialized in the special Application_Start method that is run on the very first request and without the request itself bein processed yet. Also, you should avoid to do complex things (that may throw exceptions) in web service's constructor. This is just a bad design, not a non-compiling or non-working solution.
Your problem probably occurs because the ASP.NET pipeline never reached the point where the request is mapped to a web service handler rather than a page handler, firing default behaviour. Tried to find the code in mono repository, no luck :)
I suggest you to first remove any WS initialization in Application_Start, and if you said you don't really need it, throw away Application_Error

Resources