nhibernate CurrentSessionContext.Hasbind giving object reference not set - c#-4.0

Hi i m using WebApi Mvc4 framework .net 4.0
I create a sessionFactory as follows:
public void ConfigureNHibernate(IKernel container)
{
var sessionFactory = FluentNHibernate
.Cfg.Fluently.Configure()
.Database(
MsSqlConfiguration.MsSql2008.ConnectionString(
c => c.FromConnectionStringWithKey("ApikeysDb")))
.CurrentSessionContext("web")
.Mappings(m => m.FluentMappings.AddFromAssemblyOf<CTP.ApiNext.Data.SqlServer.SqlCommandFactory>())
.BuildSessionFactory();
// Add the ISessionFactory instance to the container
container.Bind<ISessionFactory>().ToConstant(sessionFactory);
// Configure a resolver method to be used for creating ISession objects
container.Bind<ISession>().ToMethod(CreateSession);
container.Bind<ICurrentSessionContextAdapter>().To<CurrentSessionContextAdapter>();
}
and below when I am binding my ISession object to the HTTP context, I am getting error "Object reference not set"
public ISession CreateSession(IContext context)
{
var sessionFactory = context.Kernel.Get<ISessionFactory>();
if (!CurrentSessionContext.HasBind(sessionFactory))
{
// Open new ISession and bind it to the current session context
var session = sessionFactory.OpenSession();
CurrentSessionContext.Bind(session);
}
return sessionFactory.GetCurrentSession();
}
The error is at at line: CurrentSessionContext.HasBind(sessionFactory)
The error details are:
[NullReferenceException: Object reference not set to an instance of an object.]
lambda_method(Closure , Object ) +73
NHibernate.Context.ReflectiveHttpContext.get_HttpContextCurrentItems() +84
NHibernate.Context.WebSessionContext.GetMap() +52
NHibernate.Context.MapBasedSessionContext.get_Session() +70
NHibernate.Context.CurrentSessionContext.HasBind(ISessionFactory factory) +71
CTP.ApiNext.Web.Api.App_Start.NinjectConfigurator.CreateSession(IContext context) in C:\Projects\UNILEVER\WHITELABEL\_api-next\ctp-api-next\src\CTP.ApiNext.Web.Api\App_Start\NinjectConfigurator.cs:91
Ninject.Activation.Providers.CallbackProvider`1.CreateInstance(IContext context) in c:\Projects\Ninject\ninject\src\Ninject\Activation\Providers\CallbackProvider.cs:45
Ninject.Activation.Provider`1.Create(IContext context) in c:\Projects\Ninject\ninject\src\Ninject\Activation\Provider.cs:38
Ninject.Activation.Context.Resolve() in c:\Projects\Ninject\ninject\src\Ninject\Activation\Context.cs:157
Ninject.<>c__DisplayClass10.<Resolve>b__c(IBinding binding) in c:\Projects\Ninject\ninject\src\Ninject\KernelBase.cs:386
System.Linq.WhereSelectEnumerableIterator`2.MoveNext() +145
System.Linq.Enumerable.SingleOrDefault(IEnumerable`1 source) +4077101
Ninject.Planning.Targets.Target`1.GetValue(Type service, IContext parent) in c:\Projects\Ninject\ninject\src\Ninject\Planning\Targets\Target.cs:197
Ninject.Planning.Targets.Target`1.ResolveWithin(IContext parent) in c:\Projects\Ninject\ninject\src\Ninject\Planning\Targets\Target.cs:165
Ninject.Activation.Providers.StandardProvider.GetValue(IContext context, ITarget target) in c:\Projects\Ninject\ninject\src\Ninject\Activation\Providers\StandardProvider.cs:114
Ninject.Activation.Providers.<>c__DisplayClass4.<Create>b__2(ITarget target) in c:\Projects\Ninject\ninject\src\Ninject\Activation\Providers\StandardProvider.cs:96
System.Linq.WhereSelectArrayIterator`2.MoveNext() +66
System.Linq.Buffer`1..ctor(IEnumerable`1 source) +216
System.Linq.Enumerable.ToArray(IEnumerable`1 source) +77
Ninject.Activation.Providers.StandardProvider.Create(IContext context) in c:\Projects\Ninject\ninject\src\Ninject\Activation\Providers\StandardProvider.cs:96
Ninject.Activation.Context.Resolve() in c:\Projects\Ninject\ninject\src\Ninject\Activation\Context.cs:157
Ninject.<>c__DisplayClass10.<Resolve>b__c(IBinding binding) in c:\Projects\Ninject\ninject\src\Ninject\KernelBase.cs:386
System.Linq.WhereSelectEnumerableIterator`2.MoveNext() +145
System.Linq.Enumerable.SingleOrDefault(IEnumerable`1 source) +4077101
Ninject.Planning.Targets.Target`1.GetValue(Type service, IContext parent) in c:\Projects\Ninject\ninject\src\Ninject\Planning\Targets\Target.cs:197
Ninject.Planning.Targets.Target`1.ResolveWithin(IContext parent) in c:\Projects\Ninject\ninject\src\Ninject\Planning\Targets\Target.cs:165
Ninject.Activation.Providers.StandardProvider.GetValue(IContext context, ITarget target) in c:\Projects\Ninject\ninject\src\Ninject\Activation\Providers\StandardProvider.cs:114
Ninject.Activation.Providers.<>c__DisplayClass4.<Create>b__2(ITarget target) in c:\Projects\Ninject\ninject\src\Ninject\Activation\Providers\StandardProvider.cs:96
System.Linq.WhereSelectArrayIterator`2.MoveNext() +66
System.Linq.Buffer`1..ctor(IEnumerable`1 source) +216
System.Linq.Enumerable.ToArray(IEnumerable`1 source) +77
Ninject.Activation.Providers.StandardProvider.Create(IContext context) in c:\Projects\Ninject\ninject\src\Ninject\Activation\Providers\StandardProvider.cs:96
Ninject.Activation.Context.Resolve() in c:\Projects\Ninject\ninject\src\Ninject\Activation\Context.cs:157
Ninject.<>c__DisplayClass10.<Resolve>b__c(IBinding binding) in c:\Projects\Ninject\ninject\src\Ninject\KernelBase.cs:386
System.Linq.WhereSelectEnumerableIterator`2.MoveNext() +145
System.Linq.<CastIterator>d__b1`1.MoveNext() +85
System.Linq.Enumerable.Single(IEnumerable`1 source) +191
Ninject.ResolutionExtensions.Get(IResolutionRoot root, IParameter[] parameters) in c:\Projects\Ninject\ninject\src\Ninject\Syntax\ResolutionExtensions.cs:37
CTP.ApiNext.Web.Api.App_Start.NinjectWebCommon.RegisterServices(IKernel kernel) in C:\Projects\UNILEVER\WHITELABEL\_api-next\ctp-api-next\src\CTP.ApiNext.Web.Api\App_Start\NinjectWebCommon.cs:61
CTP.ApiNext.Web.Api.App_Start.NinjectWebCommon.CreateKernel() in C:\Projects\UNILEVER\WHITELABEL\_api-next\ctp-api-next\src\CTP.ApiNext.Web.Api\App_Start\NinjectWebCommon.cs:48
Ninject.Web.Common.Bootstrapper.Initialize(Func`1 createKernelCallback) in c:\Projects\Ninject\Ninject.Web.Common\src\Ninject.Web.Common\Bootstrapper.cs:50
CTP.ApiNext.Web.Api.App_Start.NinjectWebCommon.Start() in C:\Projects\UNILEVER\WHITELABEL\_api-next\ctp-api-next\src\CTP.ApiNext.Web.Api\App_Start\NinjectWebCommon.cs:27
[TargetInvocationException: Exception has been thrown by the target of an invocation.]
System.RuntimeMethodHandle.InvokeMethod(Object target, Object[] arguments, Signature sig, Boolean constructor) +0
System.Reflection.RuntimeMethodInfo.UnsafeInvokeInternal(Object obj, Object[] parameters, Object[] arguments) +192
System.Reflection.RuntimeMethodInfo.Invoke(Object obj, BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture) +108
System.Reflection.MethodBase.Invoke(Object obj, Object[] parameters) +19
WebActivator.BaseActivationMethodAttribute.InvokeMethod() +236
WebActivator.ActivationManager.RunActivationMethods() +534
WebActivator.ActivationManager.RunPreStartMethods() +41
WebActivator.ActivationManager.Run() +64
[InvalidOperationException: The pre-application start initialization method Run on type WebActivator.ActivationManager threw an exception with the following error message: Exception has been thrown by the target of an invocation..]
System.Web.Compilation.BuildManager.InvokePreStartInitMethodsCore(ICollection`1 methods, Func`1 setHostingEnvironmentCultures) +550
System.Web.Compilation.BuildManager.InvokePreStartInitMethods(ICollection`1 methods) +132
System.Web.Compilation.BuildManager.CallPreStartInitMethods(String preStartInitListPath) +90
System.Web.Compilation.BuildManager.ExecutePreAppStart() +135
System.Web.Hosting.HostingEnvironment.Initialize(ApplicationManager appManager, IApplicationHost appHost, IConfigMapPathFactory configMapPathFactory, HostingEnvironmentParameters hostingParameters, PolicyLevel policyLevel, Exception appDomainCreationException) +516
[HttpException (0x80004005): The pre-application start initialization method Run on type WebActivator.ActivationManager threw an exception with the following error message: Exception has been thrown by the target of an invocation..]
System.Web.HttpRuntime.FirstRequestInit(HttpContext context) +9873912
System.Web.HttpRuntime.EnsureFirstRequestInit(HttpContext context) +101
System.Web.HttpRuntime.ProcessRequestInternal(HttpWorkerRequest wr) +456
I read so many posts, but no avail.
I have a MessageHandler (invoked by ninject), which invokes ISession, when I comment it out, the problem goes away. Why?
GlobalConfiguration.Configuration.MessageHandlers.Add(kernel.Get());

Your Factory and Session interfaces are not bound correctly. You have to set the scope as part of the Binding (InSingletonScope for the Factory as you only ever need one of these, and InThreadScope for the Session). This is so Ninject knows when to inject an existing reference or create a new instance of each type.
Try modifying your configuration to the following:
public void ConfigureNHibernate(IKernel container)
{
var sessionFactory = FluentNHibernate
.Cfg.Fluently.Configure()
.Database(
MsSqlConfiguration.MsSql2008.ConnectionString(
c => c.FromConnectionStringWithKey("ApikeysDb")))
.CurrentSessionContext("web")
.Mappings(m => m.FluentMappings.AddFromAssemblyOf<CTP.ApiNext.Data.SqlServer.SqlCommandFactory>());
// Bind the ISession Factory - Singleton as only ever need one of these
container.Bind<ISessionFactory>().ToMethod(x =>configuration.BuildSessionFactory()).InSingletonScope();
// Bind the ISession
container.Bind<ISession>().ToMethod(c => c.Kernel.Get<ISessionFactory>().OpenSession()).InThreadScope();
}
To test the above you can immediately try to instantiate a Factory:
var sessionFactory = Kernel.Get<ISessionFactory>();

Related

Resharper command line tool throwing exceptions

I discovered resharper command line tools. I am using the command utility dupfinder.exe to check duplicates in my code. I am using windows 10 64 bit. I executed the command:
dupfinder sample.sln -o=output.xml
where sample.sln is the file I am evaluating and output.xml where dupfinder will write the results. I am getting the following output:
JetBrains Duplicates Finder 2019.3.1
Running in 64-bit mode, .NET runtime 4.0.30319.42000 under Microsoft Windows NT 10.0.18362.0
Could not bind the component argument descriptor on JetBrains.ProjectModel.BuildTools.BuildToolPlatformsProviderBase+SolutionWatcher. Exception has been thrown by the target of an invocation. Object reference not set to an instance of an object.
--- EXCEPTION #1/4 [NullReferenceException]
Message = "Object reference not set to an instance of an object."
ExceptionPath = Root.InnerException.InnerException.InnerException
ClassName = System.NullReferenceException
Data.ThreadLocalDebugInfo = Run
HResult = E_POINTER=COR_E_NULLREFERENCE=80004003
Source = JetBrains.ReSharperAutomationTools.CommandLine.Common
StackTraceString = "
at JetBrains.ReSharperAutomationTools.CommandLine.Common.Console.BatchTool.MsBuild.CommandLineSolutionToolset.CommandLineToolsProvider.Discover(BuildToolEnvironment env)
at JetBrains.ProjectModel.BuildTools.BuildToolContainer.Discover(IReadOnlyCollection`1 providers, BuildToolEnvironment env)
at JetBrains.ReSharperAutomationTools.CommandLine.Common.Console.BatchTool.MsBuild.CommandLineSolutionToolset..ctor(Lifetime lifetime, ILogger logger, ICommandLineToolSettings settings, BuildToolContainer buildToolContainer)
"
--- Outer ---
--- EXCEPTION #2/4 [TargetInvocationException]
Message = "Exception has been thrown by the target of an invocation."
ExceptionPath = Root.InnerException.InnerException
ClassName = System.Reflection.TargetInvocationException
Data.ThreadLocalDebugInfo = Run
InnerException = "Exception #1 at Root.InnerException.InnerException.InnerException"
HResult = COR_E_TARGETINVOCATION=80131604
Source = mscorlib
StackTraceString = "
at System.RuntimeMethodHandle.InvokeMethod(Object target, Object[] arguments, Signature sig, Boolean constructor)
at System.Reflection.RuntimeConstructorInfo.Invoke(BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture)
at JetBrains.Application.Extensibility.PartCatalogTypeComponentDescriptor.CreateInstanceOf(Type type, IValueResolveContext context)
at JetBrains.Application.Extensibility.PartCatalogTypeComponentDescriptor.CreateInstance(IValueResolveContext context)
at JetBrains.Application.Components.SingletonDescriptor.CreateInstanceChecked(OnError onError, IComponentContainer container)
at JetBrains.Application.Components.SingletonDescriptor.GetValue()
at JetBrains.Application.Components.SignatureResolution.BindArguments(List`1 argumentDescriptors, Object origin)
"
--- Outer ---
--- EXCEPTION #3/4 [InvalidOperationException]
Message = "Could not bind the component argument descriptor on JetBrains.ProjectModel.BuildTools.BuildToolPlatformsProviderBase+SolutionWatcher."
ExceptionPath = Root.InnerException
ClassName = System.InvalidOperationException
Data.ArgumentIndex = 1
Data.Origin = JetBrains.ProjectModel.BuildTools.BuildToolPlatformsProviderBase+SolutionWatcher
InnerException = "Exception #2 at Root.InnerException.InnerException"
HResult = COR_E_INVALIDOPERATION=80131509
--- Outer ---
--- EXCEPTION #4/4 [LoggerException]
Message = "Could not bind the component argument descriptor on JetBrains.ProjectModel.BuildTools.BuildToolPlatformsProviderBase+SolutionWatcher."
ExceptionPath = Root
ClassName = JetBrains.Util.LoggerException
InnerException = "Exception #3 at Root.InnerException"
HResult = COR_E_APPLICATION=80131600
StackTraceString = "
at JetBrains.Util.ILoggerEx.Error(ILogger this, Exception exception, ExceptionOrigin origin, String comment)
at JetBrains.Application.Components.SignatureResolution.BindArguments(List`1 argumentDescriptors, Object origin)
at JetBrains.Application.Extensibility.PartCatalogTypeComponentDescriptor.CreateInstanceOf(Type type, IValueResolveContext context)
at JetBrains.Application.Extensibility.PartCatalogTypeComponentDescriptor.CreateInstance(IValueResolveContext context)
at JetBrains.Application.Components.SingletonDescriptor.CreateInstanceChecked(OnError onError, IComponentContainer container)
at JetBrains.Application.Components.SingletonDescriptor.GetValue()
at JetBrains.Application.Components.InitializationStrategyDefault.Schedule(Lifetime lifetime, ICollection`1 dscs, IComponentContainer container)
at JetBrains.Application.Components.ComponentStorage.ComposeDescriptors(ICollection`1 descriptors)
at JetBrains.ProjectModel.SolutionInstance.OpenSolutionInstance(ISolutionLoadTasksScheduler taskScheduler)
at JetBrains.ProjectModel.SolutionManagerBase.CreateSolutionInstance(SolutionElement solutionElement, SolutionInstance solutionInstance)
at JetBrains.ProjectModel.Impl.SolutionManagerImpl.CreateSolution(SolutionLocation solutionLocation)
at JetBrains.CommandLine.DupFinder.Application.Console.DupFinderProductMain.RunGuarded()
at JetBrains.CommandLine.DupFinder.Application.Console.DupFinderProductMain.<>c__DisplayClass4_0.<Run>b__0()
at JetBrains.Threading.ReentrancyGuard.Execute(String name, Action action)
at JetBrains.CommandLine.DupFinder.Application.Console.DupFinderProductMain.Run()
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 JetBrains.Application.Environment.RunsPublicStaticIntMain.<>c__DisplayClass0_0.<.ctor>b__0()
at JetBrains.Util.Logging.Logger.Catch(Action action)
at JetBrains.Threading.JetDispatcher.Closure.Execute()
at JetBrains.Util.Concurrency.WinJetDispatcher.ProcessQueue(Int32 nMinBucket)
at System.Windows.Threading.DispatcherOperation.InvokeDelegateCore()
at System.Windows.Threading.DispatcherOperation.InvokeImpl()
at MS.Internal.CulturePreservingExecutionContext.CallbackWrapper(Object obj)
at System.Threading.ExecutionContext.RunInternal(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx)
at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx)
at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state)
at MS.Internal.CulturePreservingExecutionContext.Run(CulturePreservingExecutionContext executionContext, ContextCallback callback, Object state)
at System.Windows.Threading.DispatcherOperation.Invoke()
at System.Windows.Threading.Dispatcher.ProcessQueue()
at System.Windows.Threading.Dispatcher.WndProcHook(IntPtr hwnd, Int32 msg, IntPtr wParam, IntPtr lParam, Boolean& handled)
at MS.Win32.HwndWrapper.WndProc(IntPtr hwnd, Int32 msg, IntPtr wParam, IntPtr lParam, Boolean& handled)
at MS.Win32.HwndSubclass.DispatcherCallbackOperation(Object o)
at System.Windows.Threading.ExceptionWrapper.InternalRealCall(Delegate callback, Object args, Int32 numArgs)
at System.Windows.Threading.ExceptionWrapper.TryCatchWhen(Object source, Delegate callback, Object args, Int32 numArgs, Delegate catchHandler)
at System.Windows.Threading.Dispatcher.LegacyInvokeImpl(DispatcherPriority priority, TimeSpan timeout, Delegate method, Object args, Int32 numArgs)
at MS.Win32.HwndSubclass.SubclassWndProc(IntPtr hwnd, Int32 msg, IntPtr wParam, IntPtr lParam)
at MS.Win32.UnsafeNativeMethods.DispatchMessage(MSG& msg)
at MS.Win32.UnsafeNativeMethods.DispatchMessage(MSG& msg)
at System.Windows.Threading.Dispatcher.PushFrameImpl(DispatcherFrame frame)
at JetBrains.Application.Environment.IJetHostEx.<>c__DisplayClass2_0.<RunHostMessageLoop>b__0(Lifetime lifetime)
at JetBrains.Lifetimes.Lifetime.Using(Action`1 action)
at JetBrains.Application.Environment.IJetHostEx.RunHostMessageLoop(IComponentContainer containerEnv)
at JetBrains.Application.Environment.HostParameters.JetHostParametersCaller.RunMainLoop(ComponentContainer containerEnv)
at JetBrains.Application.Environment.JetEnvironment.InternalRun(JetHostParametersCaller host, ComponentContainer containerEnv)
at JetBrains.Application.Environment.JetEnvironment.CreateAndRun(Full hostparams)
at JetBrains.ReSharperAutomationTools.CommandLine.Common.Application.CommandLineProgram.Main(Assembly assembly, Type environmentZoneType, HostInfo hostInfo, ICommandLineProductInfo productInfo, String[] args, IJetHostMixin[] mixins)
at JetBrains.ReSharperAutomationTools.CommandLine.Common.Application.CommandLineProgram.Run[TZone,TProductInfo](String productHostShortName, String[] args)
at JetBrains.CommandLine.DupFinder.Application.DupFinderProgram.Main(String[] args)
"
Component JetBrains.ProjectModel.BuildTools.BuildToolPlatformsProviderBase+SolutionWatcher [Singleton, Corrupted] construction has failed. Exception has been thrown by the target of an invocation. Object reference not set to an instance of an object.
// more stacktrace omitted due to number of character limitations
I do not understand the errors. What should I do?
There is a bug report about the same exception on JetBrains bug tracker. It is going to be fixed in the next bugfix update soon.
UPDATE: Fixed in 2019.3.2 build

Sitecore Logs - Azure Search

Currently I'm seeing the following a lot in my logs, I'm using Sitecore 8.2 rev 2 with azure. The issue only started recently when I added some new indexes to the site for a new microsite. Any ideas of where to start investigating, I've raised with Sitecore too?
ManagedPoolThread #17 22:03:10 ERROR Exception
Exception: System.Reflection.TargetInvocationException
Message: Exception has been thrown by the target of an invocation.
Source: mscorlib
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 Sitecore.Reflection.ReflectionUtil.InvokeMethod(MethodInfo method, Object[] parameters, Object obj)
at Sitecore.Jobs.JobRunner.RunMethod(JobArgs args)
at (Object , Object[] )
at Sitecore.Pipelines.CorePipeline.Run(PipelineArgs args)
at Sitecore.Pipelines.DefaultCorePipelineManager.Run(String pipelineName, PipelineArgs args, String pipelineDomain)
at Sitecore.Jobs.Job.ThreadEntry(Object state)
Nested Exception
Exception: System.AggregateException
Message: One or more errors occurred.
Source: mscorlib
at System.Threading.Tasks.Task.ThrowIfExceptional(Boolean includeTaskCanceledExceptions)
at System.Threading.Tasks.Task.Wait(Int32 millisecondsTimeout, CancellationToken cancellationToken)
at System.Threading.Tasks.Parallel.ForWorker[TLocal](Int32 fromInclusive, Int32 toExclusive, ParallelOptions parallelOptions, Action`1 body, Action`2 bodyWithState, Func`4 bodyWithLocal, Func`1 localInit, Action`1 localFinally)
at System.Threading.Tasks.Parallel.ForEachWorker[TSource,TLocal](IEnumerable`1 source, ParallelOptions parallelOptions, Action`1 body, Action`2 bodyWithState, Action`3 bodyWithStateAndIndex, Func`4 bodyWithStateAndLocal, Func`5 bodyWithEverything, Func`1 localInit, Action`1 localFinally)
at System.Threading.Tasks.Parallel.ForEach[TSource](IEnumerable`1 source, ParallelOptions parallelOptions, Action`2 body)
at Sitecore.ContentSearch.AbstractSearchIndex.PerformUpdate(IEnumerable`1 indexableInfo, IndexingOptions indexingOptions)
Nested Exception
Exception: System.InvalidOperationException
Message: Sequence contains no elements
Source: System.Core
at System.Linq.Enumerable.First[TSource](IEnumerable`1 source)
at Sitecore.ContentSearch.Azure.CloudSearchUpdateContext.Delete(IIndexableId id)
at Sitecore.ContentSearch.SitecoreItemCrawler.Update(IProviderUpdateContext context, IIndexableUniqueId indexableUniqueId, IndexEntryOperationContext operationContext, IndexingOptions indexingOptions)
at Sitecore.ContentSearch.AbstractSearchIndex.<>c__DisplayClass93_2.<PerformUpdate>b__0(IndexableInfo info, ParallelLoopState parallelLoopState)
at System.Threading.Tasks.Parallel.<>c__DisplayClass17_0`1.<ForWorker>b__1()
at System.Threading.Tasks.Task.InnerInvokeWithArg(Task childTask)
at System.Threading.Tasks.Task.<>c__DisplayClass176_0.<ExecuteSelfReplicating>b__0(Object )
For those with the same issue,
The patch is Sitecore.Support.158988 found here:
https://github.com/SitecoreSupport/Sitecore.Support.158988
Versions cover Sitecore 8.2 update 1 and update 2.
164633 The CloudSearchUpdateContext.Delete(IIndexableId) fails with an exception in case the search index does not contain any matching documents.
Thanks.
Looks like there is a patch for this from Sitecore, hopefully this will resolve the issue.

Sitecore Azure Error : Instance validation error: '2014-06.2.4' is not a valid value for SchemaVersion

When I click on Sitecore Azure module from my Sitecore desktop I'm getting bellow given error. I've Sitecore SDK 2.9 installed
Instance validation error: '2014-06.2.4' is not a valid value for SchemaVersion.
Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.
Exception Details: System.InvalidOperationException: Instance validation error: '2014-06.2.4' is not a valid value for SchemaVersion.
Source Error:
An unhandled exception was generated during the execution of the current web request. Information regarding the origin and location of the exception can be identified using the exception stack trace below.
Stack Trace:
[InvalidOperationException: Instance validation error: '2014-06.2.4' is not a valid value for SchemaVersion.]
Microsoft.Xml.Serialization.GeneratedAssembly.XmlSerializationReaderServiceDefinition.Read68_SchemaVersion(String s) +123
Microsoft.Xml.Serialization.GeneratedAssembly.XmlSerializationReaderServiceDefinition.Read71_ServiceDefinition(Boolean isNullable, Boolean checkType) +585
Microsoft.Xml.Serialization.GeneratedAssembly.XmlSerializationReaderServiceDefinition.Read72_ServiceDefinition() +116
[InvalidOperationException: There is an error in XML document (2, 147).]
System.Xml.Serialization.XmlSerializer.Deserialize(XmlReader xmlReader, String encodingStyle, XmlDeserializationEvents events) +857
System.Xml.Serialization.XmlSerializer.Deserialize(TextReader textReader) +159
Sitecore.Azure.Deployments.AzureDeployments.Deployment.LoadData() +568
Sitecore.Azure.Deployments.AzureDeployments.AzureDeployment.LoadData() +17
Sitecore.Azure.Deployments.AzureEntity..ctor(AzureEntity parentNode, Item storeItem) +196
Sitecore.Azure.Deployments.AzureDeployments.ContentDeliveryDeployment..ctor(WebRole parentNode, DeploymentItem item) +30
Sitecore.Azure.Deployments.EntitiesFactory.Create(Item item, AzureEntity parent) +2431
Sitecore.Azure.Deployments.AzureEntity..ctor(AzureEntity parentNode, Item storeItem) +334
Sitecore.Azure.Deployments.EntitiesFactory.Create(Item item, AzureEntity parent) +1581
Sitecore.Azure.Deployments.AzureEntity..ctor(AzureEntity parentNode, Item storeItem) +334
Sitecore.Azure.Deployments.EntitiesFactory.Create(Item item, AzureEntity parent) +1464
Sitecore.Azure.Deployments.AzureEntity..ctor(AzureEntity parentNode, Item storeItem) +334
Sitecore.Azure.Deployments.EntitiesFactory.Create(Item item, AzureEntity parent) +1881
Sitecore.Azure.Deployments.AzureEntity..ctor(AzureEntity parentNode, Item storeItem) +334
Sitecore.Azure.Deployments.Environments.Environment..ctor(AzureEntity parentNode, EnvironmentDefinition environmentDefinition, EnvironmentItem item) +41
Sitecore.Azure.Deployments.EntitiesFactory.Create(Item item, AzureEntity parent) +2292
Sitecore.Azure.Deployments.AzureEntity..ctor(AzureEntity parentNode, Item storeItem) +334
Sitecore.Azure.Configuration.Settings.get_EnvironmentsRoot() +150
Sitecore.Azure.Managers.AzureManagers.TrafficProfilesManager.GetGlobalDomainURIs() +76
Sitecore.Azure.UI.Shell.Applications.Azure.AzureManagerForm.TrafficManagerInitialising(String environmnentType, DeploymentSlot slot, String& startupScript) +124
Sitecore.Azure.UI.Shell.Applications.Azure.AzureManagerForm.OnLoad(EventArgs e) +159
[TargetInvocationException: Exception has been thrown by the target of an invocation.]
System.RuntimeMethodHandle.InvokeMethod(Object target, Object[] arguments, Signature sig, Boolean constructor) +0
System.Reflection.RuntimeMethodInfo.UnsafeInvokeInternal(Object obj, Object[] parameters, Object[] arguments) +128
System.Reflection.RuntimeMethodInfo.Invoke(Object obj, BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture) +146
Sitecore.Reflection.ReflectionUtil.InvokeMethod(MethodInfo method, Object[] parameters, Object obj) +89
Sitecore.Web.UI.Sheer.ClientPage.OnLoad(EventArgs e) +594
System.Web.UI.Control.LoadRecursive() +68
System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint) +4498
Version Information: Microsoft .NET Framework Version:4.0.30319; ASP.NET Version:4.6.1055.0
Fixed it by searching in sitecore for 2014-06.2.4 and replacing this value with 2015-04.2.6

CRM trying re-create 'Business Closure Calendar' calendar every minute

We are getting following error in event log because InternalOperationPlugin is trying to create 'Business Closure Calendar' in Calender entity almost every minute.
InternalOperationPlugin is a core system plugin which is registered on Stage 30 (non-customizable). Can anyone give an idea why core plugin is trying to create this record every minute.
We are on Roll up 8 and not in position to install latest.
Thanks in Advance
The Web Service plug-in failed in OrganizationId: 07ae1f6f-237f-e111-83c6-005056b41d30; SdkMessageProcessingStepId: 22ccbb1b-ea3e-db11-86a7-000a3a5473e8;
EntityName: calendar;
Stage: 30;
MessageName: RetrieveMultiple;
AssemblyName: Microsoft.Crm.Extensibility.InternalOperationPlugin, Microsoft.Crm.ObjectModel, Version=5.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._InvokeMethodFast(IRuntimeMethodInfo method, Object target, Object[] arguments, SignatureStruct& sig, MethodAttributes methodAttributes, RuntimeType 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(IServiceProvider serviceProvider)
at Microsoft.Crm.Extensibility.V5PluginProxyStep.ExecuteInternal(PipelineExecutionContext context)
at Microsoft.Crm.Extensibility.VersionedPluginProxyStepBase.Execute(PipelineExecutionContext context)
Inner Exception: System.ArgumentException: Item has already been added. Key in dictionary: '7fdf4980-237f-e111-83c6-005056b41d30' Key being added: '7fdf4980-237f-e111-83c6-005056b41d30'
at System.Collections.Hashtable.Insert(Object key, Object nvalue, Boolean add)
at Microsoft.Crm.ObjectModel.CalendarService.RetrieveMultiple(EntityExpression entityExpression, ExecutionContext context)
** Error from Event Log **
at VersionedPluginProxyStepBase.Execute(PipelineExecutionContext context)
at Pipeline.Execute(PipelineExecutionContext context)
at MessageProcessor.Execute(PipelineExecutionContext context)
at InternalMessageDispatcher.Execute(PipelineExecutionContext context)
at ExternalMessageDispatcher.ExecuteInternal(IInProcessOrganizationServiceFactory serviceFactory, IPlatformMessageDispatcherFactory dispatcherFactory, String messageName, String requestName, Int32 primaryObjectTypeCode, Int32 secondaryObjectTypeCode, ParameterCollection fields, CorrelationToken correlationToken, CallerOriginToken originToken, UserAuth userAuth, Guid callerId, Guid transactionContextId, Int32 invocationSource, Nullable`1 requestId, Version endpointVersion)
at OrganizationSdkServiceInternal.ExecuteRequest(OrganizationRequest request, CorrelationToken correlationToken, CallerOriginToken callerOriginToken, WebServiceType serviceType)
at OrganizationSdkServiceInternal.Execute(OrganizationRequest request, CorrelationToken correlationToken, CallerOriginToken callerOriginToken, WebServiceType serviceType)
at InprocessServiceProxy.ExecuteCore(OrganizationRequest request)
at SandboxSdkListener.Execute(SandboxCallInfo callInfo, SandboxSdkContext requestContext, String operation, Byte[] serializedRequest)
at
at SyncMethodInvoker.Invoke(Object instance, Object[] inputs, Object[]& outputs)
at DispatchOperationRuntime.InvokeBegin(MessageRpc& rpc)
at ImmutableDispatchRuntime.ProcessMessage5(MessageRpc& rpc)
at ImmutableDispatchRuntime.ProcessMessage31(MessageRpc& rpc)
at MessageRpc.Process(Boolean isOperationContextSet)
at ChannelHandler.DispatchAndReleasePump(RequestContext request, Boolean cleanThread, OperationContext currentOperationContext)
at ChannelHandler.HandleRequest(RequestContext request, OperationContext currentOperationContext)
at ChannelHandler.AsyncMessagePump(IAsyncResult result)
at AsyncThunk.UnhandledExceptionFrame(IAsyncResult result)
at AsyncResult.Complete(Boolean completedSynchronously)
at TryReceiveAsyncResult.OnReceive(IAsyncResult result)
at AsyncThunk.UnhandledExceptionFrame(IAsyncResult result)
at AsyncResult.Complete(Boolean completedSynchronously)
at ReceiveAsyncResult.OnReceiveComplete(Object state)
at SessionConnectionReader.OnAsyncReadComplete(Object state)
at AsyncThunk.UnhandledExceptionFrame(IAsyncResult result)
at LazyAsyncResult.Complete(IntPtr userToken)
at NegotiateStream.ProcessFrameBody(Int32 readBytes, Byte[] buffer, Int32 offset, Int32 count, AsyncProtocolRequest asyncRequest)
at NegotiateStream.ReadCallback(AsyncProtocolRequest asyncRequest)
at FixedSizeReader.CheckCompletionBeforeNextRead(Int32 bytes)
at FixedSizeReader.ReadCallback(IAsyncResult transportResult)
at AsyncResult.Complete(Boolean completedSynchronously)
at ReadAsyncResult.OnAsyncReadComplete(Object state)
at SocketConnection.AsyncReadCallback(Boolean haveResult, Int32 error, Int32 bytesRead)
at IOCompletionThunk.UnhandledExceptionFrame(UInt32 error, UInt32 bytesRead, NativeOverlapped* nativeOverlapped)
at _IOCompletionCallback.PerformIOCompletionCallback(UInt32 errorCode, UInt32 numBytes, NativeOverlapped* pOVERLAP)
Web Service Plug-in failed in SdkMessageProcessingStepId: {22CCBB1B-EA3E-DB11-86A7-000A3A5473E8}; EntityName: calendar; Stage: 30; MessageName: RetrieveMultiple; AssemblyName: Microsoft.Crm.Extensibility.InternalOperationPlugin, Microsoft.Crm.ObjectModel, Version=5.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._InvokeMethodFast(IRuntimeMethodInfo method, Object target, Object[] arguments, SignatureStruct& sig, MethodAttributes methodAttributes, RuntimeType 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(IServiceProvider serviceProvider)
at Microsoft.Crm.Extensibility.V5PluginProxyStep.ExecuteInternal(PipelineExecutionContext context)
at Microsoft.Crm.Extensibility.VersionedPluginProxyStepBase.Execute(PipelineExecutionContext context)
Inner Exception: System.ArgumentException: Item has already been added. Key in dictionary: '7fdf4980-237f-e111-83c6-005056b41d30' Key being added: '7fdf4980-237f-e111-83c6-005056b41d30'
at System.Collections.Hashtable.Insert(Object key, Object nvalue, Boolean add)
at Microsoft.Crm.ObjectModel.CalendarService.RetrieveMultiple(EntityExpression entityExpression, ExecutionContext context)
.
UPDATE
I have already checked Calendar Entity. There is only one record with Id equals to '7fdf4980-237f-e111-83c6-005056b41d30'. Mpreover, I have searched whole database to find out if there is any other record using same Id.

Unable to update OptionSetValue field on CRM 2011 custom Entity

I'm getting a "Specified cast is not valid." Exception when trying to update an OptionSetValue attribute of a custom field on a custom entity.
This works:
data = new Xrm.Xyz_data()
{
Xyz_dataId = (Guid)entity["xyz_dataId"],
// Xyz_dataStatus = new OptionSetValue(5),
Xyz_IsSyncReqd = true
};
service.Update(data);
But uncomment the OptionSetValue line and it throws this exception:
System.ServiceModel.FaultException`1[Microsoft.Xrm.Sdk.OrganizationServiceFault]: Specified cast is not valid. (Fault Detail is equal to Microsoft.Xrm.Sdk.OrganizationServiceFault).
With this stack trace:
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 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.Update(Entity entity)
at Microsoft.Xrm.Sdk.Client.OrganizationServiceProxy.UpdateCore(Entity entity)
at Microsoft.Xrm.Sdk.Client.OrganizationServiceProxy.Update(Entity entity)
That looks right to me - I don't use early bound which it looks like you are doing but can you verify that the data context has been refreshed since the picklist attribute was created and published?
If this is a built in state field you will probably need to first do the update and then perform a UpdateStateValueRequest. Excerpt from CRM 2011 SDK -
#region How to update state value
// Modify the state value label from Active to Open.
// Create the request.
UpdateStateValueRequest updateStateValue = new UpdateStateValueRequest
{
AttributeLogicalName = "statecode",
EntityLogicalName = Contact.EntityLogicalName,
Value = 1,
Label = new Label("Open", _languageCode)
};
// Execute the request.
_serviceProxy.Execute(updateStateValue);
#endregion How to update state value
So I finally figured out what was happening. I turned on server side debugging using the same registry settings as CRM 4.0:
Windows Registry Editor Version 5.00
[HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\MSCRM]
"TraceEnabled"=dword:00000001
"TraceCategories"="*:Error"
"TraceCallStack"=dword:00000001
"TraceRefresh"=dword:00000001
I reran my test that was failing, and found this error:
[2011-10-24 18:19:37.990] Process: w3wp |Organization:00000000-0000-0000-0000-000000000000 |Thread: 14 |Category: Platform |User: 00000000-0000-0000-0000-000000000000 |Level: Error | ExceptionConverter.ConvertMessageAndErrorCode
at ExceptionConverter.ConvertMessageAndErrorCode(Exception exception, Int32& errorCode)
at ExceptionConverter.ToSingleFaultOther(Exception exception)
at ExceptionConverter.ToSingleFaultUntyped(Exception exception)
at ExceptionConverter.ConvertToFault(Exception exception)
at ExceptionConverter.TryConvertToFaultExceptionInternal(Exception exception, Boolean createNewFaultException, FaultException`1& faultException)
at FaultHelper.ConvertToFault(Exception exception)
at OrganizationSdkServiceInternal.Update(Entity entity, CorrelationToken correlationToken, CallerOriginToken callerOriginToken, WebServiceType serviceType)
at
at SyncMethodInvoker.Invoke(Object instance, Object[] inputs, Object[]& outputs)
at DispatchOperationRuntime.InvokeBegin(MessageRpc& rpc)
at ImmutableDispatchRuntime.ProcessMessage5(MessageRpc& rpc)
at ImmutableDispatchRuntime.ProcessMessage31(MessageRpc& rpc)
at MessageRpc.Process(Boolean isOperationContextSet)
at ChannelHandler.DispatchAndReleasePump(RequestContext request, Boolean cleanThread, OperationContext currentOperationContext)
at ChannelHandler.HandleRequest(RequestContext request, OperationContext currentOperationContext)
at ChannelHandler.AsyncMessagePump(IAsyncResult result)
at AsyncThunk.UnhandledExceptionFrame(IAsyncResult result)
at AsyncResult.Complete(Boolean completedSynchronously)
at ReceiveItemAndVerifySecurityAsyncResult`2.InnerTryReceiveCompletedCallback(IAsyncResult result)
at AsyncThunk.UnhandledExceptionFrame(IAsyncResult result)
at AsyncResult.Complete(Boolean completedSynchronously)
at AsyncQueueReader.Set(Item item)
at InputQueue`1.Dispatch()
at ScheduledOverlapped.IOCallback(UInt32 errorCode, UInt32 numBytes, NativeOverlapped* nativeOverlapped)
at IOCompletionThunk.UnhandledExceptionFrame(UInt32 error, UInt32 bytesRead, NativeOverlapped* nativeOverlapped)
at _IOCompletionCallback.PerformIOCompletionCallback(UInt32 errorCode, UInt32 numBytes, NativeOverlapped* pOVERLAP)
>System.InvalidCastException: Microsoft Dynamics CRM has experienced an error. Reference number for administrators or support: #9F125FAE: System.InvalidCastException: Specified cast is not valid.
> at Microsoft.Practices.EnterpriseLibrary.ExceptionHandling.ExceptionPolicyEntry.IntentionalRethrow(Exception chainException, Exception originalException)
> at Microsoft.Practices.EnterpriseLibrary.ExceptionHandling.ExceptionPolicyEntry.RethrowRecommended(Exception chainException, Exception originalException)
> at Microsoft.Practices.EnterpriseLibrary.ExceptionHandling.ExceptionPolicyEntry.Handle(Exception exceptionToHandle)
> at Microsoft.Practices.EnterpriseLibrary.ExceptionHandling.ExceptionPolicyImpl.HandleException(Exception exceptionToHandle)
> at Microsoft.Practices.EnterpriseLibrary.ExceptionHandling.ExceptionPolicy.HandleException(Exception exceptionToHandle, String policyName, ExceptionPolicyFactory policyFactory)
> at Microsoft.Practices.EnterpriseLibrary.ExceptionHandling.ExceptionPolicy.HandleException(Exception exceptionToHandle, String policyName)
> at Common.Services.ExceptionPolicy.HandleException(Exception exceptionToHandle, String policyName)
> at XYZ.CRM.Common.Services.ExceptionPolicy.HandleException(Exception exceptionToHandle, String policyName)
> at XYZ.CRM.Plugin.Common.PluginBase.OnError(Exception ex)
> at XYZ.CRM.Plugin.Common.PluginBase.Execute(IServiceProvider serviceProvider)
> at Microsoft.Crm.Extensibility.V5PluginProxyStep.ExecuteInternal(PipelineExecutionContext context)
> at Microsoft.Crm.Extensibility.VersionedPluginProxyStepBase.Execute(PipelineExecutionContext context)
And since I was debugging my plugin via a unit test, I realized that another plugin was getting fired when those fields were updated by my plugin, and that plugin was apparently causing an exception. But even worse was that the exception handler was causing another exception, that was getting returned, masking the true exception. I tested a really simple fix by eating any exceptions that the exception handler might throw, and it is working great now! Now to discover why my other plugin is failing...

Resources