Account That Was Just Created No Longer Exists in CRM Plugin - dynamics-crm-online

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?

Related

How disable location in Xamarin.Forms UI Test

How can I disable location while single UI test in xamarin forms (I am using Android 8.1 simulator)? In one test case I want cancel location permission, and in other simulate that the GPS can not find user location.
I thought about backdors, but I did not found nothing useful or up to date on msdn and stack (some links pasted bellow).
I have tried something like this (and much more similar 'mutations'):
Droid.MainActivity:
[Export("GpsBackdoor")]
public void GpsBackdoor()
{
Intent intent = new Intent("android.location.GPS_ENABLED_CHANGE");
intent.PutExtra("enabled", Java.Lang.Boolean.False);
SendBroadcast(intent);
}
UITests.Test:
[Test]
public void SetCurrentUserLocation_WhenGPSisOff_ShouldShowAlert()
{
app.WaitForElement(x => x.Text("Nearest stops"));
app.Invoke("GpsBackdoor");
app.Tap(x => x.Text("Nearest stops"));
var result = app.WaitForElement("Could not obtain position");
}
After running test I am getting message:
System.Exception : Error while performing Invoke("GpsBackdoor", null)
----> System.Net.Http.HttpRequestException : An error occurred while sending
the request.
----> System.Net.WebException : The underlying connection was closed: The
connection was closed unexpectedly.
at Xamarin.UITest.Utils.ErrorReporting.With[T](Func`1 func, Object[] args,
String memberName)
at Xamarin.UITest.Android.AndroidApp.Invoke(String methodName, Object
argument)
at BusMap.Mobile.UITests.NearestStopsMapPageTests.
SetCurrentUserLocation_WhenGPSisOff_ShouldShowAlert() in
<source>\NearestStopsMapPageTests.cs:line 40
--HttpRequestException
at Xamarin.UITest.Shared.Http.HttpClient.SendData(String endpoint, String
method, HttpContent content, ExceptionPolicy exceptionPolicy, Nullable`1
timeOut)
at Xamarin.UITest.Shared.Http.HttpClient.Post(String endpoint, String
arguments, ExceptionPolicy exceptionPolicy, Nullable`1 timeOut)
at Xamarin.UITest.Android.AndroidGestures.Invoke(String methodName, Object[]
arguments)
at Xamarin.UITest.Utils.ErrorReporting.With[T](Func`1 func, Object[] args,
String memberName)
--WebException
at System.Net.HttpWebRequest.EndGetResponse(IAsyncResult asyncResult)
at System.Net.Http.HttpClientHandler.GetResponseCallback(IAsyncResult ar)
I've also tried turn off Wifi or cellular data, which gave me the same error.
I will be grateful for any help.
P.S. Some links which I've found:
Enable/Disable wifi using Xamarin UiTest
How to start GPS ON and OFF programatically in Android

LINQ Query getting timedOut

