How to get error details on Azure Web site - asp.net-mvc

I'm new to Azure. Does anybody know how get detailed error message on website deployed to Azure web?
I added SimpleMembership to website and now Registration and Login (Post) are showing
Sorry, an error occurred while processing your request.
I'm connecting to DB on my home computer (no problem with connection).
LogFiles folder on azure ftp server has some files but I don't see how to use this information. I wish I can get YellowScreen on azure...

You have two options:
First, you can turn off custom errors in your web config. This is the quick-and-dirty approach but it will at least get you the information you are looking for. Just be sure to turn custom errors back on when you are done. NOTE: This method will display your stacktrace to the entire world.
<configuration>
<system.web>
<customErrors mode="Off" />
</system.web>
</configuration>
Second, you can remote desktop into your deployed machine, go to IIS Manager, and Browse to your site. Once you are there, reproduce the error and you will get the yellow screen of death you are looking for. For this to work, you will have to Enable Detailed Errors

Create a table in db where you will store you error logs, I'm using EF and table called Logs.
Create a class:
public class MyAppExceptionFilter : IExceptionFilter
{
private MyApp.Models.ApplicationDbContext db = new Models.ApplicationDbContext();
public void OnException(ExceptionContext context)
{
Exception ex = context.Exception;
Log log = new Log();
log.DateTime = DateTime.Now;
log.LogText = "Exception happened, text:" + ex.Message;
try
{
log.LogText +="User details:"+context.HttpContext.User.Identity.Name;
}
catch
{
log.LogText += "User details:none";
}
db.Logs.Add(log);
db.SaveChanges();
}
}
In FilterConfig.cs in App_Start folder add:
public static void RegisterGlobalFilters(GlobalFilterCollection filters)
{
filters.Add(new HandleErrorAttribute());
*filters.Add(new MyAppExceptionFilter());*
}

You can also get the same diagnostic by piping console logs to the cloud shell.
Login to azure. Bring up the console...azure CLI.
az webapp log config --name <app-name> --resource-group
myResourceGroup --application-logging filesystem --level information
To start streaming...
az webapp log tail --name <app-name> --resource-group myResourceGroup
Now just refresh the browser for the error.
Ctrl-C back at the CLI will stop streaming.
I picked this up here:Tutorial: Build an ASP.NET Core and Azure SQL Database app in Azure App Service

Related

Azure Cloud Service - Configure Session from RoleEnvironment

Our application is hosted as a Cloud Service in Azure and we have all our connection strings and other connection-like settings defined in the ServiceConfiguration files. We are also using a Redis Cache as the session state store. We are trying to specify the Redis Cache host and access key in the ServiceConfig and then use those values for the deployment depending on where the bits land. The problem is session is defined in the web.config and we can't pull RoleEnvironment settings into the web.config.
We tried altering the web.config in the Application_Startup method but get errors that access is denied to the web.config on startup, which makes sense.
We don't really want to write deployment scripts to give the Network Service user access to the web.config.
Is there a way to setup session to use a different Redis Cache at runtime of the application?
The error that we are getting is "Access to the path 'E:\sitesroot\0\web.config' is denied'. I read an article that gave some examples on how to give the Network Service user access to the web.config as part of the role starting process and did that and then now we have access to the file but now get the following error "Unable to save config to file 'E:\sitesroot\0\web.config'."
We ended up being able to solve this using the ServerManager API in the WebRole.OnStart method. We did something like this:
using (var server = new ServerManager())
{
try
{
Site site = server.Sites[RoleEnvironment.CurrentRoleInstance.Id + "_Web"];
string physicalPath = site.Applications["/"].VirtualDirectories["/"].PhysicalPath;
string webConfigPath = Path.Combine(physicalPath, "web.config");
var doc = System.Xml.Linq.XDocument.Load(webConfigPath);
var redisCacheProviderSettings = doc.Descendants("sessionState").Single().Descendants("providers").Single().Descendants("add").Single();
redisCacheProviderSettings.SetAttributeValue("host", RoleEnvironment.GetConfigurationSettingValue("SessionRedisCacheHost"));
redisCacheProviderSettings.SetAttributeValue("accessKey", RoleEnvironment.GetConfigurationSettingValue("SessionRedisCacheAccessKey"));
redisCacheProviderSettings.SetAttributeValue("ssl", "true");
redisCacheProviderSettings.SetAttributeValue("throwOnError", "false");
doc.Save(webConfigPath);
}
catch (Exception ex)
{
// Log error
}
}

