mini-profiler nullreferenceexception - mvc-mini-profiler

When a stored procedure I'm running executes mini-profiler throws a null reference and causes my application to stop. In this instance the SP doesn't return anything.
Here is the stacktrace:
at MvcMiniProfiler.MiniProfiler.AddSqlTiming(SqlTiming stats) in C:\Users\sam\Desktop\mvc-mini-profiler\MvcMiniProfiler\MiniProfiler.cs:line 274
at MvcMiniProfiler.SqlTiming..ctor(DbCommand command, ExecuteType type, MiniProfiler profiler) in C:\Users\sam\Desktop\mvc-mini-profiler\MvcMiniProfiler\SqlTiming.cs:line 137
at MvcMiniProfiler.SqlProfiler.ExecuteStartImpl(DbCommand command, ExecuteType type) in C:\Users\sam\Desktop\mvc-mini-profiler\MvcMiniProfiler\SqlProfiler.cs:line 39
at MvcMiniProfiler.SqlProfilerExtensions.ExecuteStart(SqlProfiler sqlProfiler, DbCommand command, ExecuteType type) in C:\Users\sam\Desktop\mvc-mini-profiler\MvcMiniProfiler\SqlProfiler.cs:line 93
at MvcMiniProfiler.MiniProfiler.MvcMiniProfiler.Data.IDbProfiler.ExecuteStart(DbCommand profiledDbCommand, ExecuteType executeType) in C:\Users\sam\Desktop\mvc-mini-profiler\MvcMiniProfiler\MiniProfiler.IDbProfiler.cs:line 14
at MvcMiniProfiler.Data.ProfiledDbCommand.ExecuteDbDataReader(CommandBehavior behavior) in C:\Users\sam\Desktop\mvc-mini-profiler\MvcMiniProfiler\Data\ProfiledDbCommand.cs:line 158
at System.Data.Common.DbCommand.ExecuteReader()
at System.Data.Linq.SqlClient.SqlProvider.Execute(Expression query, QueryInfo queryInfo, IObjectReaderFactory factory, Object[] parentArgs, Object[] userArgs, ICompiledSubQuery[] subQueries, Object lastResult)
at System.Data.Linq.SqlClient.SqlProvider.ExecuteAll(Expression query, QueryInfo[] queryInfos, IObjectReaderFactory factory, Object[] userArguments, ICompiledSubQuery[] subQueries)
at System.Data.Linq.SqlClient.SqlProvider.System.Data.Linq.Provider.IProvider.Execute(Expression query)
at System.Data.Linq.DataContext.ExecuteMethodCall(Object instance, MethodInfo methodInfo, Object[] parameters)
at NetINFO.NetINFODataContext.usp_SRM_GetPlansByType(Nullable`1 sRM_ID, Nullable`1 sRM_PlanTypeID) in C:\Code\netinfo\NetInfo.Web\App_Data\NetINFO.designer.cs:line 1949
at NetINFO.NetCMG.SRM.GetSRMPlans(Int32 pPlanType) in C:\Code\netinfo\NetInfo.Web\pages\NetCMG\classes\SRM.cs:line 673
at NetINFO.NetCMG.SRM.Validate() in C:\Code\netinfo\NetInfo.Web\pages\NetCMG\classes\SRM.cs:line 540
at NetCMG.Controls.TicketErrorsCtl.ValidateTicket(SRM Ticket) in C:\Code\netinfo\NetInfo.Web\pages\NetCMG\Controls\TicketErrorsCtl.ascx.cs:line 29
at NetCMG.Controls.TicketErrorsCtl.Page_Load(Object sender, EventArgs e) in C:\Code\netinfo\NetInfo.Web\pages\NetCMG\Controls\TicketErrorsCtl.ascx.cs:line 16
at System.Web.Util.CalliHelper.EventArgFunctionCaller(IntPtr fp, Object o, Object t, EventArgs e)
at System.Web.Util.CalliEventHandlerDelegateProxy.Callback(Object sender, EventArgs e)
at System.Web.UI.Control.OnLoad(EventArgs e)
at System.Web.UI.Control.LoadRecursive()
at System.Web.UI.Control.LoadRecursive()
at System.Web.UI.Control.LoadRecursive()
at System.Web.UI.Control.LoadRecursive()
at System.Web.UI.Control.LoadRecursive()
at System.Web.UI.Control.LoadRecursive()
at System.Web.UI.Control.LoadRecursive()
at System.Web.UI.Control.LoadRecursive()
at System.Web.UI.Control.LoadRecursive()
at System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint)

