How to Get Back the Alert to Run Program With Build Erros Again in .net
The Microsoft release of ASP.NET Web Forms had most .Net developers excited for a new framework to replace old Classic ASP scripting. However, Web Forms made information technology tedious to proceed track of page states resulting in spaghetti lawmaking for many web projects.
When MVC was introduced, it made spider web evolution much easier with the model, view, controller structure. Merely it as well introduced its own complications, and many.NET programmers ran into challenges when switching to MVC.
In this commodity, nosotros've compiled some of the most common errors in ASP.NET and how to resolve them.
High Response Execution Time
Request fourth dimension in any awarding is a combination of good code and optimized server configurations. Just one poorly optimized component in a web application tin upshot in high execution times and eventually time out. Performance bug are one of the nearly difficult issues to resolve because the root cause could be whatsoever number of issues. Poorly written lawmaking, poorly written database queries, inadequate server resources, low bandwidth, and even malfunctioning hardware tin can exist the root crusade of a tiresome-performing application.
When applications time out, a server administrator might kickoff have a quick look at server resources using Windows Job Managing director on the server.
High CPU, memory or Ethernet utilization could mean that information technology's time to upgrade resource, but it could also hateful that code is poorly optimized. Should you find the awarding is failing due to high resource usage, a quick workaround is to restart the application pool in IIS. Annotation that this will take the awarding offline while the app pool restarts, but it'due south a quick emergency solution if the application is timing out and crashing.
As server resource fasten and your application's performance plummets, SolarWinds® Pingdom® identifies the fourth dimension it takes to reply. Pingdom too identifies if the application crashes and no longer responds to users, and can also warn you of imminent critical downtime. To larn more, check out our weblog on How to Analyze Web Application Performance Using SolarWinds.
Wearisome First Page Load
When initializing a web application in IIS, several server procedures fire up the awarding including processing static content, cached resource, the generation of dynamic data, and a server response sent to the user. Until the initialization finishes, user requests can appear to "hang," which could lead to a loftier bounce rate.
IIS eight.0 has an "Application Initialization" feature to better perceived site speed by proactively initializing content before receiving the beginning request. If information technology does receive a request, it can ship a relevant static page to the user while the application initialization procedure completes. The feature is installed from the Server Manager tool.
After installing the feature, yous must add together configuration entries into the applicationHost.config and spider web.config files.
In the applicationHost.config file, add the post-obit entry to the <applicationPools> department. Make certain y'all change the .Net version with the running version for the application.
<add together name=".Cyberspace v4.5" startMode="AlwaysRunning" managedRuntimeVersion="v4.0" /> Adjacent, scroll downwards to the <sites> section and add the following configuration within the <application> subsection. Once again, use the .NET version relevant to the application.
<application path="/appinit" preloadEnabled="true" applicationPool=".Cyberspace v4.v"> In the web.config file for the application, add the post-obit section to the <system.webServer> section.
<applicationInitialization remapManagedRequestsTo="StaticHome.htm" skipManagedModules="true" > <add initializationPage="/" /> </applicationInitialization> In the above configuration, the "StaticHome.htm" file will serve as the "splash page" when the application initializes.
After you brand these configurations, you must restart the IIS web service.
Showing Custom Errors
Fault treatment is essential in whatsoever awarding, and sending a custom message to users volition relieve potential sales. .NET default errors are too general, and leave your users unable to movement beyond the "yellow fault of death" page. Yous tin handle errors and provide your own custom message or handler using the application'south Web.config or Global.asax files.
You demand a view to brandish letters and a controller to process the view. In the following code examples, the "Error" controller is used to send the user to the "ErrorMessage" view. The get-go step is to change the "Application_Error" method in global.asax. We'll utilise a 404 error message as an example.
protected void Application_Error(object sender, EventArgs east) { Exception exc = Server.GetLastError(); Response.Clear(); HttpException httpException = exc as HttpException; if (httpException != null) { string controllerAction = System.string.Empty; switch (httpException.GetHttpCode()) { case 404: // page not found controllerAction = "Error404"; break; } // clear error on server Server.ClearError(); Response.Redirect(String.Format("~/Mistake/{0}/?message={1}", controllerAction, exc.Bulletin)); } } In the code to a higher place, the user is redirected to a URL generated using the controllerAction and the error message. In the following case, the Fault controller uses the controllerAction to make up one's mind which method to run, and uses the bulletin to determine which View to render. In this case, it displays a 404 error.
public ActionResult Error404(string message) { return View("ErrorMessage", message); } You can use an event logging solution such every bit SolarWinds Papertrail™ to log the 404 server response. With Papertrail, yous can quickly search on specific errors to find the root crusade.
For case, you can search for a 404 based on a page name. In the following instance, nosotros logged a fatal error when the user attempted to access the path /example404. The exception was captured in the global.asax file by adding the following code to the Application_Error event.
protected void Application_Error(object sender, EventArgs east) { Exception lastException = Server.GetLastError(); NLog.Logger logger = NLog.LogManager.GetCurrentClassLogger(); logger.Fatal(lastException); }
Ajax Fault Handling
Ajax in MVC sends input from a user to a dorsum-end controller. The controller processes input and sends JSON back to the Ajax asking without refreshing the unabridged folio. Similar to the previous example, you could have an error during controller processing and demand to handle information technology from the front end finish. Ajax does not know when an error occurs unless the controller sends a success or failed response to the Ajax call. A simple controller action is shown beneath.
public ActionResult TestAjax() { bool success = true; return Json(success, JsonRequestBehavior.AllowGet); } The controller sends "true" to Ajax, but your own logic should send either true or false back to the Ajax function. The following jQuery code is an instance of calling the controller'southward action from the user's browser and displaying a bulletin should the processing return an mistake. If the "response" variable is prepare to false, so an alert displays. Otherwise, "Success" is displayed in the browser.
$.ajax({ url: "/MyController/TestAjax/", blazon: "Get", dataType: 'json', error: function (response) { if(!(response)) { alarm('error'); } }, success: function (response) { if(response) { alarm('Success'); } } }); When an Ajax mistake occurs, yous tin can send a customized mistake message to Papertrail. To enable this message, add the following lawmaking to any Controller activeness:
bool success = false; if (!success) //processing failed { Logger logger = LogManager.GetCurrentClassLogger(); logger.Info("An Ajax exception occurred in the Dwelling house controller and TestAjax() method."); } The "success" variable is set to false to trigger the logger. However, placing your own logic into an action and creating a custom message gives an administrator more detailed information in Papertrail logs, which can be seen below.
403 Forbidden Error
When developing an application, it'southward standard to deploy it to a staging server and then a production server. Although the awarding runs fine on your local computer, when you deploy it to either staging or production, you might receive a 403 forbidden error when you signal the browser to the domain. This can be an effect with anonymous and Windows authentication configured in IIS.
The "Bearding Authentication" configuration in IIS allows unauthenticated users to access your content. For most public applications on the internet such as a website, the "Bearding Authentication" setting should be set to true. If you do not want the general public to accept access to your application, this setting should be set to imitation.
For internal applications where yous want network users to access an internal website, the "Windows Hallmark" setting should be set to "truthful." This allows you lot to integrate Windows authentication (Active Directory) and a web awarding. Unauthenticated users cannot access the spider web application.
To solve the consequence, go to the Windows IIS manager and click the site in your list of configured IIS sites. Double-click the "Hallmark" module. 2 configurations display:
To permit users to browse your site, "Bearding Hallmark" should exist enabled. Should you ever decide to create folders where merely authenticated users can access them, add the "Windows Authentication" setting and set it to true.
Internal Server Mistake 500
Next to performance issues, internal 500 server errors are also some of the near difficult to resolve. Because it's a full general mistake, it could be anywhere in the application or even a server configuration. To solve this issue, you lot need to be able to trace back to the error if yous are unable to identify it by reproducing it in development or staging environments.
In development, you tin can set up the application to display detailed errors to find the consequence, but yous should not leave detailed errors enabled in the product environment. This introduces a security result, since this data tin can be used by an assailant. Notwithstanding, in a development surround, detailed errors show you the location of the exception or logical mistake in your code. Add together the following lawmaking to your web.config to see detailed errors:
<configuration> <organisation.webServer> <httpErrors errorMode="Detailed" /> </system.webServer> <organization.web> <customErrors way="Off" /> <compilation debug="true" /> </organization.spider web> </configuration> You tin transport these events, including 500 exceptions to Papertrail . Using Papertrail, you can speedily observe the root crusade by viewing the exception, where it occurred, and the controller and activity where it was raised.
Database Connection Errors
Most every dynamic website runs using a dorsum-cease database. The database could exist on the same local machine (for instance, in evolution) or a database hosted on a remote server. The incorrect port, server accost, or user credentials could effect in database connection errors. The most mutual fault is to input the server name without specifying the database instance.
In environments where a development, staging, and production server are set up, it's mutual to have multiple connexion strings in a web.config file. Developers avoid accidentally using the incorrect connection string by either keeping a production-just spider web.config on the deployment server, or by setting flags that utilise a connection string based on some application server attribute.
MVC .NET introduced the "SqlConnectionStringBuilder" course in the "System.Data.SqlClient" namespace. This form lets you dynamically build a connection string based on attributes and business logic that the developer assigns. The following code is an case:
SqlConnectionStringBuilder builder = new SqlConnectionStringBuilder(); // set the connection string based on the server name switch (System.Environment.MachineName) { instance "PRODUCTION": architect.ConnectionString = "server=(production-database);user id=examination;" + "countersign= test_prod;initial catalog=prod"; break; example "Development": builder.ConnectionString = "server=(development-database);user id=exam;" + "password= test_prod;initial catalog=dev"; interruption; default: builder.ConnectionString = "server=(development-database);user id=test;" + "countersign= test_prod;initial catalog=dev"; Logger logger = LogManager.GetCurrentClassLogger(); logger.Info("ALERT: Default database connection pointing to DEV server."); interruption; } architect.AsynchronousProcessing = true; builder["Connect Timeout"] = 1000; string connectionString = architect.ConnectionString; In addition to building a dynamic connection string based on machine name, should the "default" section of the switch statement trigger, an alert is logged to let administrators know that the code is running on neither product or evolution servers, which could lead to critical problems.
Conclusion
Before ever deploying an application, always thoroughly examination either manually or using scripts. Some exceptions can be avoided by just thoroughly testing, only fifty-fifty the near exhaustive QA process could miss critical errors. Monitoring and logging these events will reduce and mitigate their effects on users, productivity, and the awarding.
While these errors aren't an exhaustive list, they stand for many of the common mistakes an MVC .NET developer will run into during development. Subsequently your code is deployed to production, you tin can use SolarWinds tools such as Pingdom and Papertrail, and other monitoring tools to identify issues and find root crusade analysis.
warne-smithhentitivinge.blogspot.com
Source: https://www.papertrail.com/blog/troubleshooting-common-asp-net-mvc-problems/
0 Response to "How to Get Back the Alert to Run Program With Build Erros Again in .net"
Post a Comment