In asp.NET using C# can I create an error log? - c#

I have a C#.net site which displays custom error pages to the user. This is set in web.config:
<customErrors mode="Off">
<error statusCode="500" redirect="~/error.cshtml" />
<error statusCode="404" redirect="~/error.cshtml" />
</customErrors>
The problem is that if there is an error, I have no record of what it was. I'm familiar with PHP where I can set a location for the error_log file which I can then check for PHP errors. Is there a way to do something similar in .NET?

You can use log4net dll, it has provisions to log errors as well as diagnostic messages.
Link where the log4net is available :
https://logging.apache.org/log4net/release/example-apps.html
Codeproject demo to get started :
http://www.codeproject.com/Articles/8245/A-Brief-Introduction-to-the-log-net-logging-librar

You can try NLog. Here is a Tutorial

You can use the built-in logging functionality that comes with ASP.NET.
Set it up in system.diagnostics in web.config, declare a trace source in your code and off you go.
You can configure it to write to the event log as well as log files and custom destinations.
I just did a quick google search and found an introductory article here: http://www.thejoyofcode.com/from_zero_to_logging_with_system_diagnostics_in_15_minutes.aspx
You will find many more without too much effort.

Have a look at the HealthMonitoring possibilities that come with ASP.Net. For instance, you can get references to exceptions and send emails with the exception to a specified address. A couple of years ago I wrote this article about HealthMonitoring: http://www.tomot.de/en-us/article/6/asp.net/how-to-create-a-custom-healthmonitoring-provider-that-sends-e-mails
If you want a more mature error logging solution, have a look at Elmah.

Related

Live testing ASP.NET custom Role Provider

Using ASP.NET Webforms + VB/C#
I've been tasked to restrict ASP.NET page access to users not in specific roles. And I need to be able to live test my solution (versus unit testing where I could use mocks or fakes). Our site is rather complex so I doubt I'd be able to find all the "gotchas" with just unit testing.
I have something on my development computer I'm pretty sure will work in Production: I have a custom Role Provider hooked into the web.config file. It's being initialized and called when I debug the website, so I'm reasonably sure it's working OK. I have a folder ("Administration") marked only for a specific role. Our roles are defined in our own database and are not tied to Microsoft or Windows roles/permissions.
The problem is: I cannot actually login as a user I wish to debug with. I can "simulate" this with a special development-only start page. That works OK for our menu/navigation items which are built from the roles database, but of course without restricting pages (with a Role Provider or something similar), you can still manually type in a page and it will be served up. This devel-only start page sets the username I pass in as a FormsAuthentation auth cookie.
FormsAuthentication.Initialize()
FormsAuthentication.SignOut()
FormsAuthentication.SetAuthCookie(simUserName, True)
It seems like when I first start debugging (usually after a reboot), the custom Role Provider will get called with the same username I'm simulating, but after a while, that suddenly stops and my local Windows name gets passed instead. (Cookie issue?) After that, it no longer works.
Anyway -- Is there a way I can test roles locally during development or will we just have to put this on Production and hope for the best.
I didn't know what code or settings would be useful at this time, so let me know what you need. Thanks!
I think I've found the solution to my problem. I decided to work with some of the samples in Ch. 7 of Beginning ASP.NET Security by Barry Dorrans (published by Wrox) in the hopes working with authentication and authorization in simple examples might lead to a solution, and it did.
One of the examples of using Forms authentication (pp. 155-157) showed a simple login.aspx page similar to my development startup page. The code I had in my Development startup page (shown above) was incorrect. It should have been:
FormsAuthentication.Authenticate(simUserName, simUserPassword)
FormsAuthentication.RedirectFromLoginPage(simUserName, False)
I also defined my simulated users in my Development web.config:
<authentication mode="Forms">
<forms defaultUrl="default.aspx" loginUrl="mystart.aspx">
<credentials passwordFormat="Clear">
<user name="GeorgeWashington" password="password"/>
<user name="AndrewJackson" password="password"/>
<user name="AbrahamLincoln" password="password"/>
<user name="TeddyRoosevelt" password="password"/>
<user name="JackKennedy" password="password"/>
</credentials>
</forms>
</authentication>
When FormsAuthentication.Authenticate is called and authenticates which ever of the simulated users I choose, it looks like it causes ASP.NET to now always use this username in calls to the Role Provider. At least, this appears to be working when debugging the website.
I've set the project to always call my Development startup page (the login page -- mystart.aspx). This way I always start with a fresh authentication in case I need to work with a different role.
Anyone wanting to use this solution, WARNING: Your Development startup page must NEVER be used for the Production website. Likewise, NEVER use usernames and passwords in a Production web.config. This is ONLY for debugging and testing. Depending how you version control your development and production code, you may have to manually merge certain changes going from development to production in order to avoid sending this debugging code to Production.
I also understand Microsoft wants us to use a Membership Provider in place of the FormsAuthentication class. And in Production code, we should. But for my purposes (ensuring I can interact with the website in differing users/roles while debugging), this appears to be the simplest solution.
EDIT -- one more piece of the puzzle: I was still getting strange method calls in my Custom Role Provider. A few times a method would be called with the username I logged in with on my login page (this is what I expected); most often it was my Windows username which led me to believe Windows authorization was still being used by ASP.NET somewhere. After more research (thanks SO!!!), I found in my applicationhost.config file for my project, Windows authentication was set to True which I guess was causing a conflict with my web.config file. Setting the values in applicationhost.config to:
<location path="MyWebSite">
<system.webServer>
<security>
<authentication>
<anonymousAuthentication enabled="true" />
<windowsAuthentication enabled="false" />
</authentication>
</security>
</system.webServer>
</location>
seems to have solved that issue.
If you have any questions, or need more information, please let me know.

