I'm having something that is occurring intermediately (like <1% of the time), that I have no idea how it is possible. I have a plugin registered on the Post Operation of the Qualify Lead event, and have overridden the Qualify Button to execute a Qualify Lead request, setting the CreateAccount, CreateContact, and CreateOpportunity values to false. The plugin then creates the Account, Contact and oppotunity, as well as 4 other potential custom entities.
Below is the relevant code:
protected override void ExecuteInternal(ExtendedPluginContext context)
{
var createdEntities = context.GetOutputParameterValue<EntityReferenceCollection>("CreatedEntities");
var initiatingUser = context.SystemOrganizationService.GetEntity<SystemUser>(context.InitiatingUserId, u => new { u.new_RelatedEmployee, u.FullName });
var initiatingUserEntityRef = initiatingUser.ToEntityReference();
var lead = RetrieveLead(context);
CreateAccount(context, lead, initiatingUserEntityRef, createdEntities);
CreateContact(context, lead, initiatingUserEntityRef, createdEntities);
CreateLocation(context, lead, initiatingUser, createdEntities);
CreateSystemPullJob(context, lead, initiatingUserEntityRef, createdEntities);
CreateInstallJob(context, lead, initiatingUserEntityRef, createdEntities);
CreateOpportunity(context, lead, initiatingUserEntityRef, createdEntities);
CreateOpportunityProducts(context, lead, initiatingUserEntityRef, createdEntities);
UpdateLead(context, lead, initiatingUser, createdEntities);
}
private static void CreateAccount(ExtendedPluginContext context, XrmLead lead, EntityReference initiatingUser, EntityReferenceCollection createdEntities)
{
if (lead.CustomerId != null)
{
context.Trace("Account already exists for Lead. Not creating Account.");
return;
}
context.Trace("Creating Account");
var account = context.SystemOrganizationService.InitializeFrom<Account>(lead.ToEntityReference(), TargetFieldType.ValidForCreate);
account.OwnerId = initiatingUser;
account.ModifiedOnBehalfBy = initiatingUser;
account.CreatedOnBehalfBy = initiatingUser;
account.Id = context.SystemOrganizationService.CreateWithSupressDuplicateDetection(account);
lead.CustomerId = account.ToEntityReference();
createdEntities.Add(account.ToEntityReference());
}
private static void CreateInstallJob(ExtendedPluginContext context,
XrmLead lead,
EntityReference initiatingUser,
EntityReferenceCollection createdEntities)
{
context.Trace("Creating Install Job");
var job = context.SystemOrganizationService.InitializeFrom<new_job>(lead.ToEntityReference(), TargetFieldType.ValidForCreate);
job.new_jobname = "New - Install";
job.new_CustomerId = lead.CustomerId;
job.new_LocationId = GetLocation(lead, createdEntities);
job.new_JobTypeEnum = new_JobType.Installation;
job.OwnerId = initiatingUser;
job.ModifiedOnBehalfBy = initiatingUser;
job.CreatedOnBehalfBy = initiatingUser;
if (lead.new_PreviousLocationId != null)
{
// Set prerequiste job to system pull job
job.new_PrerequisiteJobId = createdEntities.First(e => e.LogicalName == job.LogicalName);
}
job.Id = context.SystemOrganizationService.CreateWithSupressDuplicateDetection(job);
createdEntities.Add(job.ToEntityReference());
}
The account is created, added to the lead.CustomerId, and then used to add the relationship to the location upon creation.
According to the stack trace, the error happens on the Creation of the Install Job, (even though the Contact already was created, and references it as it's ParentCustomerId)
Unhandled Exception: System.ServiceModel.FaultException`1[[Microsoft.Xrm.Sdk.OrganizationServiceFault, Microsoft.Xrm.Sdk, Version=8.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35]]: Account With Id = d14241a1-eef1-e611-810e-e0071b6ac161 Does Not ExistDetail:
<OrganizationServiceFault xmlns:i="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://schemas.microsoft.com/xrm/2011/Contracts">
<ActivityId>05e171b8-60dd-44d5-ba40-42edb79620d8</ActivityId>
<ErrorCode>-2147220969</ErrorCode>
<ErrorDetails xmlns:d2p1="http://schemas.datacontract.org/2004/07/System.Collections.Generic" />
<Message>Account With Id = d14241a1-eef1-e611-810e-e0071b6ac161 Does Not Exist</Message>
<Timestamp>2017-02-13T13:16:34.5516854Z</Timestamp>
<ExceptionSource>SdkClient</ExceptionSource>
<InnerFault>
<ActivityId>05e171b8-60dd-44d5-ba40-42edb79620d8</ActivityId>
<ErrorCode>-2147220969</ErrorCode>
<ErrorDetails xmlns:d3p1="http://schemas.datacontract.org/2004/07/System.Collections.Generic" />
<Message>Account With Id = d14241a1-eef1-e611-810e-e0071b6ac161 Does Not Exist</Message>
<Timestamp>2017-02-13T13:16:34.5516854Z</Timestamp>
<ExceptionSource i:nil="true" />
<InnerFault i:nil="true" />
<OriginalException i:nil="true" />
<TraceText i:nil="true" />
</InnerFault>
<OriginalException>System.ServiceModel.FaultException`1[Microsoft.Xrm.Sdk.OrganizationServiceFault]: Account With Id = d14241a1-eef1-e611-810e-e0071b6ac161 Does Not Exist (Fault Detail is equal to Microsoft.Xrm.Sdk.OrganizationServiceFault).
at Microsoft.Crm.Extensibility.OrganizationSdkServiceInternal.Execute(OrganizationRequest request, CorrelationToken correlationToken, CallerOriginToken callerOriginToken, WebServiceType serviceType, Boolean checkAdminMode, ExecutionContext executionContext)
at Microsoft.Crm.Extensibility.OrganizationSdkServiceInternal.Execute(OrganizationRequest request, CorrelationToken correlationToken, CallerOriginToken callerOriginToken, WebServiceType serviceType)
at Microsoft.Crm.Extensibility.InprocessServiceProxy.ExecuteCore(OrganizationRequest request)
at Microsoft.Crm.Sandbox.SandboxSdkListener.ExecuteInternal(SandboxCallInfo callInfo, SandboxSdkContext requestContext, String operation, Byte[] serializedRequest, IExecutionContext context, String& primaryEntityName)
at Microsoft.Crm.Sandbox.SandboxSdkListener.Execute(SandboxCallInfo callInfo, SandboxSdkContext requestContext, String operation, Byte[] serializedRequest)
Original SdkErrors:
</OriginalException>
<TraceText>Entered Contoso.Xrm.Lead.Plugins.QualifyLeadLogic.Execute()
Contoso.Xrm.Lead.Plugins.QualifyLeadLogic.Execute is Executing for Entity: lead, Message: QualifyLead
Creating Account
Creating Contact
Creating Location
Creating Install Job
Exception: System.ServiceModel.FaultException`1[Microsoft.Xrm.Sdk.OrganizationServiceFault]: Account With Id = d14241a1-eef1-e611-810e-e0071b6ac161 Does Not Exist (Fault Detail is equal to Microsoft.Xrm.Sdk.OrganizationServiceFault).
Server stack trace:
at System.ServiceModel.Channels.ServiceChannel.HandleReply(ProxyOperationRuntime operation, ProxyRpc& rpc)
at System.ServiceModel.Channels.ServiceChannel.Call(String action, Boolean oneway, ProxyOperationRuntime operation, Object[] ins, Object[] outs, TimeSpan timeout)
at System.ServiceModel.Channels.ServiceChannelProxy.InvokeService(IMethodCallMessage methodCall, ProxyOperationRuntime operation)
at System.ServiceModel.Channels.ServiceChannelProxy.Invoke(IMessage message)
Exception rethrown at [0]:
at Microsoft.Crm.Sandbox.SandboxOrganizationService.Execute(String operation, Byte[] serializedRequest, Object sandboxTraceSettingsObj)
at System.Runtime.Remoting.Messaging.StackBuilderSink._PrivateProcessMessage(IntPtr md, Object[] args, Object server, Object[]& outArgs)
at System.Runtime.Remoting.Messaging.StackBuilderSink.SyncProcessMessage(IMessage msg)
Exception rethrown at [1]:
at System.Runtime.Remoting.Proxies.RealProxy.HandleReturnMessage(IMessage reqMsg, IMessage retMsg)
at System.Runtime.Remoting.Proxies.RealProxy.PrivateInvoke(MessageData& msgData, Int32 type)
at Microsoft.Crm.Sandbox.ISandboxOrganizationService.Execute(String operation, Byte[] serializedRequest, Object traceSettings)
at Microsoft.Crm.Sandbox.SandboxOrganizationServiceWrapper.ExecuteInternal(OrganizationRequest request)
at DLaB.Xrm.Extensions.CreateWithSupressDuplicateDetection(IOrganizationService service, Entity entity)
at Contoso.Xrm.Lead.Plugins.QualifyLeadLogic.CreateInstallJob(ExtendedPluginContext context, Lead lead, EntityReference initiatingUser, EntityReferenceCollection createdEntities)
at Contoso.Xrm.Lead.Plugins.QualifyLeadLogic.ExecuteInternal(ExtendedPluginContext context)
at DLaB.Xrm.Plugin.GenericPluginHandlerBase`1.ExecuteRegisteredEvent(T context)
at DLaB.Xrm.Plugin.GenericPluginHandlerBase`1.Execute(IServiceProvider serviceProvider)
**** Context Info ****
Plugin: Contoso.Xrm.Lead.Plugins.QualifyLeadLogic
* Registered Event *
Stage: PostOperation
Message: QualifyLead
Message Name: QualifyLead
Entity Logical Name:
Execute: Null
BusinessUnitId: 425821ca-d73c-e411-936d-a45d36fd8134
CorrelationId: 75366e73-bee1-4154-81a4-354a4c0ffe8f
Depth: 1
InitiatingUserId: 995e0b19-4592-e611-80f3-5065f38a4951
IsInTransaction: True
IsolationMode: 2
MessageName: QualifyLead
Mode: 0
OperationCreatedOn: 2/13/2017 1:16:32 PM
OperationId: 68ea91c1-3727-4cb4-a52d-3a632b4239e0
Organization: org8ea62131(fc3abc92-879c-4a08-8715-4156ce535b92)
OwningExtension: Contoso.Xrm.Lead.Plugins.QualifyLead: QualifyLead of lead (3d85ff0c-8705-e611-80ee-3863bb36bd38)
PrimaryEntityId: 00000000-0000-0000-0000-000000000000
PrimaryEntityName: lead
SecondaryEntityName: none
UserId: 995e0b19-4592-e611-80f3-5065f38a4951
* Input Parameters *
Param[CreateAccount]: False
Param[CreateContact]: False
Param[CreateOpportunity]: False
Param[LeadId]: EntityReference { LogicalName: lead, Name: , Id: 122448c6-edf1-e611-810e-e0071b6ac161}
Param[SourceCampaignId]: EntityReference { LogicalName: campaign, Name: , Id: 330a11ca-4687-e611-80f3-5065f38b21f2}
Param[Status]: 3
Param[OpportunityCurrencyId]:
Param[OpportunityCustomerId]:
Param[ProcessInstanceId]:
* Output Parameters *
Param[CreatedEntities] Entity Reference Collection:
EntityReference { LogicalName: account, Name: , Id: d14241a1-eef1-e611-810e-e0071b6ac161}
EntityReference { LogicalName: contact, Name: , Id: dd4241a1-eef1-e611-810e-e0071b6ac161}
EntityReference { LogicalName: new__location, Name: , Id: e64241a1-eef1-e611-810e-e0071b6ac161}
PostEntityImages: Empty
PreEntityImages: Empty
* Shared Variables *
Param[ChangedEntityTypes]: System.Collections.Generic.Dictionary`2[[System.String, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089],[System.String, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]]:
[lead, Update]
Param[Contoso.Xrm.Lead.Plugins.QualifyLeadLogic|QualifyLead|PostOperation|00000000-0000-0000-0000-000000000000]: 1
Has Parent Context: False
Stage: 40
Exiting Contoso.Xrm.Lead.Plugins.QualifyLeadLogic.Execute()
</TraceText>
</OrganizationServiceFault>
Server stack trace:
at System.ServiceModel.Channels.ServiceChannel.HandleReply(ProxyOperationRuntime operation, ProxyRpc& rpc)
at System.ServiceModel.Channels.ServiceChannel.Call(String action, Boolean oneway, ProxyOperationRuntime operation, Object[] ins, Object[] outs, TimeSpan timeout)
at System.ServiceModel.Channels.ServiceChannel.Call(String action, Boolean oneway, ProxyOperationRuntime operation, Object[] ins, Object[] outs)
at System.ServiceModel.Channels.ServiceChannelProxy.InvokeService(IMethodCallMessage methodCall, ProxyOperationRuntime operation)
at System.ServiceModel.Channels.ServiceChannelProxy.Invoke(IMessage message)
Exception rethrown at [0]:
at System.Runtime.Remoting.Proxies.RealProxy.HandleReturnMessage(IMessage reqMsg, IMessage retMsg)
at System.Runtime.Remoting.Proxies.RealProxy.PrivateInvoke(MessageData& msgData, Int32 type)
at Microsoft.Crm.Sandbox.ISandboxHost.ExecuteAndReturnTraceInfo(SandboxCallInfo callInfo, SandboxPluginExecutionContext requestContext, Guid pluginAssemblyId, Int32 sourceHash, String assemblyName, Guid pluginTypeId, String pluginTypeName, String pluginConfiguration, String pluginSecureConfig, String assemblyContents, Boolean returnTraceInfo)
at Microsoft.Crm.Sandbox.SandboxPlugin.Execute(SandboxClient client, SandboxCallTracker callTracker, IExecutionContext requestContext, String assemblyContents, Boolean returnTraceInfo)
at Microsoft.Crm.Sandbox.SandboxCodeUnit.Execute(IExecutionContext context)
I only see two possibilities, that the account wasn't created to begin with (seems unlikely since the contact creation was successful) or that the account is deleted after contact creation, but before Install Job Creation (but I'm not aware of anywhere that we perform deletions, and I don't think you can have a deletion of an entity in a transaction, from outside the transaction...)
Ideas?
Can you verify that the "missing account id" is the id of the account that was supposedly created?
If you query the db for this account after the error occurred, I guess it gets no hit?
Did you check "double click bug"? Issuing the QualifyLead twice "simultaneously" could of course lead to interesting effects, if there is possible SystemOrganizationService bleed between the two executions.
(Tried to make this a comment since it's technically not an answer, but it was too long.)
What happens if you comment out creation of the install job? Does everything else work correctly? Account gets created?
Another thing to check would be to query for the account after each of your create methods execute. Would help you narrow down when the account disappears.
Also, in regards to your note about deletions from outside the transaction being prevented, my understanding of how transactions work is as follows. What you suggest would be true if the delete came from something that creates its own transaction (an async plugin, say). But if the delete came from some synchronous plugin on create of contact, for example, then that plugin would also be running in the transaction. If that is true, then it would be allowed to delete the account.
Not an answer either but too long for comments
So if you're saying it a) happens intermittently and b) there is no other logic that could be deleting the account, I think the only conclusion is for some unknown timing reason, the create of installjob gets ahead of the account being visible to it. No clue why this would happen but again, to narrow things down you could catch the exception and not fail the transaction. This would at least tell you if the account actually did get created ok. If that's the case and the root cause of the timing issue can't be found, you could only try the installjob create if you are sure you can retrieve the account. All workarounds until more elimination of variables can be done.
Another thought is could it be security-related? That account does not exist message may really mean account does not exist for you. Seems odd if the plugin context user created it but maybe other security factors involved?
I have a Customer type field in a form with the schema name: myorg_customer. (Note that this is not an out-of-the-box customer field with schema name customerid that comes with CRM.)
I am opening a new Create form using javascript as follows:
var customer = [
{
id: "571A6CE5-3EBC-4672-A164-D8F9654D4FCF",
name: "TestContact"
}
];
parameters['myorg_customer'] = customer[0].id;
parameters['myorg_customername'] = customer[0].name;
parameters['myorg_customertype'] = "contact" // since my customer is a contact instead of an account.
parent.Xrm.Utility.openEntityForm("myorg_myentity", null, parameters);
But after doing so, the page changes to open the Create form but I get an error message saying "An error has occurred". The log file is as follows:
Unhandled Exception: System.ServiceModel.FaultException`1[[Microsoft.Xrm.Sdk.OrganizationServiceFault, Microsoft.Xrm.Sdk, Version=8.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35]]: System.Web.HttpUnhandledException: Microsoft Dynamics CRM has experienced an error. Reference number for administrators or support: #89B46272Detail:
<OrganizationServiceFault xmlns:i="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://schemas.microsoft.com/xrm/2011/Contracts">
<ErrorCode>-2147220970</ErrorCode>
<ErrorDetails xmlns:d2p1="http://schemas.datacontract.org/2004/07/System.Collections.Generic">
<KeyValuePairOfstringanyType>
<d2p1:key>CallStack</d2p1:key>
<d2p1:value xmlns:d4p1="http://www.w3.org/2001/XMLSchema" i:type="d4p1:string"> at System.Web.UI.Page.HandleError(Exception e)
at System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint)
at System.Web.UI.Page.ProcessRequest(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint)
at System.Web.UI.Page.ProcessRequest()
at System.Web.UI.Page.ProcessRequest(HttpContext context)
at System.Web.HttpApplication.CallHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute()
at System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously)</d2p1:value>
</KeyValuePairOfstringanyType>
</ErrorDetails>
<Message>System.Web.HttpUnhandledException: Microsoft Dynamics CRM has experienced an error. Reference number for administrators or support: #89B46272</Message>
<Timestamp>2017-01-03T13:41:22.8457002Z</Timestamp>
<InnerFault>
<ErrorCode>-2147220970</ErrorCode>
<ErrorDetails xmlns:d3p1="http://schemas.datacontract.org/2004/07/System.Collections.Generic">
<KeyValuePairOfstringanyType>
<d3p1:key>CallStack</d3p1:key>
<d3p1:value xmlns:d5p1="http://www.w3.org/2001/XMLSchema" i:type="d5p1:string"> at Microsoft.Crm.Application.ParameterFilter.ValidateParameter(HttpRequest request, ArrayList parameterCollection, String key, String value, ParameterSources source, EntityType pageEntityType, FormAdditionalAllowedParameters additionalAllowedParameters)
at Microsoft.Crm.Application.ParameterFilter.ValidateParameters(Page page, EntityType pageEntityType, Boolean alwaysEnableParameterChecking, FormAdditionalAllowedParameters formAdditionalAllowedParametersTemp)
at Microsoft.Crm.Application.Controls.AppPage.ValidatePageParameters()
at Microsoft.Crm.Application.Controls.AppPage.OnInit(EventArgs e)
at System.Web.UI.Control.InitRecursive(Control namingContainer)
at System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint)</d3p1:value>
</KeyValuePairOfstringanyType>
</ErrorDetails>
<Message>System.InvalidOperationException: Microsoft Dynamics CRM has experienced an error. Reference number for administrators or support: #46259303</Message>
<Timestamp>2017-01-03T13:41:22.8457002Z</Timestamp>
<InnerFault i:nil="true" />
<TraceText i:nil="true" />
</InnerFault>
<TraceText i:nil="true" />
</OrganizationServiceFault>
The same method works when setting an out-of-the-box customer field on a form by setting the customerid, customeridname, and customeridtype parameters.
Any insights?
Thanks,
Anindit
You'll need to add myorg_customer, myorg_customername and myorg_customertype as form parameters. Your error message is Crm's bad way of saying the form parameter isn't allowed...
These are the guidelines from the Documentation:
The following guidelines apply when setting the value of a lookup on a
form using a query string argument:
For simple lookups you must set the value and the text to display in the lookup. Use the suffix “name” with the name of the attribute to set the value for the text.
Don’t use any other arguments.
For customer and owner lookups you must set the value and the name in the same way you set them for simple lookups. In addition you must use the suffix “type” to specify the type of entity. Allowable values are account, contact, systemuser, and team.
You can’t set the values for partylist or regarding lookups.
I'd make sure you are using an actual Customer Field Type, and not just a Contact Reference. I'd also make sure that it isn't a regarding or a partylist. If it is, you will need to define parameter values that don't match what CRM is looking for (add Underscores for example myorg_customer_id, myorg_customer_name and myorg_customer_type) and then write code on the onload to read these parameters and populate the correct field.
We want to implement 'Record level security' in MS CRM Dynamics. On User and Case Entity we have an OptionSet which has below values, that Optionset has a lot of values, below are just simple values:
Category 1
Category 2
We want to restrict Category 1 users to see only Category 1 Cases and to restrict Category 2 users to see only Category 2 Cases.
What I have done so far?
I was thinking that this should be possible through Retrieve plugin, but after I wrote my code.. I found that the retrieve plugin is triggering 5 times when I tried to open a case record. It also does not throw my custom error.
public void Execute(IServiceProvider serviceProvider)
{
ITracingService tracer = (ITracingService)serviceProvider.GetService(typeof(ITracingService));
IPluginExecutionContext context = (IPluginExecutionContext)serviceProvider.GetService(typeof(IPluginExecutionContext));
IOrganizationServiceFactory factory = (IOrganizationServiceFactory)serviceProvider.GetService(typeof(IOrganizationServiceFactory));
IOrganizationService service = factory.CreateOrganizationService(context.UserId);
tracer.Trace("context.Depth = " + context.Depth);
if (context.Depth > 1)
return;
tracer.Trace("context.Stage = " + context.Stage);
tracer.Trace("context.MessageName = " + context.MessageName);
EntityReference entityReference = (EntityReference)context.InputParameters["Target"];
tracer.Trace("entityReferencee = " + entityReference.LogicalName);
if (context.OutputParameters != null && context.OutputParameters.Contains("BusinessEntity"))
{
if (context.OutputParameters["BusinessEntity"] is Entity)
{
Entity entity = (Entity)context.OutputParameters["BusinessEntity"];
tracer.Trace("entity.LogicalName = " + entity.LogicalName);
context.OutputParameters["BusinessEntity"] = null;
throw new Exception("You can not view this record.");
}
else
{
tracer.Trace("BusinessEntity entity is not an entity.");
}
}
else
{
tracer.Trace("BusinessEntity entity is null");
}
}
This is how the plugin is registered:
Error:
Detail of Log File is given below:
Unhandled Exception:
System.ServiceModel.FaultException`1[[Microsoft.Xrm.Sdk.OrganizationServiceFault,
Microsoft.Xrm.Sdk, Version=7.0.0.0, Culture=neutral,
PublicKeyToken=31bf3856ad364e35]]: System.Web.HttpUnhandledException:
Microsoft Dynamics CRM has experienced an error. Reference number for
administrators or support: #CF526D62Detail:
-2147220970 System.Web.HttpUnhandledException: Microsoft Dynamics
CRM has experienced an error. Reference number for administrators or
support: #CF526D62
2015-09-21T12:33:00.6154994Z
-2147220956
Unexpected exception from plug-in (Execute): RestrictUserAccess.Case: System.Exception: You can not view this
record.
2015-09-21T12:33:00.6154994Z
[RestrictUserAccess: RestrictUserAccess.Case]
[c8860cb6-4260-e511-80ea-3863bb3600d8: RestrictUserAccess.Case:
Retrieve of incident]
context.Depth = 1 context.Stage = 40 context.MessageName = Retrieve
entityReferencee = incident entity.LogicalName = incident
Your code does throw the exception, but the CRM platform handles it as an unexpected error. (Just read the log details.)
When you need to signal a functional error, you have to throw an InvalidPluginExecutionException.
It is possible that the system itself is retrieving the same Case record multiple times. Also scripting on your web form or in the ribbon can be responsible for retrieving the same record, e.g. when it needs to evaluate the record state.
Therefore throwing exceptions on retrieval of Case records may not be a useful solution. An alternative approach could be to clear all (or all sensitive) fields on retrieval by removing them from the Entity.Attributes collection.
I have created a new Surface controller for use with my Umbraco 7.1.8 installation. My code is as follows:
public class EnquiryController : SurfaceController
{
ILog Log = LogManager.GetLogger(
MethodBase.GetCurrentMethod().DeclaringType
);
[HttpPost]
public ActionResult Submit(EnquiryModel model)
{
if (!ModelState.IsValid)
return CurrentUmbracoPage();
// Create a regular expression to remove script tags
Regex regex = new Regex(#"<script(.+?)*</script>");
string request = regex.Replace(model.Message, string.Empty);
request = request + "<br/><br/>" + "Phone: " + model.Telephone + "<br/><br/>" + "Email: " + model.Email;
MailMessage message = new MailMessage();
message.From = new MailAddress(model.Email);
message.To.Add(new MailAddress("info#axumtech.com"));
message.Subject = "New Website Enquiry - " + model.Name;
message.Body = request;
SmtpClient client = new SmtpClient();
try
{
client.Send(message);
TempData["success"] = true;
}
catch (Exception ex)
{
TempData["error"] = true;
Log.Debug("Custom Error - " + ex.Message);
return CurrentUmbracoPage();
}
return RedirectToCurrentUmbracoPage();
}
}
My problem is my code fails to send the Email and simply performs the CurrentUmbracoPage() method call.
To counteract this and find out what the issue is I have attempted to log the Exception that is generated using Log4Net however this does not appear to be working as nothing is written to the standard Umbraco log.
This is all occuring on a live server. I have published my development code using Visual Studio 2013 and then uploaded this published site to the server via FTP ensuring that the correct SMTP detals are entered into the Web.Config.
The one thing that concerns me and could be a cause of this issue is that this publish process seems to omit the /Controllers and /Models folders from my solution despite the actually being a part of the project. Is this an issue or are these compiled in .dlls?
To me it seems rather odd that the controllers folder is omitted and could potentially explain why the Email is not being sent..
Have you built your project? Your controllers are compiled into a dll so do not need to be included in the published site.
If you are still building this page then get rid of the try catch and turn custom errors off so you get the ysod - you want this page to fail with direc feedback
However, to get logging working:
At the top create using ref
using Umbraco.Core.Logging
In the catch:
LogHelper.Error(MethodBase.GetCurrentMethod().DeclaringType, ex.ToString(), ex)
It seems you have a problem in your log4net configuration (are you calling XmlConfigurator.Configure?). The easiest way to solve this is to enable internal logging to see what is wrong:
enable the internal logging:
<appSettings>
<add key="log4net.Internal.Debug" value="true"/>
</appSettings>
Set the output location:
<system.diagnostics>
<trace autoflush="true">
<listeners>
<add name="textWriterTraceListener" type="System.Diagnostics.TextWriterTraceListener" initializeData="C:\tmp\log4net.txt" />
</listeners>
</trace>
</system.diagnostics>
This issue was caused by an error in my model. The model parameter was marked as an int but a text string was being sent through to it by the form. Because of this the model was always invalid and therefore would redirect the page before it ever hit the logging.
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.