I have getting following error message in my custom log file :
2018-03-07 15:40:51,897 ERROR - The request channel timed out while waiting for a reply after 00:01:59.9880000. Increase the timeout value passed to the call to Request or increase the SendTimeout value on the Binding. The time allotted to this operation may have been a portion of a longer timeout.
mscorlib
Server stack trace:
at System.ServiceModel.Channels.RequestChannel.Request(Message message, TimeSpan timeout)
at System.ServiceModel.Channels.SecurityChannelFactory`1.SecurityRequestChannel.Request(Message message, TimeSpan timeout)
at System.ServiceModel.Dispatcher.RequestChannelBinder.Request(Message message, TimeSpan timeout)
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 System.Runtime.Remoting.Proxies.RealProxy.HandleReturnMessage(IMessage reqMsg, IMessage retMsg)
at System.Runtime.Remoting.Proxies.RealProxy.PrivateInvoke(MessageData& msgData, Int32 type)
at Microsoft.Xrm.Sdk.IOrganizationService.Execute(OrganizationRequest request)
at Microsoft.Xrm.Sdk.Client.OrganizationServiceProxy.ExecuteCore(OrganizationRequest request)
at Microsoft.Xrm.Sdk.Client.OrganizationServiceProxy.Execute(OrganizationRequest request)
at Microsoft.Xrm.Sdk.Client.OrganizationServiceContext.Execute(OrganizationRequest request)
at Microsoft.Xrm.Sdk.Linq.QueryProvider.RetrieveEntityCollection(OrganizationRequest request, NavigationSource source)
at Microsoft.Xrm.Sdk.Linq.QueryProvider.Execute(QueryExpression qe, Boolean throwIfSequenceIsEmpty, Boolean throwIfSequenceNotSingle, Projection projection, NavigationSource source, List`1 linkLookups, String& pagingCookie, Boolean& moreRecords)
at Microsoft.Xrm.Sdk.Linq.QueryProvider.Execute[TElement](QueryExpression qe, Boolean throwIfSequenceIsEmpty, Boolean throwIfSequenceNotSingle, Projection projection, NavigationSource source, List`1 linkLookups)
at Microsoft.Xrm.Sdk.Linq.QueryProvider.Execute[TElement](Expression expression)
at Microsoft.Xrm.Sdk.Linq.QueryProvider.GetEnumerator[TElement](Expression expression)
at Microsoft.Xrm.Sdk.Linq.Query`1.GetEnumerator()
at System.Collections.Generic.List`1..ctor(IEnumerable`1 collection)
at System.Linq.Enumerable.ToList[TSource](IEnumerable`1 source)
at ACE.Crm.Business.Logic.CustomerCommunicationsLogic.RetrieveCustomers() in C:\Dev\Crm\Active\Src\ACE.Crm.Business\Logic\CustomerCommunicationsLogic.cs:line 541
This is all happening due to one filter condition in LINQ :
var list = (
from c in _crmRepository.Query<Contact>()
join cn in _crmRepository.Query<Connection>() on c.ContactId equals cn.Record1Id.Id
join a in _crmRepository.Query<Account>() on cn.RecordId2.Id equals a.AccountId.Value
where c.StateCode.Value == (int)ContactState.Active
&& cn.StateCode.Value == (int)ConnectionState.Active
&& c.BirthDate != null
&& a.ace_NetworkClient.GetValueOrDefault()
select new ReturnedCustomerDataClass
{
AccountId = a.AccountId.GetValueOrDefault(),
ContactId = c.ContactId.GetValueOrDefault(),
aceContactId = c.ace_ContactID,
<<<<<<< Many Other Fields>>>>>>>>>>>
}
In Where Clause you can see a filter a.ace_NetworkClient.GetValueOrDefault().
When I am removing this filter my query is not responding and being stuck. Can any one suggest me what is going wrong if I am removing filter && a.ace_NetworkClient.GetValueOrDefault() {ace_NetworkClient is a boolean field}.
In my result I wanted both customer for whom ace_NetworkClient flag is true or false thats why I removed that existing condition, getting proper result for local Org. but failing in production org due to large data.
Thanks

Out of Memory Exception in System.Runtime.CompilerServices.RuntimeHelpers

I have an MVC 5 site running in a shared hosting environment. It uses Linq to Sql for data access. About 5-8 times a day it experiences an "Out of Memory Exception" in System.Runtime.CompilerServices.RuntimeHelpers. The problem occurs on different requests and is intermittent. It appears to be happening early in the controller method when the system is looking up a single record in a single table. Hosting provider does not seem able to help. Error report follows:
An application error has occurred in ClaytonBocce.org
** Application Information **
Application domain: /LM/W3SVC/119/ROOT-1-131413223158297977
Trust level: Full
Application Virtual Path: /
Application Path: D:\inetpub\claytonbocce\
Machine name: WEBA36
** Events **
Event code: 3005
Event message: An unhandled exception has occurred.
Event time: 6/7/2017 10:20:34 AM
Event time (UTC): 6/7/2017 5:20:34 PM
Event ID: f643ddd5511449fba679c11b0e67d562
Event sequence: 152
Event occurrence: 1
Event detail code: 0
Process information:
Process ID: 1012212
Process name: w3wp.exe
Account name: WEBA36\IUSR_216.119.96.82
Exception information:
Exception type: System.OutOfMemoryException
Exception message: Exception of type 'System.OutOfMemoryException' was thrown.
Request information:
Request URL: https://www.claytonbocce.org:443/League/Match/4612/281
Request path: /League/Match/4612/281
User host address: 66.234.194.42
User:
Is authenticated: False
Authentication Type:
Thread account name: WEBA36\IUSR_216.119.96.82
Thread information:
Thread ID: 340
Thread account name: WEBA36\IUSR_216.119.96.82
Is impersonating: False
Stack trace: at
System.Runtime.CompilerServices.RuntimeHelpers._CompileMethod(IRuntimeMethodInfo method)
at System.Reflection.Emit.DynamicMethod.CreateDelegate(Type delegateType)
at System.Data.Linq.SqlClient.ObjectReaderCompiler.Compile(SqlExpression expression, Type elementType)
at System.Data.Linq.SqlClient.SqlProvider.GetReaderFactory(SqlNode node, Type elemType)
at System.Data.Linq.SqlClient.SqlProvider.System.Data.Linq.Provider.IProvider.Execute(Expression query)
at System.Data.Linq.DataQuery`1.System.Linq.IQueryProvider.Execute[S](Expression expression)
at BocceData.Model.BocceWork.get_CurrentSeason() in D:\Users\dev\Documents\Visual Studio 2015\Projects\ClaytonBocce\BocceData\Model\BocceActive.cs:line 15
at BocceData.Model.BocceWork.SetSeason(Int32 sid) in D:\Users\dev\Documents\Visual Studio 2015\Projects\ClaytonBocce\BocceData\Model\BocceActive.cs:line 37
at BocceData.Model.BocceWork.GoToSeason(Int32 sid, Boolean requireTeam) in D:\Users\dev\Documents\Visual Studio 2015\Projects\ClaytonBocce\BocceData\Model\BocceActive.cs:line 66
at BocceData.Model.BocceWork.set_ActiveValue(String value) in D:\Users\dev\Documents\Visual Studio 2015\Projects\ClaytonBocce\BocceData\Model\BocceActive.cs:line 119
at System.Web.Mvc.Async.AsyncControllerActionInvoker.AsyncInvocationWithFilters.InvokeActionMethodFilterAsynchronouslyRecursive(Int32 filterIndex)
at System.Web.Mvc.Async.AsyncControllerActionInvoker.<>c__DisplayClass33.<BeginInvokeActionMethodWithFilters>b__31(AsyncCallback asyncCallback, Object asyncState)
at System.Web.Mvc.Async.AsyncResultWrapper.WrappedAsyncResultBase`1.Begin(AsyncCallback callback, Object state, Int32 timeout)
at System.Web.Mvc.Async.AsyncControllerActionInvoker.BeginInvokeActionMethodWithFilters(ControllerContext controllerContext, IList`1 filters, ActionDescriptor actionDescriptor, IDictionary`2 parameters, AsyncCallback callback, Object state)
at System.Web.Mvc.Async.AsyncControllerActionInvoker.<>c__DisplayClass21.<BeginInvokeAction>b__19(AsyncCallback asyncCallback, Object asyncState)
at System.Web.Mvc.Async.AsyncResultWrapper.WrappedAsyncResultBase`1.Begin(AsyncCallback callback, Object state, Int32 timeout)
at System.Web.Mvc.Async.AsyncControllerActionInvoker.BeginInvokeAction(ControllerContext controllerContext, String actionName, AsyncCallback callback, Object state)
at System.Web.Mvc.Controller.<BeginExecuteCore>b__1c(AsyncCallback asyncCallback, Object asyncState, ExecuteCoreState innerState)
at System.Web.Mvc.Async.AsyncResultWrapper.WrappedAsyncVoid`1.CallBeginDelegate(AsyncCallback callback, Object callbackState)
at System.Web.Mvc.Async.AsyncResultWrapper.WrappedAsyncResultBase`1.Begin(AsyncCallback callback, Object state, Int32 timeout)
at System.Web.Mvc.Controller.BeginExecuteCore(AsyncCallback callback, Object state)
at System.Web.Mvc.Async.AsyncResultWrapper.WrappedAsyncResultBase`1.Begin(AsyncCallback callback, Object state, Int32 timeout)
at System.Web.Mvc.Controller.BeginExecute(RequestContext requestContext, AsyncCallback callback, Object state)
at System.Web.Mvc.MvcHandler.<BeginProcessRequest>b__4(AsyncCallback asyncCallback, Object asyncState, ProcessRequestState innerState)
at System.Web.Mvc.Async.AsyncResultWrapper.WrappedAsyncVoid`1.CallBeginDelegate(AsyncCallback callback, Object callbackState)
at System.Web.Mvc.Async.AsyncResultWrapper.WrappedAsyncResultBase`1.Begin(AsyncCallback callback, Object state, Int32 timeout)
at System.Web.Mvc.MvcHandler.BeginProcessRequest(HttpContextBase httpContext, AsyncCallback callback, Object state)
at System.Web.HttpApplication.CallHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute()
at System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously)
Here is the code that calls LINQ in this failure. Line 15 is the first line of the get. BocceSeasons is a LINQ to SQL table. But this is not the only failure location; the memory exception is thrown in different locations and not consistently in any one location in the application, but always in System.Runtime.CompilerServices.RuntimeHelpers._CompileMethod.
public BocceSeason CurrentSeason
{
get
{
BocceSeason sn = BocceSeasons.OrderByDescending(s => s.id).FirstOrDefault(s => s.IsCurrent);
if (sn == null) throw new ApplicationException("BocceActive: No current season found");
return sn;
}
}

Sometimes, error "ORA-00933" occurs when using entity framework to query to Oracle DB but when I restart the webapp, it works

I have used Entity Framework 5 for Oralce Database of web-based application. Sometimes (rarely happens), error "ORA-00933" occurs but when I restart the webapp, it gets work again.
This is log:
System.Data.EntityCommandExecutionException: An error occurred while
executing the command definition. See the inner exception for details.
---> Oracle.ManagedDataAccess.Client.OracleException: ORA-00933: SQL command not properly ended at
OracleInternal.ServiceObjects.OracleCommandImpl.VerifyExecution(OracleConnectionImpl
connectionImpl, Int32& cursorId, Boolean bThrowArrayBindRelatedErrors,
OracleException& exceptionForArrayBindDML, Boolean& hasMoreRowsInDB,
Boolean bFirstIterationDone) at
OracleInternal.ServiceObjects.OracleCommandImpl.ExecuteReader(String
commandText, OracleParameterCollection paramColl, CommandType
commandType, OracleConnectionImpl connectionImpl,
OracleDataReaderImpl& rdrImpl, Int32 longFetchSize, Int64
clientInitialLOBFS, OracleDependencyImpl orclDependencyImpl, Int64[]
scnForExecution, Int64[]& scnFromExecution, OracleParameterCollection&
bindByPositionParamColl, Boolean& bBindParamPresent, Int64&
internalInitialLOBFS, OracleException& exceptionForArrayBindDML,
Boolean isDescribeOnly, Boolean isFromEF) at
Oracle.ManagedDataAccess.Client.OracleCommand.ExecuteReader(Boolean
requery, Boolean fillRequest, CommandBehavior behavior) at
Oracle.ManagedDataAccess.Client.OracleCommand.ExecuteDbDataReader(CommandBehavior
behavior) at
System.Data.EntityClient.EntityCommandDefinition.ExecuteStoreCommands(EntityCommand
entityCommand, CommandBehavior behavior) --- End of inner exception
stack trace --- at
System.Data.EntityClient.EntityCommandDefinition.ExecuteStoreCommands(EntityCommand
entityCommand, CommandBehavior behavior) at
System.Data.Objects.Internal.ObjectQueryExecutionPlan.Execute[TResultType](ObjectContext
context, ObjectParameterCollection parameterValues) at
System.Data.Objects.ObjectQuery1.GetResults(Nullable1
forMergeOption) at
System.Data.Objects.ObjectQuery1.System.Collections.Generic.IEnumerable<T>.GetEnumerator()
at System.Linq.Enumerable.SingleOrDefault[TSource](IEnumerable1
source) at
System.Linq.Queryable.SingleOrDefault[TSource](IQueryable`1 source)
at MOS.DAO.HisTreatment.HisTreatmentGet.GetById(Int64 id,
HisTreatmentSO search)
This is the code "HisTreatmentGet.GetById":
HIS_TREATMENT result = null;
try
{
bool valid = true;
using (var ctx = new AppContext())
{
var query = ctx.HIS_TREATMENT.AsQueryable().Where(p => p.ID == id);
...
result = query.SingleOrDefault();
}
}
catch (Exception ex)
{
....
}
return result;
I've tried searching on google but there's no solution. Anyone can give me advices?
There is a bug in the provider for Entity Framework from Oracle.
Seems like the Oracle.ManagedDataAccess.EntityFramework.SqlGen.SqlSelectStatement.Top_s is the culprit that gets borrowed by a parallel query. This should either be thread static (quick hack) or moved to some contextual state (proper fix, e.g. to SqlGenerator).
https://community.oracle.com/thread/3728543
No answer from Oracle support. That being said, there is a new version of the nuget package : 12.2.110. You may give it a try and check if the issue is fixed.

