I am trying to set up a simple website which uses DotNetOpenAuth as its membership provider. Everything was going great until I ran into the following exception.
[SecurityException: Request for the permission of type 'System.Net.WebPermission, System, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089' failed.]
System.Security.CodeAccessSecurityEngine.Check(Object demand, StackCrawlMark& stackMark, Boolean isPermSet) +0
System.Security.CodeAccessSecurityEngine.Check(CodeAccessPermission cap, StackCrawlMark& stackMark) +31
System.Security.CodeAccessPermission.Demand() +46
System.Net.Configuration.DefaultProxySection.PostDeserialize() +103
The code is below. Unfortunately I cannot reproduce the problem on my local machine. This is being hosted on GoDaddy shared hosting. The line which causes the exception is openid.CreateRequest(id):
public virtual ActionResult Authenticate(OpenIdAuthenticationViewModel model, string returnUrl)
{
OpenIdRelyingParty openid = new OpenIdRelyingParty();
var response = openid.GetResponse();
if (response == null)
{
Identifier id;
if (Identifier.TryParse(model.OpenIdUrl, out id))
{
try
{
var openIdRequest = openid.CreateRequest(id);
var result = openIdRequest.RedirectingResponse.AsActionResult();
return result;
}
catch (ProtocolException pe)
{
ViewData["OpenIdMessage"] = pe.Message;
return View(model);
}
}
else
{
ViewData["OpenIdMessage"] = "Invalid Identifier";
return View(model);
}
}
// code that handles response
}
I've tried changing the requirePermission attribute of
<section name="dotNetOpenAuth" type="DotNetOpenAuth.Configuration.DotNetOpenAuthSection" requirePermission="false" allowLocation="true" />
but that only caused a different root for the exception stack trace. There is very little information to be found on this exact exception on the web.
This looks like it's because you've got a web.config with the following snippet:
<system.net>
<defaultProxy enabled="true" />
</system.net>
Try removing the <defaultProxy> tag, which shouldn't be necessary on GoDaddy anyway.
Related
I was connected CRM with Plugin registration tool of CRM SDK 2016 whenever i am uploading the downloaded error log file to debugger it's showing "An error occured while parsing the plugin's profile from file" could any suggest me where i am going wrong. The image is showing below:
ErrorImage
Unhandled Exception: System.ArgumentException: Unable to parse the OrganizationServiceFault.
Parameter name: serializedReport
at PluginProfiler.Library.ProfilerUtility.ExtractReport(String serializedReport)
at PluginProfiler.Library.ProfilerUtility.DeserializeProfilerReport(String assemblyFilePath, String logFilePath, Boolean isCrmDataStream)
at PluginProfiler.Library.ProfilerExecutionUtility.RetrieveReport(String logFilePath, Boolean isCrmDataStream)
at Microsoft.Crm.Tools.PluginRegistration.CommonControls.Helper.ParseReportOrShowError(Window window, FileBrowserView profilePathControl, Boolean requireReportParse, ProfilerPluginReport& report)
Inner Exception: System.InvalidOperationException: Message does not contain a serialized value.
at PluginProfiler.Library.ProfilerUtility.ExtractReportFromFault(OrganizationServiceFault fault)
at PluginProfiler.Library.ProfilerUtility.ExtractReport(String serializedReport)
Except this, when log file is downloaded it contains the below error:
Unhandled Exception: System.ServiceModel.FaultException`1[[Microsoft.Xrm.Sdk.OrganizationServiceFault, Microsoft.Xrm.Sdk, Version=9.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35]]: Unexpected exception from plug-in (Execute): SamplePlugins.PostCreateContact: System.Security.SecurityException: Request for the permission of type 'System.Security.Permissions.FileIOPermission, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089' failed.Detail:
<OrganizationServiceFault xmlns="http://schemas.microsoft.com/xrm/2011/Contracts" xmlns:i="http://www.w3.org/2001/XMLSchema-instance">
<ActivityId>8998bfd9-9637-430e-8c47-998c63d1f0ee</ActivityId>
<ErrorCode>-2147220956</ErrorCode>
<ErrorDetails xmlns:d2p1="http://schemas.datacontract.org/2004/07/System.Collections.Generic" />
<Message>Unexpected exception from plug-in (Execute): SamplePlugins.PostCreateContact: System.Security.SecurityException: Request for the permission of type 'System.Security.Permissions.FileIOPermission, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089' failed.</Message>
<Timestamp>2017-11-03T11:49:06.9775603Z</Timestamp>
<ExceptionRetriable>false</ExceptionRetriable>
<ExceptionSource i:nil="true" />
<InnerFault i:nil="true" />
<OriginalException i:nil="true" />
<TraceText>[SamplePlugins: SamplePlugins.PostCreateContact]
[e326c926-0dbe-e711-a94d-000d3af2242b: SamplePlugins.PostCreateContact: Create of contact (Profiled)]</TraceText>
</OrganizationServiceFault>
Below is my .CS file:
using Microsoft.Xrm.Sdk;
using System;
namespace SamplePlugins
{
public class PostCreateContact : IPlugin
{
ITracingService tracingService;
public void Execute(IServiceProvider serviceProvider)
{
tracingService = (ITracingService)serviceProvider.GetService(typeof(ITracingService));
tracingService.Trace("Tracing Execute");
// Obtain the execution context from the service provider.
IPluginExecutionContext context = (IPluginExecutionContext)
serviceProvider.GetService(typeof(IPluginExecutionContext));
// The InputParameters collection contains all the data
//passed in the message request.
if (context.InputParameters.Contains("Target") && context.InputParameters["Target"] is Entity)
{
// Obtain the target entity from the input parameters.
Entity entity = (Entity)context.InputParameters["Target"];
try
{
// Create a task activity to follow up with the account customer in 7 days
Entity followup = new Entity("task");
followup["subject"] = "Send e-mail to the new customer.";
followup["description"] = "Follow up with the customer. Check if there are any new issues that need resolution.";
followup["scheduledstart"] = DateTime.Now;
followup["scheduledend"] = DateTime.Now.AddDays(2);
followup["category"] = context.PrimaryEntityName;
// Refer to the contact in the task activity.
if (context.OutputParameters.Contains("id"))
{
Guid regardingobjectid = new Guid(context.OutputParameters["id"].ToString());
string regardingobjectidType = "contact";
followup["regardingobjectid"] = new EntityReference(regardingobjectidType, regardingobjectid);
}
// Obtain the organization service reference.
IOrganizationServiceFactory serviceFactory = (IOrganizationServiceFactory)serviceProvider.GetService(typeof(IOrganizationServiceFactory));
IOrganizationService service =
serviceFactory.CreateOrganizationService(context.UserId);
// Create the followup activity
service.Create(followup);
}
catch (Exception ex)
{
throw new InvalidPluginExecutionException(ex.Message);
}
}
}
}
}
I have tried by replacing the PluginProfiler.Solution.zip but the issue still exists.
Thanks.
I recommend you below steps:
Unregister the Plugin assembly & Profiler
Download latest 365 SDK
Register the assembly freshly using new PRT from latest SDK
Install Profiler & try again
Most important - The error log you shared cannot be used to debug using Profiler. It will be different
I have the following requirements
Set a value in web.config and enable maintenance mode
All non-ajax requests should be shown a custom error page, with the http status code set to 503. The url of page should be retained.
All ajax requests should be responded with http status code 503
I should have an opportunity to do some basic logging to a file. Log the url and the user Identity if he happened to be logged into the app
I am using ELMAH to track/log all unhandled exceptions. The mechanism for implementing maintenance mode shouldn't need me to not use ELMAH
I have "runAllManagedModulesForAllRequests" set to true. this was originally done for use with RequestReduce. we no longer use it, but I am hesitant to reset its value to false. I am not sure if any other library needs it.
Once I realized there is nothing built in which supports the above requirements, I felt I had the following two options in front of me (App_offile.html won't work for me).
an HttpModule
an MVC ActionFilter
I dropped the MVC ActionFilter as I couldn't figure out how to guarantee it to run before any authentication/authorization filters. I have a custom authentication filter which hits the db. The idea behind the maintenance mode is the db might be offline, yet the web-app shouldn't show a 500 custom error page, but a 503 custom error page.
I wrote the following httpmodule and added in my web.config. It works for ajax requests. It kinda works for non-ajax requests. All requests get redirected to the 503 error page. The side-effect is all requests for static content also result in a 503. My error page thus is shown unstyled :(
// the http module
public class MaintenanceModeModule : IHttpModule
{
private static bool _isUnderMaintenance;
static MaintenanceModeModule()
{
var valueStr = (ConfigurationManager.AppSettings["UnderMaintenance"] ?? (false).ToString());
bool underMaintenance;
bool.TryParse(valueStr, out underMaintenance);
_isUnderMaintenance = underMaintenance;
}
public void Init(HttpApplication application)
{
application.BeginRequest += OnBeginRequest;
}
private void OnBeginRequest(object sender, EventArgs e)
{
var application = (HttpApplication) sender;
var request = application.Request;
var response = application.Response;
if (_isUnderMaintenance == false)
{
return;
}
application.Context.Items["under_maintenance"] = true; // used later
if (request.Url.PathAndQuery == "/503") // the url of the action that renders the custom error page
{
return;
}
const int statusCode = (int) HttpStatusCode.ServiceUnavailable;
const string statusMessage = "Temporarily down for maintenance";
var requestWrapper = new HttpRequestWrapper(request);
if (requestWrapper.IsAjaxRequest())
{
response.Clear();
response.ClearContent();
response.ClearHeaders();
response.StatusCode = statusCode;
response.TrySkipIisCustomErrors = true;
response.StatusDescription = statusMessage;
response.End();
return;
}
// doesn't work, shows the Yellow Screen of Death (YSoD)
// application.Context.Server.Transfer("~/503", preserveForm: true);
// doesn't work, shows the Yellow Screen of Death (YSoD)
// throw new HttpException(statusCode, statusMessage);
response.Redirect("~/503");
}
public void Dispose()
{
}
}
...
// web.config
// only the relevant portions of each section is shown
<appSettings>
<add key="UnderMaintenance" value="true" />
</appSettings>
<customErrors mode="On"> <!-- Custom errors are on, even then I was seeing YSoDs during my attempts -->
<error statusCode="404" redirect="404" />
<error statusCode="503" redirect="503" />
</customErrors>
<system.webServer>
<httpErrors existingResponse="PassThrough">
</httpErrors>
<modules runAllManagedModulesForAllRequests="true">
<add name="MaintenanceMode" type="WebApp.Code.MvcInfrastructure.MaintenanceModeModule" />
</modules>
</system.webServer>
...
// route config
routes.MapRoute("503Error", "503", new { controller = "Error", action = "UnderMaintenance" });
...
// error controller
// the authentication filter skips authentication if the allowanonymous attribute is present
[AllowAnonymous]
public class ErrorController : CustomBaseController
{
public ErrorController(AppConfig appConfig)
: base(appConfig)
{
}
public ActionResult UnderMaintenance()
{
// behind the scenes reads the value from HttpContext.Items.
// This was set during the execution of the httpmodule
if (AppConfig.UnderMaintenance == false)
{
return new RedirectResult("~/");
}
Response.StatusCode = (int) HttpStatusCode.ServiceUnavailable;
Response.TrySkipIisCustomErrors = true;
// the actual content of the view is not relevant now
return View("Error503");
}
}
The problems with this approach,
Each non-ajax request is responded with a 302 and then a 503
The URL requested by the browser is not retained
It returns a 503 for all static assets as well
The code I wrote and web.config settings I enabled are all cobbled together from various sources. I am not fully sure what those settings do or what the recommended way is. Please feel free to answer with a completely different method, as long as it can meet the requirements stated.
I'm trying to properly handle and return a 404 for this URL: http://localhost:2867/dd./xml (notice the dot before the slash)
In my current implementation I get 4 exceptions/errors in Application_Error. The first exception returned by Server.GetLastError() is System.Web.HttpException while the next three are null.
I made a bare minimum implementation to reproduce this issue. Here's the code in global.asax.cs:
protected void Application_Error(object sender, EventArgs e)
{
Exception exception = Server.GetLastError();
Server.ClearError();
var routeData = new RouteData();
routeData.Values.Add("controller", "Error");
routeData.Values.Add("action", "Generic");
routeData.Values.Add("area", "");
IController errorController = new ErrorController();
// this line throws System.Web.HttpException is a view is returned from ErrorController
errorController.Execute(new RequestContext(new HttpContextWrapper(Context), routeData));
}
The error controller looks like this:
public class ErrorController : Controller
{
public ActionResult Generic()
{
Response.TrySkipIisCustomErrors = true;
Response.StatusCode = (int)HttpStatusCode.NotFound;
return View();
// returning content rather than a View doesn't fire 'System.Web.HttpException' in Application_Error
//return Content("Some error!");
}
}
There are two issues. One is that for the given URL instead of one error in Application_Error I get 3 or 4, and the other is that when returning a view from the ErrorController an exception is thrown on the Execute call line in Application_Start. If a Content("something") is returned instead this internal (to MVC I assume) exception is not triggered.
In order to see the problem you have to be in debug mode and use the development server. When using IIS or IIS Express the error is not caught for some reason. Also, every now and then these errors go away. To get it back to the beginning you have to clean the solution.
If you'd like to play with it here's the bare minimum solution: http://dl.dropbox.com/u/16605600/InvalidUrl.zip
Thank you for your help!
If you're using IIS7+ putting this in the web.config works:
<system.webServer>
<httpErrors errorMode="Custom" existingResponse="Replace">
<remove statusCode="404" />
<error statusCode="404" responseMode="ExecuteURL" path="/Error/PageNotFound" />
</httpErrors>
</system.webServer>
(Answer from How can I properly handle 404 in ASP.NET MVC?)
Would still be nice to know what is going on in the Application_Error.
You can handle a 404 by changing the customeErrors section in the web.config
There is also a redirectMode attribute which you can use to control the nature of the error page redirection (and avoid the 302) (Read here)
<configuration>
...
<system.web>
<customErrors mode="RemoteOnly"
redirectMode="ResponseRewrite"
defaultRedirect="/ErrorPages/Oops.aspx">
<error statusCode="404" redirect="/ErrorPages/404.aspx" />
</customErrors>
...
http://www.asp.net/hosting/tutorials/displaying-a-custom-error-page-cs
In ASP.net MVC, there is a method you can override to catch all exceptions thrown in a controller. Just override Controller.OnException(...) and you can do custom error handling in there as well. If all of your controllers inherit from a common base controller class, you can put the error handling there.
http://msdn.microsoft.com/en-us/library/system.web.mvc.controller.onexception.aspx
I've read many articles and several post (including here in stackoverflow) but do not know what I'm doing wrong.
Here my code:
Global.asax.cs
public static void RegisterGlobalFilters(GlobalFilterCollection filters)
{
filters.Add(new HandleErrorAttribute());
}
ErrorControler.cs
public class ErrorController : Controller
{
public ActionResult Error404()
{
return View();
}
public ActionResult Error500()
{
return View();
}
}
Web.config
<customErrors mode="On" defaultRedirect="~/Error/Error500">
<error statusCode="404" redirect="~/Error/Error404"/>
</customErrors>
MyController.cs
public ActionResult Index()
{
using (var db = new DataContext())
{
int a = 2, b = 0;
var r = a / b;
return View(r);
}
}
Error500.cshtml
#model System.Web.Mvc.HandleErrorInfo
#{
ViewBag.Title = "Erro";
}
<h2>#ViewBag.Title</h2>
<div id="error-info">
<p>Ocorreu um erro inexperado na página <a class="error-url" href="#Response["aspxerrorpath"]" title="Origem do erro">#Response["aspxerrorpath"]</a></p>
<p>Se o erro persistir, por-favor, entre em contato com os administradores do site.</p>
<div class="error-details">
<p>#Model.Exception.Message</p>
</div>
</div>
When I try to access the path /MyController the following message appears:
Server Error in '/' Application.
The resource cannot be found.
Description: HTTP 404. The resource you are looking for (or one of its
dependencies) could have been removed, had its name changed, or is
temporarily unavailable. Please review the following URL and make
sure that it is spelled correctly.
Requested URL: /Error/Error500
I would like that happen when an error on any controller, if the http status code has not been informed in web.config, it redirects to the default view Error500
In this article, for example, it handles DbException errors, but would like to handle any type of error.
Errors of type 404 (page not found) works perfectly. The user is redirected to the page Error404.cshtml
If you want this to happen remove/comment the following line from your Global.asax:
filters.Add(new HandleErrorAttribute());
You basically have to choose whether you want ASP.NET to handle your errors (the <customErrors> section in your web.config) or ASp.NET MVC (the global HandleErrorAttribute action filter, which by the way requires you to turn on custom errors in web.config)
Or checkout an alternative method for handling errors in ASP.NET MVC (with this approach you still have to remove the line I showed from your Global.asax).
I am trying to authenticate against the Huddle API using the Windows Phone 7 Emulator. However, I am not getting any success. I keep getting "The remote server returned an error: NotFound". I have even tried "dumbing down" my code and just trying a straight web site, eg. Google but still get the same result.
I have the following code:
string url = "http://www.google.com";
HttpWebRequest client= WebRequest.CreateHttp(new Uri(url)) as HttpWebRequest;
client.AllowReadStreamBuffering = true;
// Call and handle the response.
client.BeginGetResponse(
(asResult) =>
{
Dispatcher.BeginInvoke(
() =>
{
try
{
var response = client.EndGetResponse(asResult);
System.IO.StreamReader reader = new System.IO.StreamReader(response.GetResponseStream());
string responseString = reader.ReadToEnd();
}
catch (WebException failure)
{
throw failure;
}
});
},
null
);
Execution always ends up in the catch section. However, having watched Fiddler2, there seems not to be any traffic at all to google.com. So the request doesn't seem to be being made.
I've seen a similar problem here Retrieve XML from https using WebClient/HttpWebRequest - WP7, but I am using a standard port so not sure this is relevant. I have also tried simplifying the code as per the post, but no success.
Interestingly, the most likely option seems to be because I may not have Network Capabilities defined in my AppManifestWM.xaml file as per HttpWebRequest Breaks On WP7, but my AppManifestWM.xaml file appears to have this defined:
<Deployment xmlns="http://schemas.microsoft.com/windowsphone/2009/deployment" AppPlatformVersion="7.0">
<App xmlns="" ProductID="{ac5b5d62-573c-4134-b290-0ad4f678ad7f}" Title="xxx.WindowsPhone7.Client" RuntimeType="Silverlight" Version="1.0.0.0" Genre="apps.normal" Author="xxx.WindowsPhone7.Client author" Description="Sample description" Publisher="xxx.WindowsPhone7.Client publisher">
<IconPath IsRelative="true" IsResource="false">ApplicationIcon.png</IconPath>
<Capabilities>
<Capability Name="ID_CAP_NETWORKING" />
<Capability Name="ID_CAP_LOCATION" />
<Capability Name="ID_CAP_SENSORS" />
<Capability Name="ID_CAP_MICROPHONE" />
<Capability Name="ID_CAP_MEDIALIB" />
<Capability Name="ID_CAP_GAMERSERVICES" />
<Capability Name="ID_CAP_PHONEDIALER" />
<Capability Name="ID_CAP_PUSH_NOTIFICATION" />
<Capability Name="ID_CAP_WEBBROWSERCOMPONENT" />
</Capabilities>
<Tasks>
<DefaultTask Name ="_default" NavigationPage="MainPage.xaml"/>
</Tasks>
<Tokens>
<PrimaryToken TokenID="xxx.WindowsPhone7.ClientToken" TaskName="_default">
<TemplateType5>
<BackgroundImageURI IsRelative="true" IsResource="false">Background.png</BackgroundImageURI>
<Count>0</Count>
<Title>xxx.WindowsPhone7.Client</Title>
</TemplateType5>
</PrimaryToken>
</Tokens>
</App>
</Deployment>
So I'm at a loss. The request doesn't actually seem to be occurring, leading me to think something is preventing it.
Update:
Nothing changed, but thought this stack trace might heko:
System.Net.WebException was unhandled
Message=The remote server returned an
error: NotFound. StackTrace:
at System.Net.Browser.ClientHttpWebRequest.InternalEndGetResponse(IAsyncResult
asyncResult)
at System.Net.Browser.ClientHttpWebRequest.EndGetResponse(IAsyncResult
asyncResult)
at xxx.WindowsPhone7.Client.Views.AddHuddleUserPage.<>c__DisplayClass2.<>c__DisplayClass4.b__1()
at System.Reflection.RuntimeMethodInfo.InternalInvoke(RuntimeMethodInfo
rtmi, Object obj, BindingFlags
invokeAttr, Binder binder, Object
parameters, CultureInfo culture,
Boolean isBinderDefault, Assembly
caller, Boolean verifyAccess,
StackCrawlMark& stackMark)
at System.Reflection.RuntimeMethodInfo.InternalInvoke(Object
obj, BindingFlags invokeAttr, Binder
binder, Object[] parameters,
CultureInfo culture, StackCrawlMark&
stackMark)
at System.Reflection.MethodBase.Invoke(Object
obj, Object[] parameters)
at System.Delegate.DynamicInvokeOne(Object[]
args)
at System.MulticastDelegate.DynamicInvokeImpl(Object[]
args)
at System.Delegate.DynamicInvoke(Object[]
args)
at System.Windows.Threading.DispatcherOperation.Invoke()
at System.Windows.Threading.Dispatcher.Dispatch(DispatcherPriority
priority)
at System.Windows.Threading.Dispatcher.OnInvoke(Object
context)
at System.Windows.Hosting.CallbackCookie.Invoke(Object[]
args)
at System.Windows.Hosting.DelegateWrapper.InternalInvoke(Object[]
args)
at System.Windows.RuntimeHost.ManagedHost.InvokeDelegate(IntPtr
pHandle, Int32 nParamCount,
ScriptParam[] pParams, ScriptParam&
pResult)
The status is System.Net.WebExceptionStatus.UnknownError
Thanks for your time.
Never used Fiddler2 but had exact the same problem when developing a Windows Phone app.
For me the cause was quite different:
The WMAppManifest.xml was just missing ID_CAP_NETWORKING!
Since I got the "not found" exception and not a "not supported exception" I tried almost everything else until I found the real cause of the problem ... ;-)
I prefer disabling all CAPS and only enable the ones the app really needs since users will not understand/accept if an app needs access to "everything" ;-)
I worked several hours with the exact same symptoms as the original poster. Then I closed Fiddler2 as suggested above. And then it works. No more "The remote server returned and error: NotFound."
Magic! Thank you, kellyb. Should have upvoted but I do not have enough credit.
Do you have Fiddler running? I get this error repeatedly when Fiddler is attached to my networking stack. With Fiddler off, no issues.
I would be interested in hearing the why's behind that if someone knows...
Cheers
Shutting down Fiddler2 solved my issue.
Ok, I've solved it ... but don't know how. My machine has not been rebooted, my code has not changed. The only possible explanation is my emulator did crash a few times. Maybe something in there.
Thanks for your time, this is the code I'm using, which works well with the Huddle API:
string url = "https://api.huddle.net/v1/xml/workspaces"; ;
HttpWebRequest client= WebRequest.CreateHttp(new Uri(url)) as HttpWebRequest;
client.Credentials = new NetworkCredential(ViewModel.UserAccount.UserName, ViewModel.UserAccount.Password);
client.AllowReadStreamBuffering = true;
// Call and handle the response.
client.BeginGetResponse(
(asResult) =>
{
Dispatcher.BeginInvoke(
() =>
{
try
{
var response = client.EndGetResponse(asResult);
System.IO.StreamReader reader = new System.IO.StreamReader(response.GetResponseStream());
string responseString = reader.ReadToEnd();
}
catch (WebException failure)
{
MessageBox.Show(failure.Message, "Cannot authenticate", MessageBoxButton.OK);
#if DEBUG
throw failure;
#endif
}
});
},
null
);
This may just be a matter of resolving your network connectivity.
Can you access the web via IE and a WebBrowser control inside an app?
You may have a proxy in the way. See if this doco helps in that regard.
Proxy Support for Windows Phone Emulator