Unable to perform JNDI lookup using IBM WebSphere Application Server Liberty

I am using IBM WebSphere Application Server Liberty to perform JNDI lookup.I am pretty sure about giving right about the location of resources in the project. However, when i run this I am getting a name not found error.
Here is the code performing the lookup:
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
{
PrintWriter out = response.getWriter();
response.setContentType("text/html");
try {
FlightService flightService = (FlightService)new InitialContext().lookup("java:comp/Web1/FlightService!com.airline.FlightService");
}
catch(Exception ex){
ex.printStackTrace();
}
if(flightService !=null){
out.println(flightService.getAirplaneModel());
out.println(flightService.getFrom());
out.println(flightService.getTo());
}
}
Here is the server.xml:
<server description="new server">
<!-- Enable features -->
<featureManager>
<feature>webProfile-7.0</feature>
<feature>localConnector-1.0</feature>
</featureManager>
<!-- To access this server from a remote client add a host attribute to the following element, e.g. host="*" -->
<httpEndpoint httpPort="9090" httpsPort="9443" id="defaultHttpEndpoint"/>
<!-- Automatically expand WAR files and EAR files -->
<applicationManager autoExpand="true"/>
<applicationMonitor updateTrigger="mbean"/>
<webApplication id="Web1" location="Web1-0.0.1-SNAPSHOT.war" name="Web1"/>
</server>
I am not sure , If i have to set any configuration related properties. Any help would be appreciated.
Looking at the server xml. I don't see JNDI entry being defined.
Based on the code, it should be trying to access a JNDI entry from a servlet. In this case, where do you define you JNDI entry in the first place?
I think you need the following to define the JNDI entry in the server xml
https://www.ibm.com/support/knowledgecenter/en/SSEQTP_8.5.5/com.ibm.websphere.wlp.doc/ae/twlp_dep_jndi_refentry.html
Please give it a try

How do I debug an ASPNET Core MVC Application Deployed in Azure

I've created a simple ASPNET Core 1.0 MVC app, which I am trying to deploy to Azure using Visual Studio. I am able to run this app locally on my machine using IIS Express, and navigate to my default route and display the page. However, in Azure I always get a 500 error every time, and at this point I am at a loss for how to get additional information.
I've enabled detailed request logging in my Azure app, but it doesn't really seem to tell me much.
ModuleName="AspNetCoreModule", Notification="EXECUTE_REQUEST_HANDLER", HttpStatus="500", HttpReason="Internal Server Error", HttpSubStatus="0", ErrorCode="The operation completed successfully.
(0x0)", ConfigExceptionInfo=""
I've stripped down my Startup configuration to the bare essentials
public void ConfigureServices(IServiceCollection services)
{
services.AddMvc();
}
public void Configure(IApplicationBuilder app, ILoggerFactory loggingFactory)
{
loggingFactory.AddConsole();
loggingFactory.AddDebug();
app.UseMvc(routes => {
routes.MapRoute(
name: "default",
template: "{controller=Home}/{action=Index}/{id?}"
);
});
}
Something must be blowing up in the MVC pipeline but I have no idea how to add more visibility. What can I do to get more information?
And in case it matters, this is my Program.cs
var host = new WebHostBuilder()
.UseKestrel()
.UseContentRoot(Directory.GetCurrentDirectory())
.UseIISIntegration()
.UseStartup<Startup>()
.Build();
host.Run();
Try setting ASPNETCORE_ENVIRONMENT to Development to display full exception message on the error page.
Remember to turn it off when finished, otherwise you will leak error information.

Azure RoleEnvironment.Changing event not being called in ASP.NET MVC 5

