Why does XDocument.Load throw exception when ELMAH is enabled? - asp.net-mvc

I have the following code that retrieves a link to the latest post from the blog subsite:
XDocument doc = XDocument.Load("http://www.mysite.com/blog/syndication.axd");
XElement node = doc.Descendants("item").FirstOrDefault();
string text = node.Element("title").Value;
string uri = node.Element("link").Value;
The code always worked fine. This week I added ELMAH.MVC via NuGet as a Package Reference. As soon as I deploy the web.config file with the added ELMAH sections, I get the following error:
System.Web.HttpException (0x80004005): Error executing child request for handler
'System.Web.Mvc.HttpHandlerUtil+ServerExecuteHttpHandlerAsyncWrapper'.
---> System.Net.WebException: The remote server returned an error: (500) Internal Server Error.
at System.Net.HttpWebRequest.GetResponse()
at System.Xml.XmlDownloadManager.GetNonFileStream(Uri uri, ICredentials credentials, IWebProxy proxy, RequestCachePolicy cachePolicy)
at System.Xml.XmlDownloadManager.GetStream(Uri uri, ICredentials credentials, IWebProxy proxy, RequestCachePolicy cachePolicy)
at System.Xml.XmlUrlResolver.GetEntity(Uri absoluteUri, String role, Type ofObjectToReturn)
at System.Xml.XmlReaderSettings.CreateReader(String inputUri, XmlParserContext inputContext)
at System.Xml.XmlReader.Create(String inputUri, XmlReaderSettings settings, XmlParserContext inputContext)
at System.Xml.Linq.XDocument.Load(String uri, LoadOptions options)
If I put the old web.config file back, the error goes away.
Any idea why adding ELMAH would cause XDocument.Load to fail?

You need to look at your ASP.Net site and find the server-side error.

Related

Publishing my API project in another IIS