System.Data.DataException error occurred in EntityFramework.dll

I have been following this tutorial Getting Started with Entity Framework 6 Code First using MVC 5.
When I got to the section where I need to run the program and click on Student so that the program would create database I get the following error.
System.Data.DataException was unhandled by user code
HResult=-2146233087
Message=An exception occurred while initializing the database. See the InnerException for details.
Source=EntityFramework
StackTrace:
at System.Data.Entity.Internal.InternalContext.PerformInitializationAction(Action action)
at System.Data.Entity.Internal.InternalContext.PerformDatabaseInitialization()
at System.Data.Entity.Internal.LazyInternalContext.b__4(InternalContext c)
at System.Data.Entity.Internal.RetryAction1.PerformAction(TInput input)
at System.Data.Entity.Internal.LazyInternalContext.InitializeDatabaseAction(Action1 action)
at System.Data.Entity.Internal.LazyInternalContext.InitializeDatabase()
at System.Data.Entity.Internal.InternalContext.Initialize()
at System.Data.Entity.Internal.InternalContext.GetEntitySetAndBaseTypeForType(Type entityType)
at System.Data.Entity.Internal.Linq.InternalSet1.Initialize()
at System.Data.Entity.Internal.Linq.InternalSet1.GetEnumerator()
at System.Data.Entity.Infrastructure.DbQuery1.System.Collections.Generic.IEnumerable<TResult>.GetEnumerator()
at System.Collections.Generic.List1..ctor(IEnumerable1 collection)
at System.Linq.Enumerable.ToList[TSource](IEnumerable1 source)
at ContosoUniversityFollow.Controllers.StudentController.Index() in c:\Users\Office\Documents\Visual Studio 2013\Projects\ContosoUniversityFollow\ContosoUniversityFollow\Controllers\StudentController.cs:line 21
at lambda_method(Closure , ControllerBase , Object[] )
at System.Web.Mvc.ActionMethodDispatcher.Execute(ControllerBase controller, Object[] parameters)
at System.Web.Mvc.ReflectedActionDescriptor.Execute(ControllerContext controllerContext, IDictionary2 parameters)
at System.Web.Mvc.ControllerActionInvoker.InvokeActionMethod(ControllerContext controllerContext, ActionDescriptor actionDescriptor, IDictionary2 parameters)
at System.Web.Mvc.Async.AsyncControllerActionInvoker.ActionInvocation.InvokeSynchronousActionMethod()
at System.Web.Mvc.Async.AsyncControllerActionInvoker.b__36(IAsyncResult asyncResult, ActionInvocation innerInvokeState)
at System.Web.Mvc.Async.AsyncResultWrapper.WrappedAsyncResult2.CallEndDelegate(IAsyncResult asyncResult)
at System.Web.Mvc.Async.AsyncResultWrapper.WrappedAsyncResultBase1.End()
at System.Web.Mvc.Async.AsyncResultWrapper.End[TResult](IAsyncResult asyncResult, Object tag)
at System.Web.Mvc.Async.AsyncControllerActionInvoker.EndInvokeActionMethod(IAsyncResult asyncResult)
at System.Web.Mvc.Async.AsyncControllerActionInvoker.AsyncInvocationWithFilters.b__3c()
at System.Web.Mvc.Async.AsyncControllerActionInvoker.AsyncInvocationWithFilters.<>c__DisplayClass45.b__3e()
InnerException: System.Data.Entity.Core.EntityException
HResult=-2146233087
Message=The underlying provider failed on Open.
Source=EntityFramework
StackTrace:
at System.Data.Entity.Core.EntityClient.EntityConnection.Open()
at System.Data.Entity.Core.Objects.ObjectContext.EnsureConnection()
at System.Data.Entity.Core.Objects.ObjectContext.ExecuteInTransaction[T](Func1 func, IDbExecutionStrategy executionStrategy, Boolean startLocalTransaction, Boolean releaseConnectionOnSuccess)
at System.Data.Entity.Core.Objects.ObjectQuery1.<>c__DisplayClassb.b__9()
at System.Data.Entity.SqlServer.DefaultSqlExecutionStrategy.Execute[TResult](Func1 operation)
at System.Data.Entity.Core.Objects.ObjectQuery1.GetResults(Nullable1 forMergeOption)
at System.Data.Entity.Core.Objects.ObjectQuery1..GetEnumerator>b__0()
at System.Lazy1.CreateValue()
at System.Lazy1.LazyInitValue()
at System.Lazy1.get_Value()
at System.Data.Entity.Internal.LazyEnumerator1.MoveNext()
at System.Linq.Enumerable.FirstOrDefault[TSource](IEnumerable1 source)
at System.Data.Entity.Core.Objects.ELinq.ObjectQueryProvider.<GetElementFunction>b__1[TResult](IEnumerable1 sequence)
at System.Data.Entity.Core.Objects.ELinq.ObjectQueryProvider.ExecuteSingle[TResult](IEnumerable1 query, Expression queryRoot)
at System.Data.Entity.Core.Objects.ELinq.ObjectQueryProvider.System.Linq.IQueryProvider.Execute[TResult](Expression expression)
at System.Data.Entity.Internal.Linq.DbQueryProvider.Execute[TResult](Expression expression)
at System.Linq.Queryable.FirstOrDefault[TSource](IQueryable1 source)
at System.Data.Entity.Internal.EdmMetadataRepository.QueryForModelHash(Func2 createContext)
at System.Data.Entity.Internal.InternalContext.QueryForModelHash()
at System.Data.Entity.Internal.ModelCompatibilityChecker.CompatibleWithModel(InternalContext internalContext, ModelHashCalculator modelHashCalculator, Boolean throwIfNoMetadata)
at System.Data.Entity.Internal.InternalContext.CompatibleWithModel(Boolean throwIfNoMetadata)
at System.Data.Entity.Database.CompatibleWithModel(Boolean throwIfNoMetadata)
at System.Data.Entity.DropCreateDatabaseIfModelChanges1.InitializeDatabase(TContext context)
at System.Data.Entity.Internal.InternalContext.<>c__DisplayClasse1.<CreateInitializationAction>b__d()
at System.Data.Entity.Internal.InternalContext.PerformInitializationAction(Action action)
InnerException: System.Data.SqlClient.SqlException
HResult=-2146232060
Message=Cannot open database "ContosoUniversity1" requested by the login. The login failed.
Login failed for user 'Office-PC\Office'.
Source=.Net SqlClient Data Provider
ErrorCode=-2146232060
Class=11
LineNumber=65536
Number=4060
Procedure=""
Server=(LocalDb)\v11.0
State=1
StackTrace:
at System.Data.ProviderBase.DbConnectionPool.TryGetConnection(DbConnection owningObject, UInt32 waitForMultipleObjectsTimeout, Boolean allowCreate, Boolean onlyOneCheckConnection, DbConnectionOptions userOptions, DbConnectionInternal& connection)
at System.Data.ProviderBase.DbConnectionPool.TryGetConnection(DbConnection owningObject, TaskCompletionSource1 retry, DbConnectionOptions userOptions, DbConnectionInternal& connection)
at System.Data.ProviderBase.DbConnectionFactory.TryGetConnection(DbConnection owningConnection, TaskCompletionSource1 retry, DbConnectionOptions userOptions, DbConnectionInternal oldConnection, DbConnectionInternal& connection)
at System.Data.ProviderBase.DbConnectionInternal.TryOpenConnectionInternal(DbConnection outerConnection, DbConnectionFactory connectionFactory, TaskCompletionSource1 retry, DbConnectionOptions userOptions)
at System.Data.ProviderBase.DbConnectionClosed.TryOpenConnection(DbConnection outerConnection, DbConnectionFactory connectionFactory, TaskCompletionSource1 retry, DbConnectionOptions userOptions)
at System.Data.SqlClient.SqlConnection.TryOpenInner(TaskCompletionSource1 retry)
at System.Data.SqlClient.SqlConnection.TryOpen(TaskCompletionSource1 retry)
at System.Data.SqlClient.SqlConnection.Open()
at System.Data.Entity.SqlServer.DefaultSqlExecutionStrategy.<>c__DisplayClass1.<Execute>b__0()
at System.Data.Entity.SqlServer.DefaultSqlExecutionStrategy.Execute[TResult](Func1 operation)
at System.Data.Entity.SqlServer.DefaultSqlExecutionStrategy.Execute(Action operation)
at System.Data.Entity.Core.EntityClient.EntityConnection.Open()
InnerException:
I have a hard time trying to fix the problem. I follow everything and even redo it just to make sure I got it right. I don't think I miss any steps. But there is something wrong. If I run the whole sample code, everything works fine.
Any help is appreciated.
Thanks,
Pheap
EDIT:
It was really frustrating for a simple thing that lead to an error like this.
#mmeasor, I just saw that error as well. It cannot connect to database. So that lead me to check the connection.
What happen was that at first I used this connection string:
So EntityFramework created a database file ContosoUniversity1.mdf in here like C:\Users\Office\ContosoUniversity1.mdf. But then I want it to create another one and use that instead and this time I want it to be in the program App_Data\ folder instead.
So I modified the web.config file to:
I thought if I do that, EF will create a new database for me in the \App_Data\ folder and link to that instead of the old on in C:\Users\Office.
I was so wrong! that was when I start getting the error posted above. And I cannot find what causes the problem.
With the second web.config, I tried to copy the database file to the App_Data folder, but that still doesn't work.
Now I use the first connection string and it works fine.
So now the question is: How to make the program links to database file in the \App_Data\ folder instead?
Thanks,
Pheap
I had the same problem in trying to change location of Conosto University tutorial database from User folder to App_Data folder. John Locke keyed me into the idea that it may have something to do with having to change the name of the database.
Change name slightly of database named in the web.config file (This works inconsistently, but does work consistently inconsistently. If I had to test this again...and I'm sure I will at some point...I would stay away from reusing names - i.e. don't toggle back and forth between two name preferences (e.g. database1 and database2 back to database1 - I would use completely novel names e.g. databse7...database8...database9 - get name away from previously used names)
I also had luck, once a database was created with the name I didn't want, changing the database name to what I wanted it to be and matching that name in web.config (i.e. I was able to create a "database3.mdf" file successfully and then changed it in the OS to what I wanted - "database1.mdf" and matched the web.config file to database1 and it connected up on the first try)
I had this problem for days ("An exception of type 'System.Data.DataException' occurred in EntityFramework.dll but was not handled in user code") and I tried everything since changing the connection string to many different methods I saw on Internet questions and answers,
My solution?...
Created a new proyect with another name, and it saved me.
Here EmployeeDetail is a table name and Employee is a model name. And
ID,Branch, Salary and UID are table fields:
public ActionResult Index()
{
List<EmployeeDetail> employees = context.EmployeeDetails.ToList();
List<Employee> emp = new List<Employee>();
foreach(EmployeeDetail item in employees)
{
emp.Add(new Employee
{
ID=Convert.ToInt32(item.ID),
Branch=item.Branch,`enter code here`
Salary=Conve`enter code here`rt.ToInt32(item.Salary),
UID = Convert.ToInt32(item.ID),
});
}
return View(emp);
}
view page code
<div style="font-family:Arial">
<h2>Index</h2>
<ul>
#foreach (var emp in Model)
{
<li>
#Html.ActionLink(emp.Branch, "Details", new { id = emp.ID });
</li>
}
</ul>
</div>

Resources