There is a web site, and when user exceed 1000, there is an error which is called
Service unavailable
And I want to show a text, when the system gives "service unavailable" error. How can I do it?
(app_offline.htm can be used but I want to automize it)
In case you're dealing with ASP.NET, you can create your own html page with your custom text, then configure the web.config file, more specifically the customErrors tag, to show that file when a 503 Http code is sent to the client (that is again, assuming that IIS is sending the 503 code to the browser).
Hope that helps.
Cheers.
There may be sevaral possible reasons this problem,
Simultaneous connection may reached the time limit
Your app pool may not starting properly
There is an interesting article about One more reason problem that causes the 'Service Unavailable' error from IIS, which might give you a better understand.
As you state that you're using ASP.NET you should look at trapping errors using the Page_Error event handler.
As this tends to be repeated code both in one project and many other projects, I use a base class that inherits from System.Web.UI.Page and fill in the handler there.
For example all pages based on MyBasePage
protected void Page_Error(object sender, EventArgs e)
{
Exception ex = Server.GetLastError();
this.ErrorRedirect(ex, false);
}
/// <summary>
/// Redirects to a custom error page
/// </summary>
/// <param name="ex">the caught exception</param>
/// <param name="errorCaught">true if the error is handled within a try catch block, false otherwise</param>
protected void ErrorRedirect(Exception ex, bool errorCaught)
{
/* some logging code here for use by support team */
if (ex.GetType().FullName == "BusinessObjects.BrokenRulesException" )
{
Response.Redirect("ContactHelpdesk.aspx");
}
if (errorCaught)
{
Response.Redirect("ContactHelpdesk.aspx");
}
else
{
Response.Redirect("Error.aspx");
}
}
In this code "BusinessObjects.BrokenRulesException" are thrown when my there are issues with user entered Model data that doesn't match specified rules e.g. postcodes, passwords etc. in which case a user help page pops up.
In your case you'd be looking at errors to maybe pop up the Error page.
Related
I have added try catches in my site which work great. The next part in development is to set up some exception handling output. Obviously I don't want the site to crumble when an error occurs and I don't want a horrible error screen. So, somewhere in the middle would be nice.
I was thinking to have an exception handler user control in the main master page which wil output a nice little message when something goes wrong.
What would be the best way to pass the exception to this user control? I was thinking of using a session variable.
Does anyone have a solution to this problem?
Thanks
This is easier than you're making it. Create a page called error.aspx (or whatever you want to call it), and turn the CustomErrors on in the web.config.
<configuration>
<system.web>
<customErrors defaultRedirect="errors.aspx"
mode="On">
</customErrors>
</system.web>
</configuration>
There is a lot of configurability to handle different http errors or random exceptions. If you want, you can dump the exception message (or the exception itself) into the session or use the HttpServerUtility.GetLastError (documentation)and then output any number of different messages on the error page. This will even catch exceptions that you DON'T catch.
CustomErrors Documentation
Edit:
#Icarus indicates that OP is looking for a solution by which the page continues to render and output while only showing an error message within the page, so I'll provide an answer to that as well.
There are a few ways I've handled this in the past. For very complex pages where the behavior requested is fatal (the page result can't be known), I've always deferred to an error page as I mentioned above that includes major master elements. So the menu, header, etc are all still there, but the notification of cataclysm is evident.
The behavior you seem to be looking for is something I would use less out of a need to report exceptions than to report general messages. My preference is to have a user control that has a public bindable property that a message can be injected into. Such as (forgive the VB, I can't seem to find my C# version):
<BrowsableAttribute(True), Bindable(False), Category("Misc"), _
Description("Gets or sets the NavigateUrl property for the link to start a new request.")> _
Public Property MyImportantMessage() As String
Get
Return _myImportantMessage
End Get
Set(ByVal value As String)
_myImportantMessage= value
End Set
End Property
Then the output could be any string message you like or you could program in a number of presets, fetch from resources, whatever. As to how to get it in there, we have taken the MasterPage route. We have a method in our master pages which assigns such a property in the user control directly. In order for this method to be callable, each page that uses the master page has to include the VirtualPath property, otherwise the method will not be available at compile time.
<%# MasterType
VirtualPath="~/MasterPage.master" %>
This then allows the Master property to be called from within the page itself to call this property:
'Keeping the VB theme
Me.Master.SetImportantMessage(message)
Keep in mind that Me.Master from within the page is not the same as Page.Master. So your exception will either need to bubble up to the actual page or the page reference itself will have to be sent down to your usercontrols as a property.
If you're wanting to provide an error for a handled exception, it's really as simple as populating a label with some sort of a notice that the application had a problem processing a request. You would do this within the "catch" part of the statement. I've even gone as far as presenting different messages depending on the role of the user. For instance if an admin generates an error you could actually output the actual exception message, but if someone in a lesser role generates it it would show them a more generic error and send the admin group a message/email.
try
{
//your code here
}
catch (Exception ex)
{
if (Role!="Admin")
{
Label1.Text = "There was an error, the administrator has been notified."
}
else
{
Label1.Text = "Error: " + ex.Message + ": " + ex.StackTrace; //you could add further here if you want to look for an inner exception.
}
}
I need a coding to get response from my desktop application to my web page using asp.net
I send a request from my recharge.aspx page to desktop application.
http://122.172.208.202/MARSrequest/?operator=RA&number=9900122334&amount=100&reqref=A0000001
so my desktop application get the request and perform the task and send the response to other page that is responseparser.aspx
the response like
http://www.abc.com/responseparser.aspx?ref=10293&number=9894380156&amount=100&status=SUCCESS&transid=547965399 &simbal=1000
so how to get response with out loading the responseparser page it is possible or any other idea to get the response.
my doubt is without loading a page can able to perform some operation like insert a record or create text file using asp.net
You appear to have asked this question several times in several different ways. This is not an acceptable way of using StackOverflow. If your original question is not getting the answer(s) your looking for, please consider editing and revising your question. Please consider commenting on your questions and taking the advice of other commenters.
To answer your question. I think you're looking to execute some sort of Web Service instead of loading a page. Does this sound right?
If so, I'd suggest either using one of the following
a generic HttpHandler (more info in this forum post)
a WCF application that can manage your service layer.
an MVC Application that manages the requests (this is my personal favorite - I build these completely without Views and simply return JSON for all of my {success: true/false}.)
In short, the quickest way I can think of to do this would be to use the FIRST option (HttpHandler) and change your request to the following
http://localhost/responsepage.ashx?number=9894380156&amount=10&status=success
Notice the ashx extension on the response page. It's no longer a web page but a web handler... you'll want to do some research in order to get a handle on it.
Not sure if this if this works same for desktop applications but maybe it works with
protected void YourThing()
{
Refresh();
}
protected void Refresh()
{
Response.redirect(Request.Rawurl);
}
not sure but try
for(!Page.IsPostback)
{
do stuf here
}
You can use WebService or HttpHandler.
I would prefer WebService (parser.asmx):
namespace Test.Service
{
[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
[ToolboxItem(false)]
public class WebService1 : WebService
{
[WebMethod]
public void Parse(string #ref, long number, double amount, string status, int transid, int simbal)
{
// some code
}
}
}
POST-request example:
POST /{path}/Parser.asmx/Parse HTTP/1.1
Host: ***
Content-Type: application/x-www-form-urlencoded
Content-Length: ***
ref=string&number=string&amount=string&status=string&transid=string&simbal=string
I think you can easily port your ASP code using the SqlClient classes.
Most suitable variant for you is SqlCommand with ExecuteNonQuery method:
using (SqlConnection connection = new SqlConnection(
connectionString))
{
SqlCommand command = new SqlCommand(queryString, connection);
command.Connection.Open();
command.ExecuteNonQuery();
}
In that case, I usually put whatever appropriate ADO.NET code into page_load but since you want to do it before page loading, why don't you use "page_init"? For example, put following code into code-behind
protected void Page_Init(object sender, EventArgs e)
{
//your code is here
}
You can get the name of a page within HttpContext via Request.Path.
Is there a way to distinguish between different requests from the same page?
That is when two different instances of yourpage.aspx make a request, how can you distinguish between the two using HttpContext?
you probably want to do this in a base Page class, but here's what i would do
public partial class Default : System.Web.UI.Page
{
private Guid _instanceID;
public Guid InstanceID
{
get { return _instanceID; }
}
/// <summary>
/// Constructor
/// </summary>
public Default()
{
this._instanceID = Guid.NewGuid();
}
}
then using the HttpContext somewhere else in your code...
if (HttpContext.Current.CurrentHandler is Default)
{
((Default)HttpContext.Current.CurrentHandler).InstanceID;
}
Nothing built into ASP.NET will allow you to differentiate different "page instances" or requests from them.
However, you can easily add a Guid to your view state to uniquely identify each page. This mechanism works fine when you are in the Page class itself. If you need to identify requests before you reach the page handler, you need to use a different mechanism (since view state is not yet restored).
The Page.LoadComplete event is a reasonable place to check if a Guid is associated with the page, and if not, create one.
If you're using authentication, would it work for you to distinguish which user submitted the page?
You could use System.Web.Httpcontext.Current.User.Identity.Name.
just throwing this out there: NInject (and other DI containers) use a scoping mechanism based on the HttpContext.Current object itself, so depending on what you're trying to do, you could attempt to retrieve a state object from the DI container and go from there.
I could see, myself and many people are having trouble with this two items in ASP.NET... Refresh Button, Back Button... (I see many people went to the exent of asking how to disable these two buttons in the browser..)
Now what are the problems in Implementing two more boolean variables in Page (IsRefresh, IsPostBack)... If those problems can be circumvened and implemented, it would be a great asset to developers...
When you are answering, if you could also include the steps you are taking in your web app in order to avoid reposting (at times in DB) in such scenarios that would be helpful.
Thanks
The problem with implement the two additional boolean properties is, that there really is no (reliable) way to distinguish Back / Refresh triggered requests. When hitting on of these buttons, the browser will either:
display the page from the cache if allowed, or
execute the exact same request again (possibly asking the user to confirm first)
You are experiencing case #2. When the second request occurs, the server will recieve the exact same request data as it did with the original request. Thus, ASP.NET (and most other frameworks) will handle the request just like the original was handled. There are several ways to work around this problem:
Change your caching policy to allow the browser to redisplay the results of previous requests (might solve the Back problem, but not Refresh).
Add a hidden field (or data in the ViewState) containing a unique value on the page from where postbacks are expected. Then add some data structure to keep a list of "used" values, along with logic to test for duplicates before doing anything critical.
Use the Post/Redirect/Get pattern to ensure that the POST request never ends up in the browser history.
Solution #3 is dead easy, and works in almost every case. Basically, rather then returning the results/confirmation as a reply to the "critical" postback, do a redirect to a new URL:
protected void btnCritical_Click(object sender, EventArgs e)
{
DoSomethingThatShouldNotBeDoneTwice();
Response.Redirect("confirmation.aspx");
}
aspnet_isapi recognizes a postback from the form content, specifically the ViewState field. It has no intrinsic way to distinguish a postback from a refresh.
i have seen a few strategies for working with this in the past. One is to assign each request a guid and use that as a unique key or index in the table you are writing to.
You can create a base page that all of your pages inherit from.
public partial class PageBase : System.Web.UI.Page
{
private Guid _requestId;
protected Guid RequestId
{
get
{
return _requestId;
}
}
protected virtual void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
_requestId = Guid.NewGuid();
ViewState.Add("requestId", _requestId);
}
else
{
_requestId = (Guid)ViewState["requestId"];
}
}
}
public partial class _Default : PageBase
{
protected override void Page_Load(object sender, EventArgs e)
{
base.Page_Load(sender, e);
// now do stuff
}
}
It's not quite that clear cut. The only way the server can identify a "PostBack" is based on the headers passed to the page by your request. When you POST a form, "IsPostBack" is true, as you would expect. When you refresh a page or press Back the exact same request data is sent. There's no way for the application to detect that the user issued a non-standard request (Back or Refresh) without changing the behavior of the browser that sends the request.
As you know, most browsers will indicate to you that "Clicking Back will resend the form data...", but that is merely a warning issued by the browser to let you know that it is going to send the exact same request over again. The server does not know this and has no (native) way to interpret the information.
Double Postback Prevention Tips
One way to prevent data getting posted twice is to ensure that each PostBack contains some unique data that you can validate. The process is fairly simple.
On each page load you will want to create a unique identifier for that page's PostBack events. It doesn't matter what the unique id is, so long as it isn't the same on sequential page loads. Place that unique identifier in a hidden field on your page AND in the user's session (or a cookie). Then, on each PostBack validate that the cookie in the hidden field matches the value in the session. If the values match the PostBack is an original post to the page which can be processed accordingly. After performing the necessary operations you will then need to change the unique identifier in both locations again. This way, if the user should hit back and choose to "Resend Data", the hidden field will not match the session key and you can throw out the duplicate post data.
What is a good error handling practice for an asp.net site? Examples? Thanks!
As with any .net project I find the best way is to only catch specific error types if they are may to happen on the given page.
For example you could catch Format Exceptions for a users given input (just incase JavaScript validation fails and you have not use tryparse) but always leave the catching of the top level Exception to the global error handler.
try
{
//Code that could error here
}
catch (FormatException ex)
{
//Code to tell user of their error
//all other errors will be handled
//by the global error handler
}
You can use the open source elmah (Error Logging Modules and Handlers) for ASP.Net to do this top level/global error catching for you if you want.
Using elmah it can create a log of errors that is viewable though a simple to configure web interface. You can also filter different types of errors and have custom error pages of your own for different error types.
One practice that I find to be especially useful is to create a generic error page, and then set your defaultRedirect on the customErrors node of the web.config to that error page.
Then setup your global.asax for logging all unhandled exceptions and then put them (the unhandled exceptions) in a static property on some class (I have a class called ErrorUtil with a static LastError property). Your error page can then look at this property to determine what to display to the user.
More details here: http://www.codeproject.com/KB/aspnet/JcGlobalErrorHandling.aspx
Well, that's pretty wide open, which is completely cool. I'll refer you to a word .doc you can download from Dot Net Spider, which is actually the basis for my small company's code standard. The standard includes some very useful error handling tips.
One such example for exceptions (I don't recall if this is original to the document or if we added it to the doc):
Never do a “catch exception and do nothing.” If you hide an exception, you will never know if the exception happened. You should always try to avoid exceptions by checking all the error conditions programmatically.
Example of what not to do:
try
{
...
}
catch{}
Very naughty unless you have a good reason for it.
You should make sure that you can catch most of the errors that are generated by your application and display a friendly message to the users. But of course you cannot catch all the errors for that you can use web.config and defaultRedirect by another user. Another very handy tool to log the errors is ELMAH. ELMAH will log all the errors generated by your application and show it to you in a very readable way. Plugging ELMAH in your application is as simple as adding few lines of code in web.config file and attaching the assembly. You should definitely give ELMAH a try it will literally save you hours and hours of pain.
http://code.google.com/p/elmah/
Code defensively within each page for exceptions that you expect could happen and deal with them appropriately, so not to disrupt the user every time an exception occurs.
Log all exceptions, with a reference.
Provide a generic error page, for any unhandled exceptions, which provides a reference to use for support (support can identify details from logs). Don't display the actual exception, as most users will not understand it but is a potential security risk as it exposes information about your system (potentially passwords etc).
Don't catch all exceptions and do nothing with them (as in the above answer). There is almost never a good reason to do this, occasionally you may want to catch a specific exception and not do any deliberately but this should be used wisely.
It is not always a good idea to redirect the user to a standard error page. If a user is working on a form, they may not want to be redirected away from the form they are working on. I put all code that could cause an exception inside a try/catch block, and inside the catch block I spit out an alert message alerting the user that an error has occurred as well as log the exception in a database including form input, query string, etc. I am developing an internal site, however, so most users just call me if they are having a problem. For a public site, you may wish to use something like elmah.
public string BookLesson(Customer_Info oCustomerInfo, CustLessonBook_Info oCustLessonBookInfo)
{
string authenticationID = string.Empty;
int customerID = 0;
string message = string.Empty;
DA_Customer oDACustomer = new DA_Customer();
using (TransactionScope scope = new TransactionScope())
{
if (oDACustomer.ValidateCustomerLoginName(oCustomerInfo.CustId, oCustomerInfo.CustLoginName) == "Y")
{
// if a new student
if (oCustomerInfo.CustId == 0)
{
oCustomerInfo.CustPassword = General.GeneratePassword(6, 8);
oCustomerInfo.CustPassword = new DA_InternalUser().GetPassword(oCustomerInfo.CustPassword, false);
authenticationID = oDACustomer.Register(oCustomerInfo, ref customerID);
oCustLessonBookInfo.CustId = customerID;
}
else // if existing student
{
oCustomerInfo.UpdatedByCustomer = "Y";
authenticationID = oDACustomer.CustomerUpdateProfile(oCustomerInfo);
}
message = authenticationID;
// insert lesson booking details
new DA_Lesson().BookLesson(oCustLessonBookInfo);
}
else
{
message = "login exists";
}
scope.Complete();
return message;
}
}