WPF Designer Fails to Load - c#

Using Visual Studio 2012 on Win7.
I recently converted a WPF application to a WPF user control by replacing the XAML flags <Window> with <UserControl> and changing the resources to <Control.Resources>. I also altered the codebehind to inherit from UserControl just to be safe, but at some point this broke the application and I can no longer view it in Design mode. All I get is this nonsense:
System.NullReferenceException
Object reference not set to an instance of an object.
at Microsoft.Expression.DesignHost.Isolation.Remoting.STAMarshaler.WaitForCompletion(NestedCallContext nestedCallContext, BlockingCall call, WaitHandle timeoutSignal)
at Microsoft.Expression.DesignHost.Isolation.Remoting.STAMarshaler.MarshalOutSynchronous(Action action, Int32 targetApartmentId, WaitHandle aborted, WaitHandle timeoutSignal)
at Microsoft.Expression.DesignHost.Isolation.Remoting.STAMarshaler.MarshalOut(Action action, Int32 targetApartmentId, WaitHandle aborted, CallSynchronizationMode syncMode, WaitHandle timeoutSignal)
at Microsoft.Expression.DesignHost.Isolation.Remoting.ThreadMarshaler.MarshalOut[TValue](RemoteHandle`1 targetObject, Action action, CallSynchronizationMode syncMode)
at Microsoft.Expression.DesignHost.Isolation.Remoting.ThreadMarshaler.MarshalOut[TResult,TValue](RemoteHandle`1 targetObject, Func`2 func, CallSynchronizationMode syncMode)
at Microsoft.Expression.DesignHost.Isolation.Remoting.LocalDesignerService.CreateDesignerImpl(IHostSourceItem item, IHostTextEditor editor, RemoteCancellationToken remoteCancelToken)
at Microsoft.Expression.DesignHost.Isolation.Remoting.LocalDesignerService.<>c__DisplayClass12.<Microsoft.Expression.DesignHost.IDesignerService.CreateDesigner>b__11(RemoteCancellationToken remoteToken)
at Microsoft.Expression.DesignHost.Isolation.Remoting.LocalDesignerService.CallWithCancellation[TResult](CancellationToken cancelToken, Func`2 func)
at Microsoft.Expression.DesignHost.Isolation.Remoting.LocalDesignerService.Microsoft.Expression.DesignHost.IDesignerService.CreateDesigner(IHostSourceItem item, IHostTextEditor editor, CancellationToken cancelToken)
at Microsoft.Expression.DesignHost.IsolatedDesignerService.IsolatedDesignerView.CreateDesignerViewInfo(CancellationToken cancelToken)
System.NullReferenceException
Object reference not set to an instance of an object.
Server stack trace:
at Microsoft.Expression.DesignHost.Isolation.Remoting.STAMarshaler.WaitForCompletion(NestedCallContext nestedCallContext, BlockingCall call, WaitHandle timeoutSignal)
at Microsoft.Expression.DesignHost.Isolation.Remoting.STAMarshaler.MarshalIn(Action action, Int32 targetApartmentId)
at Microsoft.Expression.DesignHost.Isolation.Remoting.ThreadMarshaler.MarshalIn(IRemoteObject targetObject, Action action)
at Microsoft.Expression.DesignHost.Isolation.Remoting.ThreadMarshaler.MarshalIn[TResult](IRemoteObject targetObject, Func`1 func)
at Microsoft.Expression.DesignHost.Isolation.Remoting.RemoteDesignerService.Microsoft.Expression.DesignHost.Isolation.Remoting.IRemoteDesignerService.CreateDesigner(IRemoteHostSourceItem remoteItem, IRemoteHostTextEditor remoteEditor, IRemoteCancellationToken remoteToken)
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 [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.Expression.DesignHost.Isolation.Remoting.IRemoteDesignerService.CreateDesigner(IRemoteHostSourceItem remoteItem, IRemoteHostTextEditor remoteEditor, IRemoteCancellationToken cancelToken)
at Microsoft.Expression.DesignHost.Isolation.Remoting.LocalDesignerService.<>c__DisplayClass8.<CreateDesignerImpl>b__6(IRemoteDesignerService d)
at Microsoft.Expression.DesignHost.Isolation.Remoting.ThreadMarshaler.<>c__DisplayClass4`2.<MarshalOut>b__3()
at Microsoft.Expression.DesignHost.Isolation.Remoting.STAMarshaler.Call.InvokeWorker()
System.NullReferenceException
Object reference not set to an instance of an object.
at Microsoft.Expression.DesignHost.Isolation.Remoting.STAMarshaler.WaitForCompletion(NestedCallContext nestedCallContext, BlockingCall call, WaitHandle timeoutSignal)
at Microsoft.Expression.DesignHost.Isolation.Remoting.STAMarshaler.MarshalOutSynchronous(Action action, Int32 targetApartmentId, WaitHandle aborted, WaitHandle timeoutSignal)
at Microsoft.Expression.DesignHost.Isolation.Remoting.STAMarshaler.MarshalOut(Action action, Int32 targetApartmentId, WaitHandle aborted, CallSynchronizationMode syncMode, WaitHandle timeoutSignal)
at Microsoft.Expression.DesignHost.Isolation.Remoting.ThreadMarshaler.MarshalOut[TValue](RemoteHandle`1 targetObject, Action action, CallSynchronizationMode syncMode)
at Microsoft.Expression.DesignHost.Isolation.Remoting.ThreadMarshaler.MarshalOut[TResult,TValue](RemoteHandle`1 targetObject, Func`2 func, CallSynchronizationMode syncMode)
at Microsoft.Expression.DesignHost.Isolation.Remoting.LocalHostProjectService.Microsoft.Expression.DesignHost.IHostProjectService.FindProject(FindProjectCriteria criteria, String criteriaValue)
at Microsoft.Expression.DesignSurface.Project.ProjectContextManager.FindApplicationProjectContext(XamlProjectContext requestingContext)
at Microsoft.Expression.DesignSurface.Project.XamlProjectContext.get_Application()
at Microsoft.Expression.DesignSurface.Documents.SceneDocument.GetApplicationDocument(IXamlProjectContext activeContext)
at Microsoft.Expression.DesignSurface.Documents.SceneDocument.get_ApplicationSceneDocument()
at Microsoft.Expression.DesignSurface.DocumentViewContext.CreateAndOpenView(ISourceItemContext sourceItem, CancellationToken cancelToken, Boolean activate, Boolean ensureOpenInHost, Boolean suppressUI)
at Microsoft.Expression.DesignSurface.DesignerService.CreateDesigner(IHostSourceItem item, IHostTextEditor editor, CancellationToken cancelToken)
at Microsoft.Expression.DesignHost.Isolation.Remoting.RemoteDesignerService.<>c__DisplayClass10.<>c__DisplayClass12.<Microsoft.Expression.DesignHost.Isolation.Remoting.IRemoteDesignerService.CreateDesigner>b__f(CancellationToken cancelToken)
at Microsoft.Expression.DesignHost.Isolation.Remoting.RemoteDesignerService.CallWithCancellation[TResult](IRemoteCancellationToken remoteToken, Func`2 func)
at Microsoft.Expression.DesignHost.Isolation.Remoting.RemoteDesignerService.<>c__DisplayClass10.<Microsoft.Expression.DesignHost.Isolation.Remoting.IRemoteDesignerService.CreateDesigner>b__e()
at Microsoft.Expression.DesignHost.Isolation.Remoting.ThreadMarshaler.<>c__DisplayClass16`1.<MarshalIn>b__15()
at Microsoft.Expression.DesignHost.Isolation.Remoting.STAMarshaler.Call.InvokeWorker()
System.NullReferenceException
Object reference not set to an instance of an object.
Server stack trace:
at Microsoft.Expression.DesignHost.Isolation.Remoting.STAMarshaler.WaitForCompletion(NestedCallContext nestedCallContext, BlockingCall call, WaitHandle timeoutSignal)
at Microsoft.Expression.DesignHost.Isolation.Remoting.STAMarshaler.MarshalIn(Action action, Int32 targetApartmentId)
at Microsoft.Expression.DesignHost.Isolation.Remoting.ThreadMarshaler.MarshalIn(IRemoteObject targetObject, Action action)
at Microsoft.Expression.DesignHost.Isolation.Remoting.ThreadMarshaler.MarshalIn[TResult](IRemoteObject targetObject, Func`1 func)
at Microsoft.Expression.DesignHost.Isolation.Remoting.RemoteHostProjectService.Microsoft.Expression.DesignHost.Isolation.Remoting.IRemoteHostProjectService.FindProject(FindProjectCriteria criteria, String criteriaValue)
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 [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.Expression.DesignHost.Isolation.Remoting.IRemoteHostProjectService.FindProject(FindProjectCriteria criteria, String criteriaValue)
at Microsoft.Expression.DesignHost.Isolation.Remoting.LocalHostProjectService.<>c__DisplayClass7.<Microsoft.Expression.DesignHost.IHostProjectService.FindProject>b__6(IRemoteHostProjectService ps)
at Microsoft.Expression.DesignHost.Isolation.Remoting.ThreadMarshaler.<>c__DisplayClass4`2.<MarshalOut>b__3()
at Microsoft.Expression.DesignHost.Isolation.Remoting.STAMarshaler.Call.InvokeWorker()
System.NullReferenceException
Object reference not set to an instance of an object.
at MS.Internal.VSUtilities.GetBuildAction(IVsHierarchy hierarchy, UInt32 itemid)
at Microsoft.VisualStudio.ExpressionHost.HostServices.HostSourceItem.<>c__DisplayClass9.<Microsoft.Expression.DesignHost.IHostSourceItem.get_BuildItemType>b__7()
at Microsoft.Expression.DesignHost.Isolation.Remoting.STAMarshaler.Call.InvokeWorker()
at Microsoft.Expression.DesignHost.Isolation.Remoting.STAMarshaler.Call.Invoke(Boolean waitingInExternalCall)
at Microsoft.Expression.DesignHost.Isolation.Remoting.STAMarshaler.InvokeCall(Call call)
at Microsoft.Expression.DesignHost.Isolation.Remoting.STAMarshaler.DirectInvoke(Action action, Int32 sourceApartmentId, Int32 targetApartmentId, Int32 originId, WaitHandle aborted)
at Microsoft.Expression.DesignHost.Isolation.Remoting.STAMarshaler.DirectInvokeInbound(Action action, Int32 targetApartmentId)
at Microsoft.Expression.DesignHost.Isolation.Remoting.STAMarshaler.MarshalIn(Action action, Int32 targetApartmentId)
at Microsoft.Expression.DesignHost.Isolation.Remoting.ThreadMarshaler.MarshalIn(IRemoteObject targetObject, Action action)
at Microsoft.VisualStudio.ExpressionHost.HostServices.HostSourceItem.Microsoft.Expression.DesignHost.IHostSourceItem.get_BuildItemType()
at Microsoft.Expression.HostUtility.Extensions.HostExtensions.<HasApplicationDocument>b__0(IHostSourceItem i)
at System.Linq.Enumerable.Any[TSource](IEnumerable`1 source, Func`2 predicate)
at Microsoft.Expression.HostUtility.Extensions.HostExtensions.HasApplicationDocument(IHostProject hostProject)
at Microsoft.VisualStudio.ExpressionHost.HostServices.HostProjectService.FindApplicationProject(String projectPath)
at Microsoft.VisualStudio.ExpressionHost.HostServices.HostProjectService.<FindProjectsInternal>d__30.MoveNext()
at System.Linq.Enumerable.FirstOrDefault[TSource](IEnumerable`1 source)
at Microsoft.VisualStudio.ExpressionHost.HostServices.HostProjectService.Microsoft.Expression.DesignHost.IHostProjectService.FindProject(FindProjectCriteria criteria, String criteriaValue)
at Microsoft.Expression.DesignHost.Isolation.Remoting.RemoteHostProjectService.<>c__DisplayClass1d.<Microsoft.Expression.DesignHost.Isolation.Remoting.IRemoteHostProjectService.FindProject>b__1c()
at Microsoft.Expression.DesignHost.Isolation.Remoting.ThreadMarshaler.<>c__DisplayClass16`1.<MarshalIn>b__15()
at Microsoft.Expression.DesignHost.Isolation.Remoting.STAMarshaler.Call.InvokeWorker()
After several googlings I located that this was a hot issue in 2012 but seems to have all but evaporated since then. But now I have nothing to go on! All my assemblies are 3.5+ (2.0 assemblies being a known issue back then) and I tried removing references but that didn't help either. I've made almost no code changes except instantiating an IoC in the control's load, but I also removed that code completely to no avail.
Anyone have any experience with this issue?
Edit - Please note, if I add a new UserControl with absolutely no customization and attempt to view it I get the same error.
Edit 2 - Tried "Attach to Process", it didn't do anything when I tried to reload the designer.

It's the bug of Visual Studio in creating incorrect intermediate files. Only rebuilding all projects may not solve the problem.
Try this,
Close the Visual Studio.
Delete the 'obj' folder.
Reopen Visual Studio.
Rebuild all projects.
Good luck !

One of the reason may be a binding of some your static resource to object which is temporary null
It may be for example binding to RowData.Row.Property where row is current row of another resource, which is null in Design Time.
The better way is Binding to RowData.Row which with Converter
public object Convert(object value, Type targetType, object parameter,
System.Globalization.CultureInfo culture)
{
if (value is MyContentType)
{
return (value as MyContentType).Property
}
else
{
return defaultValue // this value is valid for wpf control property
}
}
Other reason may be that some of your Converters or TemplateSelectors doesn't check incoming value for null
May be something else but i have no idea ....

Finally figured it out after noticing my other coworkers could see the control just fine.
The answer in this case appears to be that my visual studio was still at first release and required an update to version 4. So if all else fails and someone else runs into this issue, download the most recent visual studio patch and kick it off. I'm sure when it's done installing in a little while it'll work again.

Related

AppDomainUnloadedException when TFS is cloning git repos for a build

Suddenly, when queuing builds in TFS based on a git team project, I get the following stack trace.
Exception Message: Attempted to access an unloaded AppDomain. (type
AppDomainUnloadedException) Exception Stack Trace: Server stack
trace: at
LibGit2Sharp.Core.NativeMethods.git_clone(RepositorySafeHandle& repo,
String origin_url, FilePath workdir_path, GitCloneOptions& opts) at
LibGit2Sharp.Core.Proxy.git_clone(String url, String workdir,
GitCloneOptions& opts) at LibGit2Sharp.Repository.Clone(String
sourceUrl, String workdirPath, CloneOptions options) at
Microsoft.TeamFoundation.Build.Activities.Git.GitPull.GitClone.GetRepository(String
repositoryUrl, String workingFolder, Boolean checkoutSubmodules) at
System.Runtime.Remoting.Messaging.StackBuilderSink._PrivateProcessMessage(IntPtr
md, Object[] args, Object server, Object[]& outArgs) at
System.Runtime.Remoting.Messaging.StackBuilderSink.AsyncProcessMessage(IMessage
msg, IMessageSink replySink)
Exception rethrown at [0]: at
System.Runtime.Remoting.Proxies.RealProxy.EndInvokeHelper(Message
reqMsg, Boolean bProxyCase) at System.Func4.EndInvoke(IAsyncResult
result) at
Microsoft.TeamFoundation.Build.Activities.Git.GitPull.GitRepositoryBase.EndExecute(AsyncCodeActivityContext
context, IAsyncResult result) at
System.Activities.AsyncCodeActivity1.System.Activities.IAsyncCodeActivity.FinishExecution(AsyncCodeActivityContext
context, IAsyncResult result) at
System.Activities.AsyncCodeActivity.CompleteAsyncCodeActivityData.CompleteAsyncCodeActivityWorkItem.Execute(ActivityExecutor
executor, BookmarkManager bookmarkManager)
I changed nothing for this to happend, googling so far I found info about it perhaps being macafee, but we dont use that on our build agent.
Using an on-premises build server
Normal TFS team projects build as expected
Resolved by restarting the server - not sure how I didn't think of that.

"Value cannot be null" when invoking method decorated with [Autocomplete]

I have a Windows Forms application (.NET 3.5) which is deployed with the ClickOnce-technology and is used by approximately 50-100 concurrent users. They all target the same MS SQL database (SQL SERVER 2008 R2) which is hosted externally.
The application itself uses a "wrapper"-class to perform database queries. This class derives from ServicedComponent and decorates its methods with the [AutoComplete] attribute. Below is an example:
[Serializable]
[Transaction(TransactionOption.Required, Isolation=TransactionIsolationLevel.ReadCommitted)]
public class CTxGreenfee374Processor: ServicedComponent
{
public CTxGreenfee374Processor() { }
[AutoComplete]
internal Season SaveSeason(CallContext callContext, Season season)
{
return new PGreenfee374Processor().SaveSeason(callContext, season);
}
}
Most of the time this approach works like a charm. But numerous times a day following exception occur when this method gets invoked (of course there are similar methods with this exact problem):
System.ArgumentNullException
Value cannot be null.
Server stack trace:
at System.Threading.Monitor.Enter(Object obj)
at System.Data.ProviderBase.DbConnectionPool.TransactedConnectionPool.TransactionEnded(Transaction transaction, DbConnectionInternal transactedObject)
at System.Data.ProviderBase.DbConnectionPool.TransactionEnded(Transaction transaction, DbConnectionInternal transactedObject)
at System.Data.ProviderBase.DbConnectionInternal.CleanupConnectionOnTransactionCompletion(Transaction transaction)
at System.Data.SqlClient.SqlDelegatedTransaction.SinglePhaseCommit(SinglePhaseEnlistment enlistment)
at System.Transactions.TransactionStateDelegatedCommitting.EnterState(InternalTransaction tx)
at System.Transactions.TransactionStateDelegated.BeginCommit(InternalTransaction tx, Boolean asyncCommit, AsyncCallback asyncCallback, Object asyncState)
at System.Transactions.CommittableTransaction.Commit()
at System.EnterpriseServices.TransactionProxy.Commit(Guid guid)
at System.Runtime.InteropServices.Marshal.ThrowExceptionForHRInternal(Int32 errorCode, IntPtr errorInfo)
at System.EnterpriseServices.Thunk.Callback.DoCallback(Object otp, IMessage msg, IntPtr ctx, Boolean fIsAutoDone, MemberInfo mb, Boolean bHasGit)
at System.EnterpriseServices.ServicedComponentProxy.CrossCtxInvoke(IMessage reqMsg)
at System.EnterpriseServices.ServicedComponentProxy.Invoke(IMessage request)
at System.Runtime.Remoting.Proxies.RealProxy.PrivateInvoke(MessageData& msgData, Int32 type)
at GOLFIT.BusinessProcess.Economics.CTxGreenfee374Processor.SaveSeason(CallContext callContext, Season season)
at GOLFIT.BusinessProcess.Economics.Greenfee374Processor.SaveSeason(CallContext callContext, Season season) in C:\Projekt\GOLFIT\DEVELOPMENTPROD374\BusinessProcess\GOLFIT.BusinessProcess.Economics\Greenfee374\Greenfee374Processor.cs:line 104
at System.Runtime.Remoting.Messaging.StackBuilderSink._PrivateProcessMessage(IntPtr md, Object[] args, Object server, Int32 methodPtr, Boolean fExecuteInContext, Object[]& outArgs)
at System.Runtime.Remoting.Messaging.StackBuilderSink.PrivateProcessMessage(RuntimeMethodHandle md, Object[] args, Object server, Int32 methodPtr, Boolean fExecuteInContext, Object[]& outArgs)
at System.Runtime.Remoting.Messaging.StackBuilderSink.SyncProcessMessage(IMessage msg, Int32 methodPtr, Boolean fExecuteInContext)
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 GOLFIT.BusinessProcess.Economics.Greenfee374Processor.SaveSeason(CallContext callContext, Season season)
at GOLFIT.WinGUI.Economics.FrmPrice374.Save(Boolean refresh).
As you can see the method SaveSeason in the CTxGreenfee374Processor class is mentioned in the exception. As far as I can see this is the last trace of code that I've written.
My only clue is that the exception has something to do with the [AutoComplete] attribute and/or the derived ServicedComponent class. This conclusion is based on that I've checked for invalid input parameters and that no code inside the method gets executed before the exception. And I assume that both ServicedComponent class and [AutoComplete] attribute performs som kind of logic before the method block executes.
I haven't been successful in recreating this exception when debugging, due to inconsequent occurrences of this exeption. So I've had to depend on logs from the production application.
If anyone got an idea regarding this problem it would be extremely appreciated!

Unhandled exception prevents me from opening a project in Blend 2012

I've been following a tutorial on the MS site and got to here:
http://msdn.microsoft.com/en-us/library/windows/apps/jj129435.aspx
When I switched back to blend I got a huge error of which I have no idea what it means or how to proceed:
An unhandled exception has occurred:
System.InvalidCastException
Return argument has an invalid type.
at Microsoft.Expression.DesignHost.Isolation.Remoting.STAMarshaler.WaitForCompletion(NestedCallContext nestedCallContext, BlockingCall call, WaitHandle timeoutSignal)
at Microsoft.Expression.DesignHost.Isolation.Remoting.STAMarshaler.MarshalOutSynchronous(Action action, Int32 targetApartmentId, WaitHandle aborted, WaitHandle timeoutSignal)
at Microsoft.Expression.DesignHost.Isolation.Remoting.STAMarshaler.MarshalOut(Action action, Int32 targetApartmentId, WaitHandle aborted, CallSynchronizationMode syncMode, WaitHandle timeoutSignal)
at Microsoft.Expression.DesignHost.Isolation.Remoting.ThreadMarshaler.MarshalOut[TValue](RemoteHandle1 targetObject, Action action, CallSynchronizationMode syncMode)
at Microsoft.Expression.DesignHost.Isolation.Remoting.ThreadMarshaler.MarshalOut[TValue](RemoteHandle1 targetObject, Action1 action, CallSynchronizationMode syncMode)
at Microsoft.Expression.DesignHost.Isolation.Remoting.LocalDesignerService.Microsoft.Expression.DesignHost.IDesignerService.Initialize()
at Microsoft.Expression.DesignHost.IsolatedDesignerService.CreateLease(IIsolationTarget isolationTarget, CancellationToken cancelToken, DesignerServiceEntry& entry)
at Microsoft.Expression.DesignHost.IsolatedDesignerService.IsolatedDesignerView.CreateDesignerViewInfo(CancellationToken cancelToken)
at Microsoft.Expression.DesignHost.Isolation.IsolatedTaskScheduler.InvokeWithCulture[T](CultureInfo culture, Func2 func, CancellationToken cancelToken)
at Microsoft.Expression.DesignHost.Isolation.IsolatedTaskScheduler.<>c__DisplayClassa1.<StartTask>b__6()
at System.Threading.Tasks.Task1.InnerInvoke()
at System.Threading.Tasks.Task.Execute()
System.InvalidCastException
Return argument has an invalid type.
Server stack trace:
at Microsoft.Expression.DesignHost.Isolation.Remoting.STAMarshaler.WaitForCompletion(NestedCallContext nestedCallContext, BlockingCall call, WaitHandle timeoutSignal)
at Microsoft.Expression.DesignHost.Isolation.Remoting.STAMarshaler.MarshalIn(Action action, Int32 targetApartmentId)
at Microsoft.Expression.DesignHost.Isolation.Remoting.ThreadMarshaler.MarshalIn(IRemoteObject targetObject, Action action)
at Microsoft.Expression.DesignHost.Isolation.Remoting.RemoteDesignerService.Microsoft.Expression.DesignHost.Isolation.Remoting.IRemoteDesignerService.Initialize()
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 [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.Expression.DesignHost.Isolation.Remoting.IRemoteDesignerService.Initialize()
at Microsoft.Expression.DesignHost.Isolation.Remoting.LocalDesignerService.b_a(IRemoteDesignerService d)
at Microsoft.Expression.DesignHost.Isolation.Remoting.ThreadMarshaler.<>c_DisplayClass1`1.b__0()
at Microsoft.Expression.DesignHost.Isolation.Remoting.STAMarshaler.Call.InvokeWorker()
System.InvalidCastException
Return argument has an invalid type.
at Microsoft.Expression.DesignHost.Isolation.Remoting.STAMarshaler.WaitForCompletion(NestedCallContext nestedCallContext, BlockingCall call, WaitHandle timeoutSignal)
at Microsoft.Expression.DesignHost.Isolation.Remoting.STAMarshaler.MarshalOutSynchronous(Action action, Int32 targetApartmentId, WaitHandle aborted, WaitHandle timeoutSignal)
at Microsoft.Expression.DesignHost.Isolation.Remoting.STAMarshaler.MarshalOut(Action action, Int32 targetApartmentId, WaitHandle aborted, CallSynchronizationMode syncMode, WaitHandle timeoutSignal)
at Microsoft.Expression.DesignHost.Isolation.Remoting.ThreadMarshaler.MarshalOut[TValue](RemoteHandle1 targetObject, Action action, CallSynchronizationMode syncMode)
at Microsoft.Expression.DesignHost.Isolation.Remoting.ThreadMarshaler.MarshalOut[TResult,TValue](RemoteHandle1 targetObject, Func`2 func, CallSynchronizationMode syncMode)
at Microsoft.Expression.DesignHost.Isolation.Remoting.LocalHostProject.Microsoft.Expression.DesignHost.IHostProject.get_TargetAssemblyPath()
at Microsoft.Expression.DesignSurface.DesignerService.GetComponentName(IHostProject project)
at Microsoft.Expression.DesignSurface.DesignerService.InitializeWindowsRuntimeContext(IHostProject contextProject, IHostAppPackage appPackage)
at Microsoft.Expression.DesignSurface.DesignerService.InitializePrimaryProject()
at Microsoft.Expression.DesignSurface.DesignerService.Initialize()
at Microsoft.Expression.DesignHost.Isolation.Remoting.RemoteDesignerService.b__0()
at Microsoft.Expression.DesignHost.Isolation.Remoting.STAMarshaler.Call.InvokeWorker()
System.InvalidCastException
Return argument has an invalid type.
at System.Runtime.Remoting.Proxies.RealProxy.ValidateReturnArg(Object arg, Type paramType)
at System.Runtime.Remoting.Proxies.RealProxy.PropagateOutParameters(IMessage msg, Object[] outArgs, Object returnValue)
at System.Runtime.Remoting.Proxies.RealProxy.HandleReturnMessage(IMessage reqMsg, IMessage retMsg)
at System.Runtime.Remoting.Proxies.RealProxy.PrivateInvoke(MessageData& msgData, Int32 type)
at Microsoft.Expression.DesignHost.Isolation.Remoting.IRemoteHostProject.get_TargetAssemblyPath()
at Microsoft.Expression.DesignHost.Isolation.Remoting.LocalHostProject.b_1a(IRemoteHostProject p)
at Microsoft.Expression.DesignHost.Isolation.Remoting.ThreadMarshaler.<>c_DisplayClass4`2.b__3()
at Microsoft.Expression.DesignHost.Isolation.Remoting.STAMarshaler.Call.InvokeWorker()
Has anyone faced this before/know what is up? Many thanks
Posted by Microsoft on 11.09.2012 at 14:05
We have seen similar stack traces from other users. Are you
referencing a .Net 2.0 assembly in your project? Unfortunately
designer is not able to handled types from older (.Net 2.0) assemblies
and that is causing the designer to crash. Can you please try
removing any .Net 2.0 assemblies and see if that fixes it.
The problem are linked projects targeted .Net 2.0! Who would know. So convenient to work when the designer is not crashing all the time.
http://social.msdn.microsoft.com/Forums/en-US/vswpfdesigner/thread/f4af2020-ed43-4139-9dc9-759ce3b38377/

Cannot access a disposed object - wcf client

I have a WCF client that I'm having problems with.
From time to time I am getting this exception: Cannot access a disposed object. This is how I am opening the connection:
private static LeverateCrmServiceClient crm = null;
public static CrmServiceClient Get(string crmCertificateName)
{
if (crm != null)
{
crm.Close();
}
try
{
crm = new LeverateCrmServiceClient("CrmServiceEndpoint");
crm.ClientCredentials.ClientCertificate.SetCertificate(
StoreLocation.LocalMachine,
StoreName.My,
X509FindType.FindBySubjectName,
crmCertificateName);
}
catch (Exception e)
{
log.Error("Cannot access CRM ", e);
throw;
}
return crm;
}
As you can see, I am closing and reopening the connection each time.
What do you think might be the problem?
Stack:
System.ServiceModel.Security.MessageSecurityException: Message security verification failed. ---> System.ObjectDisposedException: Cannot access a disposed object.
Object name: 'System.ServiceModel.Security.SymmetricSecurityProtocol'.
at System.ServiceModel.Channels.CommunicationObject.ThrowIfClosedOrNotOpen()
at System.ServiceModel.Security.MessageSecurityProtocol.VerifyIncomingMessage(Message& message, TimeSpan timeout, SecurityProtocolCorrelationState[] correlationStates)
--- End of inner exception stack trace ---
Server stack trace:
at System.ServiceModel.Security.MessageSecurityProtocol.VerifyIncomingMessage(Message& message, TimeSpan timeout, SecurityProtocolCorrelationState[] correlationStates)
at System.ServiceModel.Channels.SecurityChannelFactory`1.SecurityRequestChannel.ProcessReply(Message reply, SecurityProtocolCorrelationState correlationState, TimeSpan timeout)
at System.ServiceModel.Channels.SecurityChannelFactory`1.SecurityRequestChannel.Request(Message message, TimeSpan timeout)
at System.ServiceModel.Channels.ServiceChannel.Call(String action, Boolean oneway, ProxyOperationRuntime operation, Object[] ins, Object[] outs, TimeSpan timeout)
at System.ServiceModel.Channels.ServiceChannelProxy.InvokeService(IMethodCallMessage methodCall, ProxyOperationRuntime operation)
at System.ServiceModel.Channels.ServiceChannelProxy.Invoke(IMessage message)
Exception rethrown at [0]:
at System.Runtime.Remoting.Proxies.RealProxy.HandleReturnMessage(IMessage reqMsg, IMessage retMsg)
at System.Runtime.Remoting.Proxies.RealProxy.PrivateInvoke(MessageData& msgData, Int32 type)
at Externals.CrmService.ICrmService.GetTradingPlatformAccountDetails(Guid ownerUserId, String organizationName, String businessUnitName, Guid tradingPlatformAccountId)
at MyAppName.Models.ActionsMetadata.Trader.BuildTrader(Guid tradingPlatformAccountId) in C:\Users\X\Documents\Visual Studio 2010\Projects\MyAppName\MyAppName\Models\ActionsMetadata\Trader.cs:line 120
at MyAppName.Models.ActionsMetadata.Trader.Login(String accountNumber, String password) in C:\Users\X\Documents\Visual Studio 2010\Projects\MyAppName\MyAppName\Models\ActionsMetadata\Trader.cs:line 48
at MyAppName.Models.ActionsMetadata.Handlers.LoginHandler.Handle(StepHandlerWrapper wrapper) in C:\Users\X\Documents\Visual Studio 2010\Projects\MyAppName\MyAppName\Models\ActionsMetadata\Handlers\LoginHandler.cs:line 23
at MyAppName.Models.ActionsMetadata.Handlers.HandlerInvoker.Invoke(IAction brokerAction, ActionStep actionStep, Dictionary`2 stepValues, HttpContext httpContext, BaseStepDataModel model) in C:\Users\X\Documents\Visual Studio 2010\Projects\MyAppName\MyAppName\Models\ActionsMetadata\Handlers\StepServerInoker.cs:line 42
at MyAppName.Controllers.LoginController.Login(String step) in C:\Users\X\Documents\Visual Studio 2010\Projects\MyAppName\MyAppName\Controllers\LoginController.cs:line 35
at lambda_method(Closure , ControllerBase , Object[] )
at System.Web.Mvc.ReflectedActionDescriptor.Execute(ControllerContext controllerContext, IDictionary`2 parameters)
at System.Web.Mvc.ControllerActionInvoker.InvokeActionMethod(ControllerContext controllerContext, ActionDescriptor actionDescriptor, IDictionary`2 parameters)
at System.Web.Mvc.ControllerActionInvoker.<>c__DisplayClass15.<InvokeActionMethodWithFilters>b__12()
at System.Web.Mvc.ControllerActionInvoker.InvokeActionMethodFilter(IActionFilter filter, ActionExecutingContext preContext, Func`1 continuation)
at System.Web.Mvc.ControllerActionInvoker.InvokeActionMethodWithFilters(ControllerContext controllerContext, IList`1 filters, ActionDescriptor actionDescriptor, IDictionary`2 parameters)
at System.Web.Mvc.ControllerActionInvoker.InvokeAction(ControllerContext controllerContext, String actionName)
From that stack trace, I assume you have an ASP.NET MVC application with some code that calls that Get method to get a CrmServiceClient object, and then proceeds to call various methods on that CrmServiceClient object. For example, part of the login process does this.
The way your Get method works is, each time it is called, it will first close the CrmServiceClient object that it returned previously (regardless of whether or not it is still being used) then create and return a new one.
Imagine two users attempt to log in to your application at almost the same time - within milliseconds of each other. The thread handling the first user's login calls Get and gets its CrmServiceClient object, then a millisecond later the thread handling the second user's login calls Get, which causes the first thread's CrmServiceClient object to be closed. However, the first thread is still running, and now when it attempts to call a method on it's CrmServiceClient object, it gets a System.ObjectDisposedException: Cannot access a disposed object.
"As you can see, I am closing and reopening the connection each time."
The code currently in your Get method is not a good way to achive this. You should instead make it the caller's responsibility to close (or dispose) the CrmServiceClient object, and you should perhaps rename your Get method to Open or Create to suggest this. Callers should use a using statement to ensure that the object is closed/disposed, regardless of any exceptions that occur:
using (CrmServiceClient client = CrmServiceFactory.Get("my-crm-certificate"))
{
client.Something();
client.GetTradingPlatformAccountDetails();
client.SomethingElse();
} // client is automatically closed at the end of the 'using' block

What is causing these SQL casting errors on my ASP.NET MVC/AJAX site? [Video showing problem]

I'm frustrated... my site has suddenly become very unstable. So much so that hitting refresh over and over will cause it to crash. To investigate, I turned off all error handling so I could see some YSOD's.
Instead of trying to write it all out, I made a video showing the issue. You can see it here on YouTube.
Here's a copy of the stacktrace:
[InvalidCastException: Specified cast is not valid.]
System.Data.Linq.SqlClient.SqlProvider.Execute(Expression query, QueryInfo queryInfo, IObjectReaderFactory factory, Object[] parentArgs, Object[] userArgs, ICompiledSubQuery[] subQueries, Object lastResult) +847
System.Data.Linq.SqlClient.SqlProvider.ExecuteAll(Expression query, QueryInfo[] queryInfos, IObjectReaderFactory factory, Object[] userArguments, ICompiledSubQuery[] subQueries) +113
System.Data.Linq.SqlClient.SqlProvider.System.Data.Linq.Provider.IProvider.Execute(Expression query) +344
System.Data.Linq.DataQuery`1.System.Linq.IQueryProvider.Execute(Expression expression) +23
System.Linq.Queryable.Count(IQueryable`1 source) +240
MvcPaging.PagedList`1.Initialize(IQueryable`1 source, Int32 index, Int32 pageSize, Nullable`1 totalCount) in C:\Users\BikGame\Desktop\src\MvcPaging\PagedList.cs:63
MvcPaging.PagedList`1..ctor(IQueryable`1 source, Int32 index, Int32 pageSize, Nullable`1 totalCount) in C:\Users\BikGame\Desktop\src\MvcPaging\PagedList.cs:25
MvcPaging.PagedList`1..ctor(IQueryable`1 source, Int32 index, Int32 pageSize) in C:\Users\BikGame\Desktop\src\MvcPaging\PagedList.cs:19
MvcPaging.PagingExtensions.ToPagedList(IQueryable`1 source, Int32 pageIndex, Int32 pageSize) in C:\Users\BikGame\Desktop\src\MvcPaging\PagingExtensions.cs:63
ApoAds.Controllers.HomeController.Index() in C:\Users\BikGame\Documents\Visual Studio 2008\Projects\APOAds-MultiBaseBiz\Controllers\HomeController.cs:22
lambda_method(ExecutionScope , ControllerBase , Object[] ) +39
System.Web.Mvc.ActionMethodDispatcher.Execute(ControllerBase controller, Object[] parameters) +17
System.Web.Mvc.ReflectedActionDescriptor.Execute(ControllerContext controllerContext, IDictionary`2 parameters) +178
System.Web.Mvc.ControllerActionInvoker.InvokeActionMethod(ControllerContext controllerContext, ActionDescriptor actionDescriptor, IDictionary`2 parameters) +24
System.Web.Mvc.<>c__DisplayClassa.<InvokeActionMethodWithFilters>b__7() +53
System.Web.Mvc.ControllerActionInvoker.InvokeActionMethodFilter(IActionFilter filter, ActionExecutingContext preContext, Func`1 continuation) +258
System.Web.Mvc.<>c__DisplayClassc.<InvokeActionMethodWithFilters>b__9() +20
System.Web.Mvc.ControllerActionInvoker.InvokeActionMethodFilter(IActionFilter filter, ActionExecutingContext preContext, Func`1 continuation) +258
System.Web.Mvc.<>c__DisplayClassc.<InvokeActionMethodWithFilters>b__9() +20
System.Web.Mvc.ControllerActionInvoker.InvokeActionMethodWithFilters(ControllerContext controllerContext, IList`1 filters, ActionDescriptor actionDescriptor, IDictionary`2 parameters) +193
System.Web.Mvc.ControllerActionInvoker.InvokeAction(ControllerContext controllerContext, String actionName) +382
System.Web.Mvc.Controller.ExecuteCore() +123
System.Web.Mvc.ControllerBase.Execute(RequestContext requestContext) +23
System.Web.Mvc.ControllerBase.System.Web.Mvc.IController.Execute(RequestContext requestContext) +7
System.Web.Mvc.MvcHandler.ProcessRequest(HttpContextBase httpContext) +144
System.Web.Mvc.MvcHandler.ProcessRequest(HttpContext httpContext) +54
System.Web.Mvc.MvcHandler.System.Web.IHttpHandler.ProcessRequest(HttpContext httpContext) +7
System.Web.CallHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute() +181
System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously) +75
On the page that's trying to load there are two ajax calls to views that hit the database, render a table and return html. Portions of the menu at the top of the site are pulled from the database and then cached to prevent multiple return trips. Hosting is on IIS6 in a medium trust, shared environment.
Crazy how it works and then stops working for 3-4 minutes and then works again... perhaps a sql connection hanging and then timing out after a few minutes?
Any ideas would be very greatly appreciated! Thanks in advance!
Update: added data access code
I'm using LINQ to SQL in a repository pattern. Here's a query that one of the AJAX calls is using.
public IQueryable<Ad> FindAdsPerBase(string baseName, AdStatus status)
{
return (from ad in _db.Ads
join b in _db.AdBases on ad.AdID equals b.AdID
where b.MilBase.BaseName.ToLower() == baseName.ToLower() && ad.Status == (byte)status
select ad).Distinct().OrderByDescending(x => x.DateEntered);
}
and it is called in the controller like so:
var ads = _db.FindAdsPerBase(MilBase, AdStatus.Active).Take(11);
You haven't given nearly enough information to troubleshoot, and (no offense) I'm not heading over to YouTube to watch a video. Here are some general troubleshooting steps I'd take and questions I'd ask myself:
When it fails, is it always the exact same exception? Or does it vary? If the same exception is always thrown then there might be a defect in your logic somewhere. If you get totally random exceptions then you may have a hardware or infrastructure issue.
First thing to do when you get LINQ to SQL exceptions is hook up SQL Profiler to see the exact query statement being sent to the server. Copy/paste that into SQL Management Studio and run it by hand. Look at the results and compare them to the data types of the object you're loading: is the query mapping an empty value to a non-nullable field? Maybe a query column is being mapped to a property of a different type?
If it works for 3-4 minutes, then stops for 3-4 minutes, then works again, look for any time-specific code in your project. Are you doing any caching? Maybe the issue is related to the behavior that occurs when the cache is stale versus when it's not stale, or vice versa. Maybe you have a date/time calculation that overflows or does something funky for certain inputs?
Hook up a debugger and have it catch the exception. Then walk up the stack trace and look at the program state during a failure. Compare it to the program state when the app is working correctly. Anything stand out?
You may have changed something in your database (like datatype of a column) without remembering to re-create your LINQ classes. Thus LINQ to SQL may be causing that casting exception.

Categories

Resources