System.Data.DataException error occurred in EntityFramework.dll - visual-studio-2013

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>

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

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.

Account That Was Just Created No Longer Exists in CRM Plugin

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?

All oData Web APIs are broken after importing solution

using Dynamics CRM 2016 on premises, after importing an unmanaged solution in an organization (via the Web API Action ImportSolution and then PublishAllXml), all the Web APIs have stopped working, and return the following :
(example : https://MyDynamicsServer/MyOrganization/api/data/v8.0/contacts )
{
"Message": "Object reference not set to an instance of an object.",
"ExceptionMessage": "Object reference not set to an instance of an object.",
"ExceptionType": "System.NullReferenceException",
"StackTrace": " at Microsoft.OData.Edm.ExtensionMethods.AddAlternateKeyAnnotation(EdmModel model, IEdmEntityType type, IDictionary`2 alternateKey)\r\n at Microsoft.Crm.Extensibility.OData.CrmODataModelProvider.DeclareAlternateKeys(EdmEntityType entityType, EntityMetadata entityMetadata, EdmModel edmModel)\r\n at Microsoft.Crm.Extensibility.OData.CrmODataModelProvider.AddEntitiesToModel(ICollection`1 edmEntitySets, EdmModel model, EdmEntityContainer container)\r\n at Microsoft.Crm.Extensibility.OData.CrmODataModelProvider.AddEntities(Dictionary`2 edmModels, Dictionary`2 containers, DynamicMetadataCache cache)\r\n at Microsoft.Crm.Extensibility.OData.CrmODataModelProvider.InitializeEdmModels(DynamicMetadataCache cache)\r\n at Microsoft.Crm.Extensibility.OData.CrmODataModelProvider.GetEdmModel(ModelVisibility requestedEdmType)\r\n at Microsoft.Crm.Extensibility.OData.CrmEdmModel.get_InternalEdmModel()\r\n at Microsoft.Crm.Extensibility.OData.CrmEdmModel.get_EntityContainer()\r\n at Microsoft.OData.Edm.ExtensionMethods.FindDeclaredEntitySet(IEdmModel model, String qualifiedName)\r\n at Microsoft.OData.Edm.ExtensionMethods.FindDeclaredNavigationSource(IEdmModel model, String qualifiedName)\r\n at Microsoft.OData.Core.UriParser.Parsers.ODataPathParser.TryCreateSegmentForNavigationSource(String identifier, String parenthesisExpression)\r\n at Microsoft.OData.Core.UriParser.Parsers.ODataPathParser.CreateFirstSegment(String segmentText)\r\n at Microsoft.OData.Core.UriParser.Parsers.ODataPathParser.ParsePath(ICollection`1 segments)\r\n at Microsoft.OData.Core.UriParser.Parsers.ODataPathFactory.BindPath(ICollection`1 segments, ODataUriParserConfiguration configuration)\r\n at Microsoft.OData.Core.UriParser.ODataUriParser.Initialize()\r\n at System.Web.OData.Routing.DefaultODataPathHandler.Parse(IEdmModel model, String serviceRoot, String odataPath, ODataUriResolverSetttings resolverSettings, Boolean enableUriTemplateParsing)\r\n at System.Web.OData.Routing.DefaultODataPathHandler.Parse(IEdmModel model, String serviceRoot, String odataPath)\r\n at Microsoft.Crm.Extensibility.OData.CrmODataPathHandler.Parse(IEdmModel model, String serviceRoot, String odataPath)\r\n at System.Web.OData.Routing.ODataPathRouteConstraint.Match(HttpRequestMessage request, IHttpRoute route, String parameterName, IDictionary`2 values, HttpRouteDirection routeDirection)\r\n at System.Web.Http.Routing.HttpRoute.ProcessConstraint(HttpRequestMessage request, Object constraint, String parameterName, HttpRouteValueDictionary values, HttpRouteDirection routeDirection)\r\n at System.Web.Http.Routing.HttpRoute.ProcessConstraints(HttpRequestMessage request, HttpRouteValueDictionary values, HttpRouteDirection routeDirection)\r\n at System.Web.Http.Routing.HttpRoute.GetRouteData(String virtualPathRoot, HttpRequestMessage request)\r\n at System.Web.Http.WebHost.Routing.HttpWebRoute.GetRouteData(HttpContextBase httpContext)",
"ErrorCode": 500
}
This is critical, as it makes our customizations unusable ! (and also prevents us from importing customizations automatically, as this process uses Web API)
Note that the same solution has been imported in another organization the same way without issue ...
The import of the solution through the UI still works, but that completely defeats the point of our automation pipeline ...
Has anyone encountered this issue ? Where should I look ?
(note : I have also posted this question here : https://community.dynamics.com/crm/f/117/t/206996 )
It seems your OData is not enabled or not supported. Please check via
Settings => Customizations => Developer Resources

ServiceStack : How to catch errors before written to response

I develop a Rest Service by using ServiceStack.
My model contains a DateTime property and the problem start with it.If a client post/get wrong formatted date value as string , ServiceStack fires an exception "String was not recognized as a valid DateTime."
Stack Trace:
[FormatException: String was not recognized as a valid DateTime.]
System.DateTime.Parse(String s, IFormatProvider provider, DateTimeStyles styles) +6364458
ServiceStack.Text.Common.DeserializeBuiltin`1.<GetParseFn>b__b(String value) in C:\src\ServiceStack.Text\src\ServiceStack.Text\Common\DeserializeBuiltin.cs:58
ServiceStack.ServiceModel.Serialization.StringMapTypeDeserializer.PopulateFromMap(Object instance, IDictionary`2 keyValuePairs) in C:\src\ServiceStack\src\ServiceStack.Common\ServiceModel\Serialization\StringMapTypeDeserializer.cs:79
[SerializationException: KeyValueDataContractDeserializer: Error converting to type: String was not recognized as a valid DateTime.]
ServiceStack.ServiceModel.Serialization.StringMapTypeDeserializer.PopulateFromMap(Object instance, IDictionary`2 keyValuePairs) in C:\src\ServiceStack\src\ServiceStack.Common\ServiceModel\Serialization\StringMapTypeDeserializer.cs:95
ServiceStack.ServiceHost.RestPath.CreateRequest(String pathInfo, Dictionary`2 queryStringAndFormData, Object fromInstance) in C:\src\ServiceStack\src\ServiceStack\ServiceHost\RestPath.cs:319
ServiceStack.WebHost.Endpoints.RestHandler.GetRequest(IHttpRequest httpReq, IRestPath restPath) in C:\src\ServiceStack\src\ServiceStack\WebHost.Endpoints\RestHandler.cs:104
ServiceStack.WebHost.Endpoints.RestHandler.ProcessRequest(IHttpRequest httpReq, IHttpResponse httpRes, String operationName) in C:\src\ServiceStack\src\ServiceStack\WebHost.Endpoints\RestHandler.cs:80
System.Web.CallHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute() +625
System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously) +270
I know its an error and I know it must be catches but I want to implement it with my error codes and error descriptions(human friendly).
Any advice could be very helpful about how to catch an exception before its written to response itself on (DebeugMode=true) or the service fires an exception to client.
Thnx
Add your Custom Request Binder (or more advanced option is to implement IRequiresRequestStream on your DTOs) to by-pass ServiceStack's deserialization with your own.
More information about this is contained in ServiceStack's wiki documentation

Resources