A way to have different LogPaths for elmah, based on error types

I am looking for a way to have different log path for different error types in my web api project. What I want is to put System.Web.HttpException errors in different folder and my other errors in a another folder. The reason for that is, I receive so many System.Web.HttpException errors which most of them are irrelevant but I still need to log them but in a different folder. My elmah setup is a standard one.
this is my web config tag:
<errorLog type="Elmah.XmlFileErrorLog, Elmah" logPath="~/App_Data/ErrorLog" />
<security allowRemoteAccess="false" />
</elmah>
any help is much appreciated.
The short answer: You can't. XmlFileErrorLog only supports a single directory as logPath.
If you want to implement this, you would need to fork the ELMAH source code and override the Log-method of XmlFileErrorLog.
Another approach could be to use ELMAH error filtering to ignore all System.Web.HttpException errors and then use another logging framework to log those errors. If you set up log4net, NLog, Serilog or similar, you could make that integration log all errors (including the HTTP exceptions).

ADFS 2.0 Microsoft.IdentityServer.Web.InvalidRequestException: MSIS7042

I have a custom MVC site that uses ADFS authentication for users to access the site.
This was working, I have since made no changes, with the only change occurring on the ADFS side with the TOKEN certificates rolling over. Unfortunately I cannot seem to find anything that indicates that this is related to my now very frustrating error.
Simply put no user can log in, thank goodness this is still under development so at least I do not have screaming users on my hands. I have a Dynamics CRM 2011 environment IFD and Claims-Based auth using this same ADFS server. I have also removed and recreated the Relying-Party Trusts, but still with no luck.
All I get is the following error on the page with the accompanying Event Log entry:
Site:
There was a problem accessing the site. Try to browse to the site again.
Event Log:
Encountered error during federation passive request.
Additional Data
Exception details:
Microsoft.IdentityServer.Web.InvalidRequestException: MSIS7042: The same client browser session has made '6' requests in the last '6' seconds. Contact your administrator for details.
at Microsoft.IdentityServer.Web.FederationPassiveAuthentication.UpdateLoopDetectionCookie()
at Microsoft.IdentityServer.Web.FederationPassiveAuthentication.SendSignInResponse(MSISSignInResponse response)
I have searched high and low, I have tried every suggestion I can find, including this post: ADFS v2.0 Error : MSIS7042: The same client browser session has made '6' requests in the last '1' seconds
I have configured my relying party trusts as per the following URL: http://www.cloudidentity.com/blog/2014/02/12/use-the-on-premises-organizational-authentication-option-adfs-with-asp-net-in-visual-studio-2013
I forgot to turn off custom errors, so now I get the following:
WIF10201: No valid key mapping found for securityToken: 'System.IdentityModel.Tokens.X509SecurityToken' and issuer: 'http://XXX.XXX.XXX/adfs/services/trust'.
As such I have corrected the Certificate Thumbprint, but unfortunately that doesn't seems to help the situation.
Still searching and trying solutions for this issue and will update if anything changes.
Any assistance in this regard would be greatly appreciated.
Thanks
Fixed it !! :):)
It seems there was an issue with the "issuerNameRegistry" entry in my Web.Config.
What does confuse me as to why it was working before, but never the less, here is what fixed the issue:
I had the following in my web.config, which did work previously:
<issuerNameRegistry type="System.IdentityModel.Tokens.ValidatingIssuerNameRegistry, System.IdentityModel.Tokens.ValidatingIssuerNameRegistry">
<authority name="http://adfs.domain.tld/adfs/services/trust">
<keys>
<add thumbprint="thumbprint"/>
</keys>
<validIssuers>
<add name="http://adfs.domain.tld/adfs/services/trust"/>
</validIssuers>
</authority>
</issuerNameRegistry>
Thanks to this answer https://stackoverflow.com/a/21289207/2985339 on this post Windows Azure intermittent Identity error when parsing webconfig
This is what the web.config now has:
<issuerNameRegistry type="System.IdentityModel.Tokens.ConfigurationBasedIssuerNameRegistry, System.IdentityModel, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089">
<trustedIssuers>
<add thumbprint="thumbprint" name="http://adfs.domain.tld/adfs/services/trust" />
</trustedIssuers>
</issuerNameRegistry>
Beats me as to why it stopped working, but if anyone else has this issue, hopefully this will help. :)
For the 7402 error, ensure that the identifier in your web.config and the endpoint in the RP both have a trailing slash and that they both match.
For the non-valid key, use the MMC plugin on the server side to get the thumbprint and then post this into something like Notepad++ and inspect it - ensure no dodgy characters etc., then remove spaces and then paste it into the web.config.
I've seen this a number of times.
Sorry to necro up an old thread but to those that up-voted the correct answer - did you add any new references to your project? Import anything etc?
Obviously ValidatingIssuerNameRegistry is not ConfigurationBasedIssuerNameRegistry so was wondering what steps were taken to add/remove any assemblies / versions etc.