I am trying to use the Azure Runtime Reconfiguration Pattern to allow me to change a appSetting in the normal Web.config file via PowerShell (later by Microsoft Azure Web Sites Management Library).
My problem is that the RoleEnvironment.Changing event is not being called in my MVC app, so the web app is being restarted. I have placed event set up code in the MVC Application_Start as described in the Azure article, i.e.
protected void Application_Start()
{
RoleEnvironment.Changing += RoleEnvironment_Changing;
RoleEnvironment.Changed += RoleEnvironment_Changed;
//normal MVC code etc...
AreaRegistration.RegisterAllAreas();
}
The event handlers are a straight copy of the handled from the Azure article and look like this:
private const string CustomSettingName = "TestConfig";
public static string TestConfigValue;
private static void RoleEnvironment_Changing(object sender,
RoleEnvironmentChangingEventArgs e)
{
RoleLogs.Add("RoleEnvironment_Changing: started");
var changedSettings = e.Changes.OfType<RoleEnvironmentConfigurationSettingChange>()
.Select(c => c.ConfigurationSettingName).ToList();
Trace.TraceInformation("Changing notification. Settings being changed: "
+ string.Join(", ", changedSettings));
if (changedSettings
.Any(settingName => !string.Equals(settingName, CustomSettingName,
StringComparison.Ordinal)))
{
Console.WriteLine("Cancelling dynamic configuration change (restarting).");
RoleLogs.Add("RoleEnvironment_Changing: restarting!");
// Setting this to true will restart the role gracefully. If Cancel is not
// set to true, and the change is not handled by the application, the
// application will not use the new value until it is restarted (either
// manually or for some other reason).
e.Cancel = true;
}
else
{
RoleLogs.Add("RoleEnvironment_Changing: change is OK. Not restarting");
Console.WriteLine("Handling configuration change without restarting. ");
}
}
private static void RoleEnvironment_Changed(object sender,
RoleEnvironmentChangedEventArgs e)
{
RoleLogs.Add("RoleEnvironment_ChangED: Starting");
Console.WriteLine("Updating instance with new configuration settings.");
foreach (var settingChange in
e.Changes.OfType<RoleEnvironmentConfigurationSettingChange>())
{
if (string.Equals(settingChange.ConfigurationSettingName,
CustomSettingName,
StringComparison.Ordinal))
{
// Execute a function to update the configuration of the component.
RoleLogs.Add("RoleEnvironment_ChangED: TestConfig has changed");
Console.WriteLine("TestConfig has changed.");
TestConfigValue = RoleEnvironment.GetConfigurationSettingValue(CustomSettingName);
}
}
}
I have added logs which prove that my RoleEnvironment_Changing and RoleEnvironment_Changed are not being called in the MVC WebApp which means the WebApp is restarted when I change an appSetting via PowerShell. This also means the RoleEnvironment.Changing event never gets to the WebJob.
I am using Azure SDK 2.7.0
Any ideas?
UPDATE
#richag gave me an answer, which made me realise that my problem is because I am using a App Service rather than a Cloud Service. This SO answer and plus this video (see at 5:00mins) talks about the difference (Note: the video is old so the name of the web app is different, but the concept is the same).
I don't really want to change this late in the development, and I have worked round the problem another way. Maybe on the next project and will look at Cloud Services as I can see some positives, like better control of my WebJobs configuration.
From the runtime reconfiguration pattern: "Microsoft Azure Cloud Services roles detect and expose two events that are raised when the hosting environment detects a change to the ServiceConfiguration.cscfg files" These events are not fired if you make changes to app.config/web.config files. Only when the cloud service configuration is changed, i.e. if you upload a new configuration file through the azure portal's configure tab or change a setting directly on the azure portal.
According to the debugger, none of the following events are fired when I update the Azure Portal to change an AppSetting for an ASP.NET WebAPI app:
RoleEnvironment.Changing
RoleEnvironment.Changed
RoleEnvironment.StatusCheck
RoleEnvironment.SimultaneousChanging
RoleEnvironment.SimultaneousChanged
RoleEnvironment.Stopping
Do others have different experience?

ELMAH error logging for Windows Service

We are using ELMAH to log the web application exception which works great!. Also we want to know how to customize ELMAH to log the windows service exception.
I am not interested in using another application for logging only windows service exception.
Any help would be appreciated.
I did this previously. I found out the code to use by digging though the source code starting from the ErrorSignal.FromCurrentContext().Raise(ex); method.
This currently only logs to the Database (as thats all i needed) but with a little bit more investigation you could write a wrapper method that logs to whatever you have set-up in the config file.
try
{
Elmah.SqlErrorLog ErrorLog = new Elmah.SqlErrorLog(ConfigurationManager.ConnectionStrings["Default"].ConnectionString);
ErrorLog.ApplicationName = "AppName";
ErrorLog.Log(new Elmah.Error(new Exception("example")));
}
catch (Exception ex)
{
//catch sql error
}
In my service I made the ErrorLog variable a public singleton object that was easily accessed from the service project.
you can use it
Elmah.ErrorLog.GetDefault(null).Log(new Elmah.Error(new Exception("Error text")));

Resources