I've published my API project several times and it doesn't have any problem. but when I publish the same publish files in one of my server's IIS it rise a error about one of my controllers.
I've checked it, it works properly in my local and another IIS.
This XML file does not appear to have any style information associated
with it. The document tree is shown below. An error
has occurred. An error occurred when
trying to create a controller of type 'CityController'. Make sure that
the controller has a parameterless public constructor.
System.InvalidOperationException
at
System.Web.Http.Dispatcher.DefaultHttpControllerActivator.Create(HttpRequestMessage
request, HttpControllerDescriptor controllerDescriptor, Type
controllerType) at
System.Web.Http.Controllers.HttpControllerDescriptor.CreateController(HttpRequestMessage
request) at
System.Web.Http.Dispatcher.HttpControllerDispatcher.d__1.MoveNext()
An error has
occurred. Type
'Jabama.Web.API.Controllers.CityController' does not have a default
constructor
System.ArgumentException
at System.Linq.Expressions.Expression.New(Type type) at
System.Web.Http.Internal.TypeActivator.Create[TBase](Type
instanceType) at
System.Web.Http.Dispatcher.DefaultHttpControllerActivator.GetInstanceOrActivator(HttpRequestMessage
request, Type controllerType, Func`1& activator) at
System.Web.Http.Dispatcher.DefaultHttpControllerActivator.Create(HttpRequestMessage
request, HttpControllerDescriptor controllerDescriptor, Type
controllerType)
I checked all of the cityController's dependencies, there isn't any problem in it.
I finally found what's wrong. when I published the API project, it didn't publish the Microsoft.SqlServer.Type dll in it's bin folder.I copyed the dll manualy to that IIS and it's work but I don't know why it was giving me such an error! and even yet now what was wrong with my new IIS which the API didn't work without this dll, and the other IIS worked without this even without copying it!

How to configure libgit2 in TFS Build with private repositories?

I am currently using TFS 2013 (local installation) to try to build from an internal GitHub Enterprise installation using LDAP Authentication.
The problem I am getting is that it cannot access the source code, how can I configure TFS Build to use a specific authentication?
From the TFS Build Log
Exception Message: An error was raised by libgit2. Category = Net (Error).
VS30063: You are not authorized to access https://user:password#githubrepository.corp.company.net. (type LibGit2SharpException)
Exception Data Dictionary:
libgit2.code = -1
libgit2.category = 11
Exception Stack Trace:
Server stack trace:
at LibGit2Sharp.Core.Ensure.HandleError(Int32 result)
at LibGit2Sharp.Core.Proxy.git_clone(String url, String workdir, GitCloneOptions opts)
at LibGit2Sharp.Repository.Clone(String sourceUrl, String workdirPath, Boolean bare, Boolean checkout, TransferProgressHandler onTransferProgress, CheckoutProgressHandler onCheckoutProgress, Credentials credentials)
at Microsoft.TeamFoundation.Build.Activities.Git.GitPull.GitClone.GetRepository(String repositoryUrl, String workingFolder)
at System.Runtime.Remoting.Messaging.StackBuilderSink._PrivateProcessMessage(IntPtr md, Object[] args, Object server, Object[]& outArgs)
at System.Runtime.Remoting.Messaging.StackBuilderSink.AsyncProcessMessage(IMessage msg, IMessageSink replySink)
Exception rethrown at [0]:
at System.Runtime.Remoting.Proxies.RealProxy.EndInvokeHelper(Message reqMsg, Boolean bProxyCase)
at System.Runtime.Remoting.Proxies.RemotingProxy.Invoke(Object NotUsed, MessageData& msgData)
at System.Func3.EndInvoke(IAsyncResult result)
at Microsoft.TeamFoundation.Build.Activities.Git.GitPull.GitRepositoryBase.EndExecute(AsyncCodeActivityContext context, IAsyncResult result)
at System.Activities.AsyncCodeActivity1.System.Activities.IAsyncCodeActivity.FinishExecution(AsyncCodeActivityContext context, IAsyncResult result)
at System.Activities.AsyncCodeActivity.CompleteAsyncCodeActivityData.CompleteAsyncCodeActivityWorkItem.Execute(ActivityExecutor executor, BookmarkManager bookmarkManager)
Follow up
I have tried the URL params for authentication (example)
https://username:password#domain.com/user/project.git
More Follow up
Completely uninstalled and update to the 2013 RC, error message has been updated as well, as it is different.
I have also tried setting up the build controller to run as an authenticated LDAP user in the github enterprise installation.
Libgit2 does support the url credentials, however TFS build activities for GitPull overrides the default behavior with a Microsoft.TeamFoundation.Build.Activities.Git.TfsSmartSubtransport class for the http and https protocol.
This class unfortunately ignores credentials in the URL and instead tries to retrieve credentials from the registry.
I was able to successfully get a TFS build server to pull source code from a gitlab server using TFS build with the default GitTemplate.12.xaml workflow.
Setup the TFS build's repository URL without any credentials in the URL.
Encrypted your credential's password with the following bit of code. This needs to get run on the build server as the encryption process is specific to the local machine it's executed on.
var password = "your_password";
var bytes = Encoding.Unicode.GetBytes(password);
var bytes2 = ProtectedData.Protect(bytes, null, DataProtectionScope.LocalMachine);
var base64 = Convert.ToBase64String(bytes2);
Add the following registry settings to your build server.
NOTE: The URL in the registry must exactly match the absolute URL of your repository or TFS won't find the credentials.
[HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\TeamFoundationServer\12.0\HostedServiceAccounts\Build\http://githubrepository.corp.company.net]
"Microsoft_TFS_UserName"="<username goes here>"
"Microsoft_TFS_Password"="<bas64 encrypted password goes here>"
"Microsoft_TFS_CredentialsType"="Windows"
The only other alternatives to this approach that I could think of is to modify the default workflow and replace the GitPull activity with something else.
I'm not suggesting that this is the best method, but it worked for me.
That's odd. It looks like the HTTP transport should honor url-encoded credentials.
In any case, it might be better and safer to set up the remote to get the credentials from elsewhere. The clone code is a good example of how to do this: here's how to set up the callback, and here's an example of how to generate the credential object.

facebook login using oauth fails on live server

I'm using OAuthWebSecurity to login with facebook and it is working on localhost. However then deployed to the live server I get the following error message:
The remote server returned an error: (400) Bad Request.
I have checked domain details are correct on facebook.
The sandbox mode is disabled.
I have disabled windows firewall - still get same error.
Responses from facebook have the identical format whether in live or localhost environments.
The date and time of live server is correct.
I've test locally also changing the host file to the live domain - still works locally.
Here's the stack trace:
[WebException: The remote server returned an error: (400) Bad Request.]
System.Net.WebClient.DownloadDataInternal(Uri address, WebRequest& request) +3291120
System.Net.WebClient.DownloadString(Uri address) +207
DotNetOpenAuth.AspNet.Clients.FacebookClient.QueryAccessToken(Uri returnUrl, String authorizationCode) +293
DotNetOpenAuth.AspNet.Clients.OAuth2Client.VerifyAuthentication(HttpContextBase context, Uri returnPageUrl) +167
DotNetOpenAuth.AspNet.OpenAuthSecurityManager.VerifyAuthentication(String returnUrl) +502
Microsoft.Web.WebPages.OAuth.OAuthWebSecurity.VerifyAuthenticationCore(HttpContextBase context, String returnUrl) +231
Any suggestions?
There was a defect open related to this:
https://github.com/DotNetOpenAuth/DotNetOpenAuth/issues/203
but that library is apparently no longer being maintained:
https://github.com/DotNetOpenAuth/DotNetOpenAuth/issues/317#issuecomment-29580565
... although it is still referenced in many Microsoft documents. Investigating that related to another defect.
See also: The remote server returned an error: (400) Bad Request Microsoft.AspNet.Membership.OpenAuth
This is an old one, but I hit a 400 error from Facebook login using dotnetopenoath as it is integrated into MVC 4 and went on a wild goose chase thinking that it was not working because it was no longer supported, when all I needed to do was catch and log the exception which pointed me to the problem for my particular case (app secret proof setting):
catch (WebException exception)
{
using (WebResponse response = exception.Response)
{
HttpWebResponse httpResponse = (HttpWebResponse) response;
m_log.Debug("Error code: " + httpResponse.StatusCode);
using (Stream data = response.GetResponseStream())
{
if (data != null)
{
using (var reader = new StreamReader(data))
{
string text = reader.ReadToEnd();
m_log.Debug(text);
}
}
}
}
}

asp.net mvc handle http 400 error

I have an ASP.NET MVC 4 application and I want to redirect all HTTP 400 errors to my custom error page. I was searching an hours to find a solution though HTTP 400 error isn't handled like 404 error. There are many solutions that show how to escape 400(bad request error), i.e. to allow using special characters for example in url. But I wouldn't able to find some solution to catch the exception.
Please help me to catch somehow all HTTP bad requests and redirect them to my error page.
Never redirect users in case of errors, instead return a response body for the failed request. The feature of IIS (and ASP.NET) to redirect to an error page, I believe, is fundamentally wrong, incorrect, and against the HTTP specification (because then the error is being returned for the error page resource itself, not the original request. And if it's a web-browser the user has no way of retrying, because reloading the page will return the error page again, not retrying their original failed request, which is what they want).
Anyway...
A HTTP 400 response must be generated by your application code, it isn't something that will be done automatically. A bad request is typically used when informing non-human agents (i.e. web service clients, not web browsers) that their HTTP request was missing required values or had malformed values.
You can do this in MVC by having a base controller class for all of your controllers like so:
public abstract class BaseController : Controller {
protected ActionResult Http400(String message) {
Response.StatusCode = 400;
return View(message); // you need to define a view file called "Http400.aspx" (or cshtml if you're using Razor) in your application's shared views folder
}
}
so in your application logic:
public ActionResult Foobar() {
if( IsBadRequest() ) return Http400("Bad request, try again");
}
You could do something as simple as adding adding this to your web.config
<customErrors mode="RemoteOnly">
<error statusCode="400" redirect="errorpage.html"/>
</customErrors>

WebSecurity.InitializeDatabaseConnection method can be called only once

I'm trying Windows Azure to host an MVC4 web application.
I've created a test app, using VS2012 MVC4 internet application template and added a custom Model and Controller to it.
I've published it on Azure and managed to get 'update-database' apply migrations to the Azure Database.
When i try the app locally, but using the Azure SQL database, it works fine.
I can login/register and use my test controller.
When i try the app online, i can use the test controller but login or register links give the following exception:
Server Error in '/' Application.
The "WebSecurity.InitializeDatabaseConnection" method can be called only once.
Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.
Exception Details: System.InvalidOperationException: The "WebSecurity.InitializeDatabaseConnection" method can be called only once.
Source Error:
An unhandled exception was generated during the execution of the current web request. Information regarding the origin and location of the exception can be identified using the exception stack trace below.
Stack Trace:
[InvalidOperationException: The "WebSecurity.InitializeDatabaseConnection" method can be called only once.]
WebMatrix.WebData.WebSecurity.InitializeMembershipProvider(SimpleMembershipProvider simpleMembership, DatabaseConnectionInfo connect, String userTableName, String userIdColumn, String userNameColumn, Boolean createTables) +123
WebMatrix.WebData.WebSecurity.InitializeProviders(DatabaseConnectionInfo connect, String userTableName, String userIdColumn, String userNameColumn, Boolean autoCreateTables) +51
WebMatrix.WebData.WebSecurity.InitializeDatabaseConnection(String connectionStringName, String userTableName, String userIdColumn, String userNameColumn, Boolean autoCreateTables) +52
MembershipTest2.Filters.SimpleMembershipInitializer..ctor() +193
Do you have any idea where that comes from ?
If i debug (the local version), this method is only called once.
Thanks.
You could try encapsulating the call(s) to that method to ensure it's not called more then once
if (!WebMatrix.WebData.WebSecurity.Initialized)
{
WebSecurity.InitializeDatabaseConnection(...);
}
in my case I had both
(in web.config)
<add key="enableSimpleMembership" value="true" />
and
(in _ViewStart.cshtml)
WebSecurity.InitializeDatabaseConnection("club", "Account", "UserID", "UserName", autoCreateTables: true);
Solution: it seems you cannot have both, so remove one
Does the following SO discussion help you?
Cannot seed Users & Roles
I did find the following article helped me lot to use newer MVC4 & EF together with Simple Membership Provider so if you haven't read it please take a look:
SimpleMembership, Membership Providers, Universal Providers and the new ASP.NET 4.5 Web Forms and ASP.NET MVC 4 templates

Resources