Write and display error message for live website?

I am developing a website, At the moment when i run it off my local host every thing works fine.
I have uploaded this website to fireFTP and can now access my website online.
The website does not preform the same as when hosted on local host and i cant find the errors as my website does not break.
I would like to do some testing and am wanting to know how to display an error message??
I would like to display the error message like this:
But with a custom message like, "code stepped into method writeToSpreadSheet".
This way i could find where my code gets to and pin point whats going wrong.
You need to enable show detailed error messages in IIS settings, see the link below for a short tutorial about how to do it.
IIS7 : HOW TO enable the detailed error messages for the website while browsed from for the client browsers?
Add this lines in web.config inside so you dont have
to touch the IIS configuration:
<customErrors mode="On">
<error redirect="error404.html" statusCode="404" />
</customErrors>
Change the error404.html for your desired html page.
When some page is not found user will be redirected there

Outputting to the Console in C# on IIS

We are trying to debug some web services code we're running in C# on IIS. I am new to Windows programming and have no idea how to view output to the console. We've got some write statements in the code, but I can't figure out how to view the console while this thing is running. Help?
I have found the Trace feature extremely helpful. You can get there by going to:
http://mysiteurl/trace.axd
In your web.config, place the following within the System.Web tag:
<trace enabled="true"
localOnly="false"
pageOutput="false"
requestLimit="500"
traceMode="SortByTime"
/>
Now from your code behind, you can inject some logging by doing:
HttpContext.Current.Trace.Warn("I Made It Here!");
You'll want to take a look at ASP.NET tracing
here is a handy link to get you started: http://www.asp101.com/articles/robert/tracing/default.asp
you can enable application wide tracing if you place the following in your web.config, then you will have access to your trace.axd
<trace enabled="true"
localOnly="false"
pageOutput="false"
requestLimit="500"
traceMode="SortByTime"
/>
If you're using asp.net then trace.axd should contain trace statements (as long as its turned on).
You aren't going to get a console for IIS. CLOSEST you will come is Debug.WriteLine w/ a debugger attached or using page tracing. Recommendation would be to use a logging framework that will write to debugger (when attached) as well as a file and possibly the event log (all configured via your listeners).
Some great ones are log4net and NLog.

Categories