I finally figured out the solution to my question above. The error was happening on a legacy webforms application that was using sql data source for the grid. The sql datasource was using the 'ProviderName' property. Once I removed this property everything started working.

Had the same problem: NRE from application start. Exception occures at MvcMiniProfiler.MiniProfiler.AddSqlTiming(SqlTiming stats)
Problem reason: database call in Application_AuthenticateRequest()
Problem solution: MiniProfiler.Start(); moved to the end of Application_AuthenticateRequest() method.

Related

Dynamics CRM 2013 throws SQL Timeout adding a user to a team

I have a simple but tough problem.
I am trying to add an user to a team through user interface, however I'm getting SQL Time Out for some users.
I got no plugins firing on association request. I also did not find any familiarity between the ones I am getting this error.
I have even turned the trace log on which did not give me much more details.
Following the error log generated by tracing tool.
Web Service Plug-in failed in SdkMessageProcessingStepId: {D3DE2F15-53FA-4A12-A286-346CC4BFD310}; EntityName: none; Stage: 30; MessageName: Associate; AssemblyName: Microsoft.Crm.Extensibility.InternalOperationPlugin, Microsoft.Crm.ObjectModel, Version=6.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35; ClassName: Microsoft.Crm.Extensibility.InternalOperationPlugin; Exception: Unhandled Exception: System.Reflection.TargetInvocationException: Exception has been thrown by the target of an invocation.
at System.RuntimeMethodHandle.InvokeMethod(Object target, Object[] arguments, Signature sig, Boolean constructor)
at System.Reflection.RuntimeMethodInfo.UnsafeInvokeInternal(Object obj, Object[] parameters, Object[] arguments)
at System.Reflection.RuntimeMethodInfo.Invoke(Object obj, BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture)
at System.Web.Services.Protocols.LogicalMethodInfo.Invoke(Object target, Object[] values)
at Microsoft.Crm.Extensibility.InternalOperationPlugin.Execute(IServiceProvider serviceProvider)
at Microsoft.Crm.Extensibility.V5PluginProxyStep.ExecuteInternal(PipelineExecutionContext context)
at Microsoft.Crm.Extensibility.VersionedPluginProxyStepBase.Execute(PipelineExecutionContext context)
Inner Exception: Microsoft.Crm.CrmException: SQL timeout expired.
at Microsoft.Crm.Extensibility.VersionedPluginProxyStepBase.Execute(PipelineExecutionContext context)
at Microsoft.Crm.Extensibility.Pipeline.Execute(PipelineExecutionContext context)
at Microsoft.Crm.Extensibility.MessageProcessor.Execute(PipelineExecutionContext context)
at Microsoft.Crm.Extensibility.InternalMessageDispatcher.Execute(PipelineExecutionContext context)
at Microsoft.Crm.Extensibility.ManyToManyForwardEntityAssociationCommand.AssociateEntities(EntityReference entity1, EntityReference entity2, String relationshipName, Boolean associate, ExecutionContext context)
at Microsoft.Crm.Extensibility.ManyToManyForwardEntityAssociationCommand.Execute(RelationshipProcessor processor, EntityMetadata entityMetadata, Guid entityId, EntityReferenceCollection relatedEntities, Boolean associate, ExecutionContext context)
at Microsoft.Crm.Extensibility.RelationshipProcessor.ProcessAssociation(EntityMetadata entityMetadata, Guid entityId, Relationship relationship, EntityReferenceCollection relatedEntities, Boolean associate, ExecutionContext context)
at Microsoft.Crm.Extensibility.RelationshipProcessor.Associate(EntityReference entityReference, Relationship relationship, EntityReferenceCollection relatedEntities, ExecutionContext context)
Inner Exception: Microsoft.Crm.CrmException: SQL timeout expired.
Inner Exception: System.Data.SqlClient.SqlException: Timeout expired. The timeout period elapsed prior to completion of the operation or the server is not responding.
at System.Data.SqlClient.SqlConnection.OnError(SqlException exception, Boolean breakConnection, Action`1 wrapCloseInAction)
at System.Data.SqlClient.TdsParser.ThrowExceptionAndWarning(TdsParserStateObject stateObj, Boolean callerHasConnectionLock, Boolean asyncClose)
at System.Data.SqlClient.TdsParser.TryRun(RunBehavior runBehavior, SqlCommand cmdHandler, SqlDataReader dataStream, BulkCopySimpleResultSet bulkCopyHandler, TdsParserStateObject stateObj, Boolean& dataReady)
at System.Data.SqlClient.SqlCommand.FinishExecuteReader(SqlDataReader ds, RunBehavior runBehavior, String resetOptionsString)
at System.Data.SqlClient.SqlCommand.RunExecuteReaderTds(CommandBehavior cmdBehavior, RunBehavior runBehavior, Boolean returnStream, Boolean async, Int32 timeout, Task& task, Boolean asyncWrite, SqlDataReader ds)
at System.Data.SqlClient.SqlCommand.RunExecuteReader(CommandBehavior cmdBehavior, RunBehavior runBehavior, Boolean returnStream, String method, TaskCompletionSource`1 completion, Int32 timeout, Task& task, Boolean asyncWrite)
at System.Data.SqlClient.SqlCommand.InternalExecuteNonQuery(TaskCompletionSource`1 completion, String methodName, Boolean sendToPipe, Int32 timeout, Boolean asyncWrite)
at System.Data.SqlClient.SqlCommand.ExecuteNonQuery()
at Microsoft.Crm.ObjectModel.BusinessManagementUtility.LockSystemUserEntriesForTeamMembershipChange(Guid userId, ExecutionContext context)
at Microsoft.Crm.ObjectModel.TeamMembershipServiceInternal`1.Associate(BusinessEntityMoniker entityOneMoniker, BusinessEntityMoniker entityTwoMoniker, String associationRelationshipName, ExecutionContext context)
at Microsoft.Crm.BusinessEntities.BusinessProcessObject.HandleAssociationOperation(BusinessEntityMoniker entityOneMoniker, BusinessEntityMoniker entityTwoMoniker, String associationRelationshipName, Boolean createAssociation, ExecutionContext context)
at Microsoft.Crm.BusinessEntities.BusinessProcessObject.AssociateEntities(BusinessEntityMoniker entityOneMoniker, BusinessEntityMoniker entityTwoMoniker, String associationRelationshipName, ExecutionContext context)
Inner Exception: System.ComponentModel.Win32Exception: The wait operation timed out

Entity Framework Timeout Expired

I recently publish my ASP.Net MVC 3 web application (Entity Framework 4.1 for Data Persistence) to a live server. The application is located on one web server and the database (SQL Server 2008) is located on another separate server.
The site has only been live a few days with very few hits, and because of this there are very few records contained within the database tables (10- 20 max).
I also have ELMAH (Error Logging Modules and Handlers for ASP.NET) integrated into the site and I have received a few instances of the following error already
System.Data.SqlClient.SqlException: Timeout expired. The timeout
period elapsed prior to completion of the operation or the server is
not responding.
Below shows the full details as supplied by ELMAH
System.Data.EntityException: The underlying provider failed on Open.
---> System.Data.SqlClient.SqlException: Timeout expired. The timeout period elapsed prior to completion of the operation or the server is
not responding. at
System.Data.SqlClient.SqlInternalConnection.OnError(SqlException
exception, Boolean breakConnection) at
System.Data.SqlClient.TdsParser.ThrowExceptionAndWarning() at
System.Data.SqlClient.TdsParserStateObject.ReadSniError(TdsParserStateObject
stateObj, UInt32 error) at
System.Data.SqlClient.TdsParserStateObject.ReadSni(DbAsyncResult
asyncResult, TdsParserStateObject stateObj) at
System.Data.SqlClient.TdsParserStateObject.ReadNetworkPacket() at
System.Data.SqlClient.TdsParser.ConsumePreLoginHandshake(Boolean
encrypt, Boolean trustServerCert, Boolean& marsCapable) at
System.Data.SqlClient.TdsParser.Connect(ServerInfo serverInfo,
SqlInternalConnectionTds connHandler, Boolean ignoreSniOpenTimeout,
Int64 timerExpire, Boolean encrypt, Boolean trustServerCert, Boolean
integratedSecurity) at
System.Data.SqlClient.SqlInternalConnectionTds.AttemptOneLogin(ServerInfo
serverInfo, String newPassword, Boolean ignoreSniOpenTimeout,
TimeoutTimer timeout, SqlConnection owningObject) at
System.Data.SqlClient.SqlInternalConnectionTds.LoginWithFailover(Boolean
useFailoverHost, ServerInfo primaryServerInfo, String failoverHost,
String newPassword, Boolean redirectedUserInstance, SqlConnection
owningObject, SqlConnectionString connectionOptions, TimeoutTimer
timeout) at
System.Data.SqlClient.SqlInternalConnectionTds.OpenLoginEnlist(SqlConnection
owningObject, TimeoutTimer timeout, SqlConnectionString
connectionOptions, String newPassword, Boolean redirectedUserInstance)
at
System.Data.SqlClient.SqlInternalConnectionTds..ctor(DbConnectionPoolIdentity
identity, SqlConnectionString connectionOptions, Object providerInfo,
String newPassword, SqlConnection owningObject, Boolean
redirectedUserInstance) at
System.Data.SqlClient.SqlConnectionFactory.CreateConnection(DbConnectionOptions
options, Object poolGroupProviderInfo, DbConnectionPool pool,
DbConnection owningConnection) at
System.Data.ProviderBase.DbConnectionFactory.CreatePooledConnection(DbConnection
owningConnection, DbConnectionPool pool, DbConnectionOptions options)
at System.Data.ProviderBase.DbConnectionPool.CreateObject(DbConnection
owningObject) at
System.Data.ProviderBase.DbConnectionPool.UserCreateRequest(DbConnection
owningObject) at
System.Data.ProviderBase.DbConnectionPool.GetConnection(DbConnection
owningObject) at
System.Data.ProviderBase.DbConnectionFactory.GetConnection(DbConnection
owningConnection) at
System.Data.ProviderBase.DbConnectionClosed.OpenConnection(DbConnection
outerConnection, DbConnectionFactory connectionFactory) at
System.Data.SqlClient.SqlConnection.Open() at
System.Data.EntityClient.EntityConnection.OpenStoreConnectionIf(Boolean
openCondition, DbConnection storeConnectionToOpen, DbConnection
originalConnection, String exceptionCode, String attemptedOperation,
Boolean& closeStoreConnectionOnFailure) --- End of inner exception
stack trace --- at
System.Data.EntityClient.EntityConnection.OpenStoreConnectionIf(Boolean
openCondition, DbConnection storeConnectionToOpen, DbConnection
originalConnection, String exceptionCode, String attemptedOperation,
Boolean& closeStoreConnectionOnFailure) at
System.Data.EntityClient.EntityConnection.Open() at
System.Data.Objects.ObjectContext.EnsureConnection() at
System.Data.Objects.ObjectQuery1.GetResults(Nullable1
forMergeOption) at
System.Data.Objects.ObjectQuery1.System.Collections.Generic.IEnumerable<T>.GetEnumerator()
at System.Collections.Generic.List1..ctor(IEnumerable1 collection)
at System.Linq.Enumerable.ToList[TSource](IEnumerable1 source)
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.ControllerActionInvoker.<>c_DisplayClass15.b_12()
at
System.Web.Mvc.ControllerActionInvoker.InvokeActionMethodFilter(IActionFilter
filter, ActionExecutingContext preContext, Func1 continuation) at
System.Web.Mvc.ControllerActionInvoker.InvokeActionMethodWithFilters(ControllerContext
controllerContext, IList1 filters, ActionDescriptor actionDescriptor,
IDictionary`2 parameters) at
System.Web.Mvc.ControllerActionInvoker.InvokeAction(ControllerContext
controllerContext, String actionName)
The occasions where this error has happened have been due to SELECT queries. These select queries are very simple, ie,
Select col1, col2, col3 from table where col1 = 1
And as I have stated, there is very little data within the database, so it isn’t as if the queries are pulling back 100’s of records.
I have done some research into this using both the Internet and Stackoverflow. Some people suggest to increase the dbContext CommandTimeout Property, however, I don’t understand why I should need to do this. Yes, if I were pulling back loads of records, but as I have said, these are simple SELECT statements pulling back 1-5 records at the most.
I also know that developers need to keep an eye on the SQL generated by the Entity Framework, so, I downloaded and ran this trial version http://www.datawizard.com in order to get a look at the SQL being created for the Entity Framework SELECT queries that were causing a problem. Again, the profiler showed these queries to be very simple syntax, so I don’t think that is the problem.
I am beginning to think maybe it has something to do with my database and web application being on separate servers, however, I am out of ideas!
Please if anyone can help or advise me with this issue, it would be greatly appreciated.
Thanks everyone.

NuGet Gallery and EntityFramework throws Failed to open provider error

We have a weird situation going on here. We have setup a local installation of NuGet gallery (the same code that powers http://Nuget.org). The IIS and the DB are on the same box. The IIS App pool has been configured to run under a domain user who is the local admin on the box as well and has the "right to logon as a service" rights. Now when someone (after succesfully logging in) tries and upload a package, the upload package business takes ages and eventually throws up the "The underlying provider failed to open" error
[TimeoutException: Transaction Timeout]
[TransactionException: The operation is not valid for the state of the transaction.]
System.Transactions.TransactionState.EnlistPromotableSinglePhase(InternalTransaction tx, IPromotableSinglePhaseNotification promotableSinglePhaseNotification, Transaction atomicTransaction) +53
System.Transactions.Transaction.EnlistPromotableSinglePhase(IPromotableSinglePhaseNotification promotableSinglePhaseNotification) +241
System.Data.SqlClient.SqlInternalConnection.EnlistNonNull(Transaction tx) +273
System.Data.ProviderBase.DbConnectionInternal.ActivateConnection(Transaction transaction) +150
System.Data.ProviderBase.DbConnectionPool.GetConnection(DbConnection owningObject) +2647
System.Data.ProviderBase.DbConnectionFactory.GetConnection(DbConnection owningConnection) +89
System.Data.ProviderBase.DbConnectionClosed.OpenConnection(DbConnection outerConnection, DbConnectionFactory connectionFactory) +6372062
System.Data.SqlClient.SqlConnection.Open() +300
System.Data.EntityClient.EntityConnection.OpenStoreConnectionIf(Boolean openCondition, DbConnection storeConnectionToOpen, DbConnection originalConnection, String exceptionCode, String attemptedOperation, Boolean& closeStoreConnectionOnFailure) +67
[EntityException: The underlying provider failed on Open.]
System.Data.EntityClient.EntityConnection.OpenStoreConnectionIf(Boolean openCondition, DbConnection storeConnectionToOpen, DbConnection originalConnection, String exceptionCode, String attemptedOperation, Boolean& closeStoreConnectionOnFailure) +11109230
System.Data.EntityClient.EntityConnection.Open() +142
System.Data.Objects.ObjectContext.EnsureConnection() +97
System.Data.Objects.ObjectContext.ExecuteStoreQueryInternal(String commandText, String entitySetName, MergeOption mergeOption, Object[] parameters) +109
System.Data.Objects.ObjectContext.ExecuteStoreQuery(String commandText, Object[] parameters) +87
System.Data.Entity.Internal.InternalContext.ExecuteSqlQuery(String sql, Object[] parameters) +118
System.Data.Entity.Internal.InternalContext.ExecuteSqlQueryAsIEnumerable(String sql, Object[] parameters) +85
System.Data.Entity.Internal.InternalContext.ExecuteSqlQuery(Type elementType, String sql, Object[] parameters) +241
System.Data.Entity.Internal.InternalSqlNonSetQuery.GetEnumerator() +34
System.Data.Entity.Internal.InternalSqlQuery`1.GetEnumerator() +28
System.Collections.Generic.List`1..ctor(IEnumerable`1 collection) +382
System.Linq.Enumerable.ToList(IEnumerable`1 source) +80
NuGetGallery.LuceneIndexingService.GetPackages(DbContext context, Nullable`1 dateTime) in C:\Source\DotNetDevEng.CitiNuGet\Gallery\DEV\Website\Infrastructure\Lucene\LuceneIndexingService.cs:55
NuGetGallery.LuceneIndexingService.UpdateIndex() in C:\Source\DotNetDevEng.CitiNuGet\Gallery\DEV\Website\Infrastructure\Lucene\LuceneIndexingService.cs:32
NuGetGallery.PackageService.CreatePackage(IPackage nugetPackage, User currentUser) in C:\Source\DotNetDevEng.CitiNuGet\Gallery\DEV\Website\Services\PackageService.cs:61
NuGetGallery.PackagesController.VerifyPackage(Nullable`1 listed) in C:\Source\DotNetDevEng.CitiNuGet\Gallery\DEV\Website\Controllers\PackagesController.cs:503
lambda_method(Closure , ControllerBase , Object[] ) +121
System.Web.Mvc.ReflectedActionDescriptor.Execute(ControllerContext controllerContext, IDictionary`2 parameters) +248
System.Web.Mvc.ControllerActionInvoker.InvokeActionMethod(ControllerContext controllerContext, ActionDescriptor actionDescriptor, IDictionary`2 parameters) +39
System.Web.Mvc.<>c__DisplayClass15.<InvokeActionMethodWithFilters>b__12() +125
System.Web.Mvc.ControllerActionInvoker.InvokeActionMethodFilter(IActionFilter filter, ActionExecutingContext preContext, Func`1 continuation) +640
System.Web.Mvc.ControllerActionInvoker.InvokeActionMethodFilter(IActionFilter filter, ActionExecutingContext preContext, Func`1 continuation) +640
System.Web.Mvc.ControllerActionInvoker.InvokeActionMethodWithFilters(ControllerContext controllerContext, IList`1 filters, ActionDescriptor actionDescriptor, IDictionary`2 parameters) +312
System.Web.Mvc.ControllerActionInvoker.InvokeAction(ControllerContext controllerContext, String actionName) +691
System.Web.Mvc.Controller.ExecuteCore() +162
System.Web.Mvc.ControllerBase.Execute(RequestContext requestContext) +305
System.Web.Mvc.<>c__DisplayClassb.<BeginProcessRequest>b__5() +62
System.Web.Mvc.Async.<>c__DisplayClass1.<MakeVoidDelegate>b__0() +20
System.Web.CallHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute() +469
System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously) +375
Interestingly if I switch IIS App Pool to run under the built in "LocalSystem" account all these problems goes away. The domain user we want to use has been temporarily setup as the database owner for NuGetGallery database but it isn't helping.
Can anyone suggest what setting/configuration we might be missing here?
This was due to ambient transactions going on within the code. The code relied on TransactionScope classes to manage various transactions which were getting in a jam when they got nested. Things turned particularly bad if someone tried uploading a package which was more than around 10MB in size. Once we tweaked the MSDTC on the boxes the application started behaving slightly properly. However it was still intermittently getting deadlocked within its own transactions so for now we have decided to remove transactions from the package upload bit.
For anyone else who gets into this problem I would recommend either of these two
Comment out any reference to TransactionScope in
Services\PackageService.cs (method CreatePackage, line 48)
using (var tx = new TransactionScope())
{
using (var stream = nugetPackage.GetStream())
{
UpdateIsLatest(packageRegistration);
packageRegistrationRepo.CommitChanges();
packageFileSvc.SavePackageFile(package, stream);
tx.Complete();
}
}
And in Controller\PackageController.cs method VerifyPackage(bool? Listed) line 501
using (var tx = new TransactionScope())
{
package = packageSvc.CreatePackage(nugetPackage, currentUser);
packageSvc.PublishPackage(package.PackageRegistration.Id, package.Version);
if (listed.HasValue && listed.Value == false)
packageSvc.MarkPackageUnlisted(package);
uploadFileSvc.DeleteUploadFile(currentUser.Key);
tx.Complete();
}
2 Uncomment those lines and follow the approach mentioned here http://blogs.msdn.com/b/dbrowne/archive/2010/05/21/using-new-transactionscope-considered-harmful.aspx
Basically create a transactionscope which can work well with SQL Server. Create a new class in the InfraStructureFolder, call it TranscationUtils and copy the code in there. Then the using blocks would look like
using (var tx = new TransactionUtils.CreateTransactionScope()){
//cod here
tx.Complete();
}
However this second approach can result in another server error which again relates to the default time outs you can specify for TransactionScope. We have personally decided to go with approach 1 and comment out all TransactionScope references for now.

Microsoft Dynamics 2011 N:N LINQ query with where clause containing Guid

I have constructed a simple query to return a Users Team membership (N: N relationship). This works fine for all users, however, when I add a where clause to restrict to a specific user it throws a fault exception (see stack trace below).
Strangely this works fine with "where Users.FullName.StartsWith("Alex")". Does the Dynamics CRM SDK LINQ implementation not support Guides in where clauses?
Any advice?
Example code
using (var service = new OrganizationService("Xrm"))
{
using (var xrm = new XrmServiceContext(service))
{
var AlexUser = xrm.SystemUserSet.Where(p => p.FullName.StartsWith("Alex")).First();
var AlexID = AlexUser.Id;
var Test =
from Users in xrm.SystemUserSet
join TeamMemberships in xrm.TeamMembershipSet on Users.Id equals TeamMemberships.SystemUserId
join Teams in xrm.TeamSet on TeamMemberships.TeamId equals Teams.Id
where Users.Id == AlexID // <-- problematic where clause
orderby Users.FullName
select new
{
FullName = Users.FullName,
UserID = Users.Id,
TeamName = Teams.Name
};
var Test1 = Test.ToList();
}
}
Stacktrace:
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.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.Client.Services.OrganizationService.<>c__DisplayClass19.b__18(IOrganizationService
s) at
Microsoft.Xrm.Client.Services.OrganizationService.InnerOrganizationService.UsingService[TResult](Func2 action) at Microsoft.Xrm.Client.Services.OrganizationService.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, List1 linkLookups,
String& pagingCookie, Boolean& moreRecords) at
Microsoft.Xrm.Sdk.Linq.QueryProvider.Execute[TElement](QueryExpression
qe, Boolean throwIfSequenceIsEmpty, Boolean throwIfSequenceNotSingle,
Projection projection, NavigationSource source, List1 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.Query1.GetEnumerator() at
System.Collections.Generic.List1..ctor(IEnumerable1 collection)
at System.Linq.Enumerable.ToList[TSource](IEnumerable`1 source) at
aspirets.crm.test.Program.Main(String[] args) in
C:\Users\a_marshall\documents\visual studio
2010\Projects\aspirets.crm\aspirets.crm.test\Program.cs:line 37 at
System.AppDomain._nExecuteAssembly(RuntimeAssembly assembly, String[]
args) at System.AppDomain.ExecuteAssembly(String assemblyFile,
Evidence assemblySecurity, String[] args) at
Microsoft.VisualStudio.HostingProcess.HostProc.RunUsersAssembly()
at System.Threading.ThreadHelper.ThreadStart_Context(Object state)
at System.Threading.ExecutionContext.Run(ExecutionContext
executionContext, ContextCallback callback, Object state, Boolean
ignoreSyncCtx) at
System.Threading.ExecutionContext.Run(ExecutionContext
executionContext, ContextCallback callback, Object state) at
System.Threading.ThreadHelper.ThreadStart()
Instead of Users.Id, try Users.SystemUserId. Similarly, instead of Teams.Id, try Teams.TeamId.
As for the reason why this works, I'm not aware of any documentation that states this, but because entities in the generated early-binding file inherit from Entity, they necessarily have an Id property. However, because the early-bound OrganizationServiceContext maps entity attributes directly to the CRM database, the tables of which don't contain an Id column, using the Id attribute with the LINQ provider won't work, so you'd have to use the actual database/schema names.

Dynamics CRM error: "The object cannot be updated because it is read-only"

I've got an instance of Dynamics CRM 4.0 with some weird errors. If I close a Case and then try to reactivate it I get the error "The object cannot be updated because it is read-only". This is simple, built-in CRM functionality that works fine on other instances. I get the same error if I try to convert a Quote to an Order - I believe it's trying to update the Quote, which has been "closed" by then. What's wrong and how do I fix it?
MSCRM Error Report:
--------------------------------------------------------------------------------------------------------
Error: Exception of type 'System.Web.HttpUnhandledException' was thrown.
Error Number: 0x8004022E
Error Message: The object cannot be updated because it is read-only.
Error Details: The object cannot be updated because it is read-only.
Source File: Not available
Line Number: Not available
Request URL: http://jupiter:5555/EN/cs/cases/edit.aspx?id={C75704E2-3B82-DE11-BFAD-00188B2CB446}
Stack Trace Info: [CrmException: The object cannot be updated because it is read-only.]
at Microsoft.Crm.ObjectModel.IncidentService.Update(IBusinessEntity incident, ExecutionContext context)
[TargetInvocationException: Exception has been thrown by the target of an invocation.]
at System.RuntimeMethodHandle._InvokeMethodFast(Object target, Object[] arguments, SignatureStruct& sig, MethodAttributes methodAttributes, RuntimeTypeHandle typeOwner)
at System.RuntimeMethodHandle.InvokeMethodFast(Object target, Object[] arguments, Signature sig, MethodAttributes methodAttributes, RuntimeTypeHandle typeOwner)
at System.Reflection.RuntimeMethodInfo.Invoke(Object obj, BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture, Boolean skipVisibilityChecks)
at System.Reflection.RuntimeMethodInfo.Invoke(Object obj, BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture)
at System.Web.Services.Protocols.LogicalMethodInfo.Invoke(Object target, Object[] values)
at Microsoft.Crm.Extensibility.InternalOperationPlugin.Execute(IPluginExecutionContext context)
at Microsoft.Crm.Extensibility.PluginStep.Execute(PipelineExecutionContext context)
at Microsoft.Crm.Extensibility.Pipeline.Execute(PipelineExecutionContext context)
at Microsoft.Crm.Extensibility.MessageProcessor.Execute(PipelineExecutionContext context)
at Microsoft.Crm.Extensibility.InternalMessageDispatcher.Execute(PipelineExecutionContext context)
at Microsoft.Crm.Extensibility.ExternalMessageDispatcher.Execute(String messageName, Int32 primaryObjectTypeCode, Int32 secondaryObjectTypeCode, PropertyBag fields, CorrelationToken correlationToken, CallerOriginToken originToken, UserAuth userAuth, Guid callerId)
at Microsoft.Crm.Sdk.RequestBase.Process(Int32 primaryObjectTypeCode, Int32 secondaryObjectTypeCode, CorrelationToken correlationToken, CallerOriginToken originToken, UserAuth userAuth, Guid callerId)
at Microsoft.Crm.Sdk.RequestBase.Process(CorrelationToken correlationToken, CallerOriginToken originToken, UserAuth userAuth, Guid callerId)
at Microsoft.Crm.Sdk.CrmServiceInternal.Execute(RequestBase request, CorrelationToken correlationToken, CallerOriginToken originToken, UserAuth userAuth, Guid callerId)
at Microsoft.Crm.Sdk.InProcessCrmService.Execute(Object request)
at Microsoft.Crm.Application.Platform.ServiceCommands.PlatformCommand.ExecuteInternal()
at Microsoft.Crm.Application.Platform.ServiceCommands.UpdateCommand.Execute()
at Microsoft.Crm.Application.Platform.EntityProxy.Update(Boolean performDuplicateCheck)
at Microsoft.Crm.Application.Platform.EntityProxy.Update()
at Microsoft.Crm.Web.CS.CaseDetailPage.Open(Object sender, DataEventArgs e)
at Microsoft.Crm.Application.Forms.DataEventProcessor.Raise(FormEventId eventId, FormState state, IUser user, String objectId, Entity entity)
at Microsoft.Crm.Application.Forms.AppForm.RaiseDataEvent(FormEventId eventId)
at Microsoft.Crm.Application.Forms.EndUserForm.Initialize(Entity entity)
at Microsoft.Crm.Application.Forms.CustomizableForm.Execute(Entity entity, String formType)
at Microsoft.Crm.Application.Forms.CustomizableForm.Execute(Entity entity)
at Microsoft.Crm.Web.CS.CaseDetailPage.ConfigureForm()
at Microsoft.Crm.Application.Controls.AppUIPage.OnPreRender(EventArgs e)
at System.Web.UI.Control.PreRenderRecursiveInternal()
at System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint)
[HttpUnhandledException: Exception of type 'System.Web.HttpUnhandledException' was thrown.]
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.ProcessRequestWithNoAssert(HttpContext context)
at System.Web.UI.Page.ProcessRequest(HttpContext context)
at ASP.en_cs_cases_edit_aspx.ProcessRequest(HttpContext context)
at System.Web.HttpApplication.CallHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute()
at System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously)
Try disabling your onload and onsave code to see if that is causing any problems. To quickly and temporarily disable the events, open the dialog box where you paste in your onload/onsave code and uncheck 'Event is enabled'. Then save the form and publish the entity. Does the error still occur?

Resources