Can I call Node.js function from MsTest? - edge.js

I was wanting to create unit tests around my .NET library that hosts Edge.js to make node.js function calls.
It fails with an System.AccessViolationException error and I went on to reproduce the issue by trying to use Edge in a unit test.
Will I be able to do this, or am I not understanding the current limitations?
To reproduce, a simple unit test
using System.Threading.Tasks;
using EdgeJs;
using Microsoft.VisualStudio.TestTools.UnitTesting;
namespace UnitTest {
[TestClass]
public class UnitTest1 {
[TestMethod]
public void TestMethod1() {
Start().Wait();
}
public static async Task<object> Start() {
var func = Edge.Func(#"
return function (data, cb) {
cb(null, 'Node.js ' + process.version + ' welcomes ' + data);
}
");
return await func("MSTEST");
}
}
}
and MSTEST hangs and the reported message to the output shows
System.AccessViolationException: Attempted to read or write protected memory. This is often an indication that other memory is corrupt.
at _atexit_helper(IntPtr func, UInt32* __pexit_list_size, (fnptr)** __ponexitend_e, (fnptr)** __ponexitbegin_e)
at _atexit_m(IntPtr func)
at ClrFunc.Initialize(Local<v8::Function>* , Func`2 func)
at ClrFunc.Initialize(FunctionCallbackInfo<v8::Value>* info)
at initializeClrFunc(FunctionCallbackInfo<v8::Value>* info)
at Nan.imp.?A0x8dda69af.FunctionCallbackWrapper(FunctionCallbackInfo<v8::Value>* info)
at EdgeJs.Edge.NodeStartx86(Int32 argc, String[] argv)
at EdgeJs.Edge.<>c__DisplayClass11_0.<Func>b__0()
at System.Threading.ThreadHelper.ThreadStart_Context(Object state)
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 System.Threading.ThreadHelper.ThreadStart()
at _atexit_helper(IntPtr func, UInt32* __pexit_list_size, (fnptr)** __ponexitend_e, (fnptr)** __ponexitbegin_e)
at _atexit_m(IntPtr func)
at ClrFunc.Initialize(Local<v8::Function>* , Func`2 func)
at ClrFunc.Initialize(FunctionCallbackInfo<v8::Value>* info)
at initializeClrFunc(FunctionCallbackInfo<v8::Value>* info)
at Nan.imp.?A0x8dda69af.FunctionCallbackWrapper(FunctionCallbackInfo<v8::Value>* info)
at EdgeJs.Edge.NodeStartx86(Int32 argc, String[] argv)
at EdgeJs.Edge.<>c__DisplayClass11_0.<Func>b__0()
at System.Threading.ThreadHelper.ThreadStart_Context(Object state)
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 System.Threading.ThreadHelper.ThreadStart()

Related

ConnectAsync trying to use with tcpclient.connected

I'm using following code to try to connect to a system, but with handling a timeout. When there is no connection, tcpClient.Connected gives a NullReferenceException after a while
If tcpClient.ConnectAsync(IP, Port).Wait(1000) = False Then
'Messagebox error
End If
If tcpClient.Connected Then
.....
End if
Stack trace
bij System.Net.Sockets.TcpClient.get_Connected()
bij directory\System.vb:regel 47
bij System.Threading.ThreadHelper.ThreadStart_Context(Object state)
bij System.Threading.ExecutionContext.RunInternal(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx)
bij System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx)
bij System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state)

An Xaml Error: The property "Value" was not found in type "WindowsUIXamlBindingWrapper"

I'm coding a Windows 8.1 app that use Hub control.
this project also use mvvmLight.
DataContext Class like this
public class UserInfoViewModel : ViewModelBase
{
private UserInfo userInfo;
public UserInfo User
{
get { return userInfo; }
set
{
if (value == userInfo)
return;
userInfo = value;
RaisePropertyChanged("User");
}
}
public UserInfoViewModel()
{
User = new UserInfo()
{
NikeName = "User",
ProfileImage = "ms-appx:///image/test.jpg"
};
}
}
When I use HubSection.ContentTemplate like this,
it's seems something wrong with the binding
<HubSection.ContentTemplate>
<DataTemplate>
<ContentControl>
<StackPanel
DataContext="{Binding User, Source={StaticResource Locator}}">
</StackPanel>
</ContentControl>
</DataTemplate>
</HubSection.ContentTemplate>
There will have an XAML error
The property "Value" was not found in type "WindowsUIXamlBindingWrapper"
System.ArgumentNullException
Value cannot be null.
Parameter name: key
at System.Collections.Generic.Dictionary`2.Remove(TKey key)
at Microsoft.VisualStudio.DesignTools.Utility.WindowsRuntimeService.WindowsRuntimeContext.UnregisterDynamicType(Type dynamicType)
at Microsoft.VisualStudio.DesignTools.Utility.WindowsRuntimeService.UnregisterDynamicType(Type dynamicType)
at Microsoft.VisualStudio.DesignTools.XamlDesigner.Metadata.MockTypes.MockTypeGenerator.Reset()
at Microsoft.VisualStudio.DesignTools.XamlDesigner.Metadata.XamlProjectMetadata.OnTypesInvalidatedInternal(IList`1 invalidatedAssemblies)
at Microsoft.VisualStudio.DesignTools.Platform.Metadata.TypeResolver.OnAssemblyCollectionChanged(NotifyCollectionChangedEventArgs e)
at Microsoft.VisualStudio.DesignTools.XamlDesigner.Metadata.XamlProjectMetadata.OnAssemblyCollectionChanged(NotifyCollectionChangedEventArgs e)
at Microsoft.VisualStudio.DesignTools.Designer.Project.ProjectAssemblyCollection.FireChangedEvent(NotifyCollectionChangedEventArgs eventArguments)
at Microsoft.VisualStudio.DesignTools.Designer.Project.ProjectAssemblyCollection.AssemblyCollection_EnumerationChanged(Object sender, EnumerationChangedEventArgs`1 e)
at System.EventHandler`1.Invoke(Object sender, TEventArgs e)
at Microsoft.VisualStudio.DesignTools.Utility.Collections.NotifyingCollectionBase`1.EventInvoker(EnumerationChangedEventArgs`1 eventArguments)
at Microsoft.VisualStudio.DesignTools.Utility.Events.SuspendingEventManager`1.ForwardEvents()
at Microsoft.VisualStudio.DesignTools.Utility.Events.Suspender.SuspendDisposer.Dispose(Boolean disposing)
at Microsoft.VisualStudio.DesignTools.Utility.Events.Suspender.SuspendDisposer.Dispose()
at Microsoft.VisualStudio.DesignTools.Designer.Assemblies.AssemblyCollection.AssemblyService_AssembliesUpdated(Object sender, EventArgs`1 e)
at Microsoft.VisualStudio.DesignTools.Designer.Assemblies.AssemblyService.OnAssembliesUpdated(IEnumerable`1 assemblyInformation)
at Microsoft.VisualStudio.DesignTools.Designer.Assemblies.AssemblyService.RefreshDesignerCaches()
at Microsoft.VisualStudio.DesignTools.Utility.WindowsRuntimeService.SetIterationContext(String[] paths)
at Microsoft.VisualStudio.DesignTools.Utility.WindowsRuntimeService.SynchronizeDesignerContext()
at Microsoft.VisualStudio.DesignTools.Utility.WindowsRuntimeService.ProcessShadowCopyResults(IEnumerable`1 results)
at Microsoft.VisualStudio.DesignTools.Designer.Assemblies.AssemblyService.FlushShadowCopyUpdateQueue()
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.DispatcherOperation.InvokeImpl()
at System.Windows.Threading.DispatcherOperation.InvokeInSecurityContext(Object state)
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 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 System.Windows.Threading.Dispatcher.PushFrameImpl(DispatcherFrame frame)
at System.Windows.Threading.Dispatcher.PushFrame(DispatcherFrame frame)
at System.Windows.Application.RunDispatcher(Object ignore)
at System.Windows.Application.RunInternal(Window window)
at System.Windows.Application.Run(Window window)
at Microsoft.VisualStudio.DesignTools.DesignerContract.Isolation.DesignerProcess.RunApplication()
at Microsoft.VisualStudio.DesignTools.DesignerContract.Isolation.DesignerProcess.DesignProcessViewProvider.AppContainerDesignerProcessRun(String[] activationContextArgs)
at Microsoft.VisualStudio.DesignTools.DesignerContract.Isolation.DesignerProcess.DesignProcessViewProvider.<>c__DisplayClass3_0.<applicationView_Activated>b__0()
at System.Threading.ThreadHelper.ThreadStart_Context(Object state)
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 System.Threading.ThreadHelper.ThreadStart()

RavenDB - EmbeddableDocumentStore already disposed or NRE

This question is about creating a single instance of the Raven document store in the lifetime of a ASP.Net MVC application and subsequently using a new IDocumentSession per request to serve the client with. I believe to have followed the recommended procedure described at http://ravendb.net/kb/3/using-ravendb-in-an-asp-net-mvc-website I'm still experiencing errors once the site is deployed.
My code looks as follows. The HepApp class contains the document store and is referenced by the application:
internal class HepApp
{
internal static readonly Object padlock = new object();
private static IDocumentStore _DB;
internal IDocumentStore DB
{
get
{
if (_DB == null)
{
lock (padlock)
{
if (_DB == null)
{
_DB = new EmbeddableDocumentStore().Initialize();
return _DB;
}
}
}
return _DB;
}
}
public IDocumentSession GetSession()
{
return DB.OpenSession();
}
}
My MVC Controller:
public class HomeController : Controller
{
IDocumentSession RavenSession;
public HomeController()
{
}
protected void Init()
{
RavenSession = MvcApplication.HepApp.GetSession();
}
protected override void OnActionExecuting(ActionExecutingContext filterContext)
{
base.OnActionExecuting(filterContext);
Init();
}
The application class Global.asax binds to:
public class MvcApplication : System.Web.HttpApplication
{
static readonly Object padlock = new object();
static HepApp _HepApp;
internal static HepApp HepApp
{
get
{
if(_HepApp == null)
{
lock(padlock)
{
if(_HepApp == null)
{
_HepApp = new HepApp();
}
}
}
return _HepApp;
}
}
When the application starts the document store should be initialized and live for the remainder of the application's lifetime. For each request a new Session object is created. At least, that's the idea. Instead null reference errors occur in OnActionExecuting (though I suspect the HomeController.Init method but it doesn't appear on the stack) or the EmbeddableDocumentStore object is reported als already disposed. Confusingly, these errors only crop up after the application has been running for a while which might suggest it's an app pool recycle issue
EDIT:
The errors differ but all seem to indicate a problem with the instantiation of the database store :
[EsentFileAccessDeniedException: Cannot access file, the file is locked or in use]
[InvalidOperationException: Could not write to location: \192.168.0.100\localuser\x\App_Data/Raven. Make sure you have read/write permissions for this path.]
System.InvalidOperationException: Could not write to location: \192.168.0.100\localuser\x\App_Data/Raven. Make sure you have read/write permissions for this path. ---> Microsoft.Isam.Esent.Interop.EsentFileAccessDeniedException: Cannot access file, the file is locked or in use
at Microsoft.Isam.Esent.Interop.Api.Check(Int32 err)
at Microsoft.Isam.Esent.Interop.Api.JetInit(JET_INSTANCE& instance)
at Raven.Storage.Esent.TransactionalStorage.Initialize(IUuidGenerator uuidGenerator, OrderedPartCollection1 documentCodecs)
--- End of inner exception stack trace ---
at Raven.Storage.Esent.TransactionalStorage.Initialize(IUuidGenerator uuidGenerator, OrderedPartCollection1 documentCodecs)
at Raven.Database.DocumentDatabase..ctor(InMemoryRavenConfiguration configuration, TransportState transportState)
at Raven.Client.Embedded.EmbeddableDocumentStore.InitializeInternal()
at Raven.Client.Document.DocumentStore.Initialize()
at HEPlaceHolder.HepApp.get_DB() in e:\projects\HEPlaceHolder\HEPlaceHolder\Logic\HepApp.cs:line 27
at HEPlaceHolder.Controllers.HomeController.OnActionExecuting(ActionExecutingContext filterContext) in e:\projects\HEPlaceHolder\HEPlaceHolder\Controllers\HomeController.cs:line 31
at System.Web.Mvc.Controller.System.Web.Mvc.IActionFilter.OnActionExecuting(ActionExecutingContext filterContext)
at System.Web.Mvc.Async.AsyncControllerActionInvoker.AsyncInvocationWithFilters.InvokeActionMethodFilterAsynchronouslyRecursive(Int32 filterIndex)
at System.Web.Mvc.Async.AsyncControllerActionInvoker.<>c__DisplayClass33.b__31(AsyncCallback asyncCallback, Object asyncState)
at System.Web.Mvc.Async.AsyncResultWrapper.WrappedAsyncResult1.CallBeginDelegate(AsyncCallback callback, Object callbackState)
at System.Web.Mvc.Async.AsyncResultWrapper.WrappedAsyncResultBase1.Begin(AsyncCallback callback, Object state, Int32 timeout)
at System.Web.Mvc.Async.AsyncControllerActionInvoker.BeginInvokeActionMethodWithFilters(ControllerContext controllerContext, IList1 filters, ActionDescriptor actionDescriptor, IDictionary2 parameters, AsyncCallback callback, Object state)
at System.Web.Mvc.Async.AsyncControllerActionInvoker.<>c__DisplayClass21.b__19(AsyncCallback asyncCallback, Object asyncState)
at System.Web.Mvc.Async.AsyncResultWrapper.WrappedAsyncResult1.CallBeginDelegate(AsyncCallback callback, Object callbackState)
at System.Web.Mvc.Async.AsyncResultWrapper.WrappedAsyncResultBase1.Begin(AsyncCallback callback, Object state, Int32 timeout)
at System.Web.Mvc.Async.AsyncControllerActionInvoker.BeginInvokeAction(ControllerContext controllerContext, String actionName, AsyncCallback callback, Object state)
at System.Web.Mvc.Controller.b__1c(AsyncCallback asyncCallback, Object asyncState, ExecuteCoreState innerState)
at System.Web.Mvc.Async.AsyncResultWrapper.WrappedAsyncVoid1.CallBeginDelegate(AsyncCallback callback, Object callbackState)
at System.Web.Mvc.Async.AsyncResultWrapper.WrappedAsyncResultBase1.Begin(AsyncCallback callback, Object state, Int32 timeout)
at System.Web.Mvc.Controller.BeginExecuteCore(AsyncCallback callback, Object state)
at System.Web.Mvc.Controller.b__14(AsyncCallback asyncCallback, Object callbackState, Controller controller)
at System.Web.Mvc.Async.AsyncResultWrapper.WrappedAsyncVoid1.CallBeginDelegate(AsyncCallback callback, Object callbackState)
at System.Web.Mvc.Async.AsyncResultWrapper.WrappedAsyncResultBase1.Begin(AsyncCallback callback, Object state, Int32 timeout)
at System.Web.Mvc.Controller.BeginExecute(RequestContext requestContext, AsyncCallback callback, Object state)
at System.Web.Mvc.Controller.System.Web.Mvc.Async.IAsyncController.BeginExecute(RequestContext requestContext, AsyncCallback callback, Object state)
at System.Web.Mvc.MvcHandler.b__4(AsyncCallback asyncCallback, Object asyncState, ProcessRequestState innerState)
at System.Web.Mvc.Async.AsyncResultWrapper.WrappedAsyncVoid1.CallBeginDelegate(AsyncCallback callback, Object callbackState)
at System.Web.Mvc.Async.AsyncResultWrapper.WrappedAsyncResultBase1.Begin(AsyncCallback callback, Object state, Int32 timeout)
at System.Web.Mvc.MvcHandler.BeginProcessRequest(HttpContextBase httpContext, AsyncCallback callback, Object state)
at System.Web.Mvc.MvcHandler.BeginProcessRequest(HttpContext httpContext, AsyncCallback callback, Object state)
at System.Web.Mvc.MvcHandler.System.Web.IHttpAsyncHandler.BeginProcessRequest(HttpContext context, AsyncCallback cb, Object extraData)
at System.Web.HttpApplication.CallHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute()
at System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously)
[ObjectDisposedException: The document store has already been disposed and cannot be used
Object name: 'EmbeddableDocumentStore'.]
Raven.Client.DocumentStoreBase.EnsureNotClosed() +82
System.Web.Mvc.Async.WrappedAsyncResultBase`1.Begin(AsyncCallback callback, Object state, Int32 timeout) +128
[NullReferenceException: Object reference not set to an instance of an object.]
HEPlaceHolder.Controllers.HomeController.OnActionExecuting(ActionExecutingContext filterContext) in e:\projects\HEPlaceHolder\HEPlaceHolder\Controllers\HomeController.cs:31
System.Web.Mvc.Controller.System.Web.Mvc.IActionFilter.OnActionExecuting(ActionExecutingContext filterContext) +10
System.InvalidOperationException: Could not open transactional storage: \192.168.0.100\localuser\x\App_Data/Raven\Data ---> Microsoft.Isam.Esent.Interop.EsentTempPathInUseException: Temp path already used by another database instance
at Microsoft.Isam.Esent.Interop.Api.Check(Int32 err)
at Microsoft.Isam.Esent.Interop.Api.JetInit(JET_INSTANCE& instance)
at Raven.Storage.Esent.TransactionalStorage.Initialize(IUuidGenerator uuidGenerator, OrderedPartCollection1 documentCodecs)
--- End of inner exception stack trace ---
at Raven.Storage.Esent.TransactionalStorage.Initialize(IUuidGenerator uuidGenerator, OrderedPartCollection1 documentCodecs)
at Raven.Database.DocumentDatabase..ctor(InMemoryRavenConfiguration configuration, TransportState transportState)
at Raven.Client.Embedded.EmbeddableDocumentStore.InitializeInternal()
at Raven.Client.Document.DocumentStore.Initialize()
at HEPlaceHolder.HepApp.get_DB() in e:\projects\HEPlaceHolder\HEPlaceHolder\Logic\HepApp.cs:line 27
at HEPlaceHolder.Controllers.HomeController.OnActionExecuting(ActionExecutingContext filterContext) in e:\projects\HEPlaceHolder\HEPlaceHolder\Controllers\HomeController.cs:line 31
at System.Web.Mvc.Controller.System.Web.Mvc.IActionFilter.OnActionExecuting(ActionExecutingContext filterContext)
at System.Web.Mvc.Async.AsyncControllerActionInvoker.AsyncInvocationWithFilters.InvokeActionMethodFilterAsynchronouslyRecursive(Int32 filterIndex)
at System.Web.Mvc.Async.AsyncControllerActionInvoker.<>c__DisplayClass33.b__31(AsyncCallback asyncCallback, Object asyncState)
at System.Web.Mvc.Async.AsyncResultWrapper.WrappedAsyncResult1.CallBeginDelegate(AsyncCallback callback, Object callbackState)
at System.Web.Mvc.Async.AsyncResultWrapper.WrappedAsyncResultBase1.Begin(AsyncCallback callback, Object state, Int32 timeout)
at System.Web.Mvc.Async.AsyncControllerActionInvoker.BeginInvokeActionMethodWithFilters(ControllerContext controllerContext, IList1 filters, ActionDescriptor actionDescriptor, IDictionary2 parameters, AsyncCallback callback, Object state)
at System.Web.Mvc.Async.AsyncControllerActionInvoker.<>c__DisplayClass21.b__19(AsyncCallback asyncCallback, Object asyncState)
at System.Web.Mvc.Async.AsyncResultWrapper.WrappedAsyncResult1.CallBeginDelegate(AsyncCallback callback, Object callbackState)
at System.Web.Mvc.Async.AsyncResultWrapper.WrappedAsyncResultBase1.Begin(AsyncCallback callback, Object state, Int32 timeout)
at System.Web.Mvc.Async.AsyncControllerActionInvoker.BeginInvokeAction(ControllerContext controllerContext, String actionName, AsyncCallback callback, Object state)
at System.Web.Mvc.Controller.b__1c(AsyncCallback asyncCallback, Object asyncState, ExecuteCoreState innerState)
at System.Web.Mvc.Async.AsyncResultWrapper.WrappedAsyncVoid1.CallBeginDelegate(AsyncCallback callback, Object callbackState)
at System.Web.Mvc.Async.AsyncResultWrapper.WrappedAsyncResultBase1.Begin(AsyncCallback callback, Object state, Int32 timeout)
at System.Web.Mvc.Controller.BeginExecuteCore(AsyncCallback callback, Object state)
at System.Web.Mvc.Controller.b__14(AsyncCallback asyncCallback, Object callbackState, Controller controller)
at System.Web.Mvc.Async.AsyncResultWrapper.WrappedAsyncVoid1.CallBeginDelegate(AsyncCallback callback, Object callbackState)
at System.Web.Mvc.Async.AsyncResultWrapper.WrappedAsyncResultBase1.Begin(AsyncCallback callback, Object state, Int32 timeout)
at System.Web.Mvc.Controller.BeginExecute(RequestContext requestContext, AsyncCallback callback, Object state)
at System.Web.Mvc.Controller.System.Web.Mvc.Async.IAsyncController.BeginExecute(RequestContext requestContext, AsyncCallback callback, Object state)
at System.Web.Mvc.MvcHandler.b__4(AsyncCallback asyncCallback, Object asyncState, ProcessRequestState innerState)
at System.Web.Mvc.Async.AsyncResultWrapper.WrappedAsyncVoid1.CallBeginDelegate(AsyncCallback callback, Object callbackState)
at System.Web.Mvc.Async.AsyncResultWrapper.WrappedAsyncResultBase1.Begin(AsyncCallback callback, Object state, Int32 timeout)
at System.Web.Mvc.MvcHandler.BeginProcessRequest(HttpContextBase httpContext, AsyncCallback callback, Object state)
at System.Web.Mvc.MvcHandler.BeginProcessRequest(HttpContext httpContext, AsyncCallback callback, Object state)
at System.Web.Mvc.MvcHandler.System.Web.IHttpAsyncHandler.BeginProcessRequest(HttpContext context, AsyncCallback cb, Object extraData)
at System.Web.HttpApplication.CallHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute()
at System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously)
EDIT:
Whenever the bin folder is updated with a tweaked version to debug the problem the site will initially run ok, presumably because the application is reset.

Unable To Cast Object error when trying to populate ObjectListView control

I have downloaded the ObjectListView.dll and added it as a reference into my VB.NET application. I have added it to my toolbox and added an ObjectListView control to my form. However, when I try and populate it, I get the following error:
Unable to cast object of type 'System.Windows.Forms.ListViewItem' to
type 'BrightIdeasSoftware.OLVListItem'
My code snippet looks like so:
lsvOverdueCalls.Items.Add(tempDT.Rows(0)("id").ToString)
lsvOverdueCalls.Items(0).SubItems.Add(tempDT.Rows(0)("summary").ToString)
lsvOverdueCalls.Items(0).SubItems.Add(tempDT.Rows(0)("first_name").ToString)
Unsure if I'm doing something wrong. My applicaton is compiled under the full version of dot.net 4.5, not the client version as advised.
Any help appreciated.
Update
I noticed I get the following error in my debugger window but ONLY when moving the mouse over a ListViewItem:
A first chance exception of type 'System.InvalidCastException'
occurred in ObjectListView.dll System.Transactions Critical: 0 :
http://msdn.microsoft.com/TraceCodes/System/ActivityTracing/2004/07/Reliability/Exception/UnhandledUnhandled
exceptionDrakeMon2.0.vshost.exeSystem.InvalidCastException,
mscorlib, Version=4.0.0.0, Culture=neutral,
PublicKeyToken=b77a5c561934e089Unable to cast
object of type 'System.Windows.Forms.ListViewItem' to type
'BrightIdeasSoftware.OLVListItem'. at
BrightIdeasSoftware.ObjectListView.GetItem(Int32 index) at
BrightIdeasSoftware.ObjectListView.LowLevelHitTest(Int32 x, Int32 y)
at BrightIdeasSoftware.ObjectListView.OlvHitTest(Int32 x, Int32 y)
at BrightIdeasSoftware.ObjectListView.BuildCellEvent(CellEventArgs
args, Point location) at
BrightIdeasSoftware.ObjectListView.OnMouseMove(MouseEventArgs e) at
System.Windows.Forms.Control.WmMouseMove(Message& m) at
System.Windows.Forms.Control.WndProc(Message& m) at
System.Windows.Forms.ListView.WndProc(Message& m) at
BrightIdeasSoftware.ObjectListView.WndProc(Message& m) at
System.Windows.Forms.NativeWindow.DebuggableCallback(IntPtr hWnd,
Int32 msg, IntPtr wparam, IntPtr lparam) at
System.Windows.Forms.UnsafeNativeMethods.DispatchMessageW(MSG&
msg) at
System.Windows.Forms.Application.ComponentManager.System.Windows.Forms.UnsafeNativeMethods.IMsoComponentManager.FPushMessageLoop(IntPtr
dwComponentID, Int32 reason, Int32 pvLoopData) at
System.Windows.Forms.Application.ThreadContext.RunMessageLoopInner(Int32
reason, ApplicationContext context) at
System.Windows.Forms.Application.ThreadContext.RunMessageLoop(Int32
reason, ApplicationContext context) at
System.Windows.Forms.Form.ShowDialog(IWin32Window owner) at
DrakeMon2.frmNewDashboard.ToolStripMenuItem2_Click(Object sender,
EventArgs e) in C:\Dropbox\VS Projects\DrakeMon v2.0\DrakeMon
v2.0\frmNewDashboard.vb:line 986 at
System.Windows.Forms.ToolStripMenuItem.OnClick(EventArgs e) at
System.Windows.Forms.ToolStripItem.HandleClick(EventArgs e) at
System.Windows.Forms.ToolStripItem.HandleMouseUp(MouseEventArgs e)
at System.Windows.Forms.ToolStrip.OnMouseUp(MouseEventArgs mea) at
System.Windows.Forms.ToolStripDropDown.OnMouseUp(MouseEventArgs mea)
at System.Windows.Forms.Control.WmMouseUp(Message& m,
MouseButtons button, Int32 clicks) at
System.Windows.Forms.Control.WndProc(Message& m) at
System.Windows.Forms.ToolStrip.WndProc(Message& m) at
System.Windows.Forms.ToolStripDropDown.WndProc(Message& m)
at System.Windows.Forms.NativeWindow.DebuggableCallback(IntPtr hWnd,
Int32 msg, IntPtr wparam, IntPtr lparam) at
System.Windows.Forms.UnsafeNativeMethods.DispatchMessageW(MSG&
msg) at
System.Windows.Forms.Application.ComponentManager.System.Windows.Forms.UnsafeNativeMethods.IMsoComponentManager.FPushMessageLoop(IntPtr
dwComponentID, Int32 reason, Int32 pvLoopData) at
System.Windows.Forms.Application.ThreadContext.RunMessageLoopInner(Int32
reason, ApplicationContext context) at
System.Windows.Forms.Application.ThreadContext.RunMessageLoop(Int32
reason, ApplicationContext context) at
Microsoft.VisualBasic.ApplicationServices.WindowsFormsApplicationBase.OnRun()
at
Microsoft.VisualBasic.ApplicationServices.WindowsFormsApplicationBase.DoApplicationModel()
at
Microsoft.VisualBasic.ApplicationServices.WindowsFormsApplicationBase.Run(String[]
commandLine) at DrakeMon2.My.MyApplication.Main(String[] Args) in
17d14f5c-a337-4978-8281-53493378c1071.vb:line 81 at
System.AppDomain._nExecuteAssembly(RuntimeAssembly assembly, String[]
args) at
System.Runtime.Hosting.ApplicationActivator.CreateInstance(ActivationContext
activationContext, String[] activationCustomData) at
Microsoft.VisualStudio.HostingProcess.HostProc.RunUsersAssemblyDebugInZone()
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
System.Threading.ThreadHelper.ThreadStart()System.InvalidCastException:
Unable to cast object of type 'System.Windows.Forms.ListViewItem' to
type 'BrightIdeasSoftware.OLVListItem'. at
BrightIdeasSoftware.ObjectListView.GetItem(Int32 index) at
BrightIdeasSoftware.ObjectListView.LowLevelHitTest(Int32 x, Int32 y)
at BrightIdeasSoftware.ObjectListView.OlvHitTest(Int32 x, Int32 y)
at BrightIdeasSoftware.ObjectListView.BuildCellEvent(CellEventArgs
args, Point location) at
BrightIdeasSoftware.ObjectListView.OnMouseMove(MouseEventArgs e) at
System.Windows.Forms.Control.WmMouseMove(Message& m) at
System.Windows.Forms.Control.WndProc(Message& m) at
System.Windows.Forms.ListView.WndProc(Message& m) at
BrightIdeasSoftware.ObjectListView.WndProc(Message& m) at
System.Windows.Forms.NativeWindow.DebuggableCallback(IntPtr hWnd,
Int32 msg, IntPtr wparam, IntPtr lparam) at
System.Windows.Forms.UnsafeNativeMethods.DispatchMessageW(MSG&
msg) at
System.Windows.Forms.Application.ComponentManager.System.Windows.Forms.UnsafeNativeMethods.IMsoComponentManager.FPushMessageLoop(IntPtr
dwComponentID, Int32 reason, Int32 pvLoopData) at
System.Windows.Forms.Application.ThreadContext.RunMessageLoopInner(Int32
reason, ApplicationContext context) at
System.Windows.Forms.Application.ThreadContext.RunMessageLoop(Int32
reason, ApplicationContext context) at
System.Windows.Forms.Form.ShowDialog(IWin32Window owner) at
DrakeMon2.frmNewDashboard.ToolStripMenuItem2_Click(Object sender,
EventArgs e) in C:\Dropbox\VS Projects\DrakeMon v2.0\DrakeMon
v2.0\frmNewDashboard.vb:line 986 at
System.Windows.Forms.ToolStripMenuItem.OnClick(EventArgs e) at
System.Windows.Forms.ToolStripItem.HandleClick(EventArgs e) at
System.Windows.Forms.ToolStripItem.HandleMouseUp(MouseEventArgs e)
at System.Windows.Forms.ToolStrip.OnMouseUp(MouseEventArgs mea) at
System.Windows.Forms.ToolStripDropDown.OnMouseUp(MouseEventArgs mea)
at System.Windows.Forms.Control.WmMouseUp(Message& m,
MouseButtons button, Int32 clicks) at
System.Windows.Forms.Control.WndProc(Message& m) at
System.Windows.Forms.ToolStrip.WndProc(Message& m) at
System.Windows.Forms.ToolStripDropDown.WndProc(Message& m)
at System.Windows.Forms.NativeWindow.DebuggableCallback(IntPtr hWnd,
Int32 msg, IntPtr wparam, IntPtr lparam) at
System.Windows.Forms.UnsafeNativeMethods.DispatchMessageW(MSG&
msg) at
System.Windows.Forms.Application.ComponentManager.System.Windows.Forms.UnsafeNativeMethods.IMsoComponentManager.FPushMessageLoop(IntPtr
dwComponentID, Int32 reason, Int32 pvLoopData) at
System.Windows.Forms.Application.ThreadContext.RunMessageLoopInner(Int32
reason, ApplicationContext context) at
System.Windows.Forms.Application.ThreadContext.RunMessageLoop(Int32
reason, ApplicationContext context) at
Microsoft.VisualBasic.ApplicationServices.WindowsFormsApplicationBase.OnRun()
at
Microsoft.VisualBasic.ApplicationServices.WindowsFormsApplicationBase.DoApplicationModel()
at
Microsoft.VisualBasic.ApplicationServices.WindowsFormsApplicationBase.Run(String[]
commandLine) at DrakeMon2.My.MyApplication.Main(String[] Args) in
17d14f5c-a337-4978-8281-53493378c1071.vb:line 81 at
System.AppDomain._nExecuteAssembly(RuntimeAssembly assembly, String[]
args) at
System.Runtime.Hosting.ApplicationActivator.CreateInstance(ActivationContext
activationContext, String[] activationCustomData) at
Microsoft.VisualStudio.HostingProcess.HostProc.RunUsersAssemblyDebugInZone()
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
System.Threading.ThreadHelper.ThreadStart()
I'm assuming a threading issue, but I'm unsure why this control throws an error and a normal listview or even the BetterListView control doesn't. My form only contains this control and nothing else. And...like mentioned, it ONLY occurs if I try and move the mouse over a ListViewItem.
Thanks
You cannot do Add() on the ObjectListView like you do on a normal ListView. Instead, you need to call the SetObjects method on the ObjectListView instance, and pass it a list of items to add.
So in your case, create a List<Call> of the items to add (assuming your model is a Call class with id, summary and first_name fields, and then pass it on to the lsvOverdueCalls.SetObjects() like so.
var lstCalls = new List<Call>()
{
new Call() {
Id = tempDT.Rows(0)("id").ToString,
Summary = tempDT.Rows(0)("summary").ToString,
First_Name = tempDT.Rows(0)("first_name").ToString
}
};
lsvOverdueCalls.SetObjects(lstCalls);
And here's how your Call model should look like.
public class Call
{
public string Id { get; set; }
public string Summary { get; set; }
public string First_Name { get; set; }
}

Authorize attribute not working with Windows Authentication application

I have an MVC4 application whereby I have assigned roles to my user using a custom role provider so that when I check User.IsInRole against my User table it determines which links etc to display on screen in my _Layout.cshtml page. This is working on the Layout page in that the correct links are appearing.
However when I secure my Admin controller using the
[Authorize(Roles = "Admin")]
I am getting the following stack trace from an object not set to instance of an object error:
[NullReferenceException: Object reference not set to an instance of an object.]
System.Web.Mvc.AuthorizeAttribute.AuthorizeCore(HttpContextBase httpContext) +39
System.Web.Mvc.AuthorizeAttribute.OnAuthorization(AuthorizationContext filterContext) +159
System.Web.Mvc.ControllerActionInvoker.InvokeAuthorizationFilters(ControllerContext controllerContext, IList`1 filters, ActionDescriptor actionDescriptor) +96
System.Web.Mvc.Async.<>c__DisplayClass25.<BeginInvokeAction>b__1e(AsyncCallback asyncCallback, Object asyncState) +446
System.Web.Mvc.Async.WrappedAsyncResult`1.Begin(AsyncCallback callback, Object state, Int32 timeout) +130
System.Web.Mvc.Async.AsyncControllerActionInvoker.BeginInvokeAction(ControllerContext controllerContext, String actionName, AsyncCallback callback, Object state) +302
System.Web.Mvc.<>c__DisplayClass1d.<BeginExecuteCore>b__17(AsyncCallback asyncCallback, Object asyncState) +30
System.Web.Mvc.Async.WrappedAsyncResult`1.Begin(AsyncCallback callback, Object state, Int32 timeout) +130
System.Web.Mvc.Controller.BeginExecuteCore(AsyncCallback callback, Object state) +382
System.Web.Mvc.Async.WrappedAsyncResult`1.Begin(AsyncCallback callback, Object state, Int32 timeout) +130
System.Web.Mvc.Controller.BeginExecute(RequestContext requestContext, AsyncCallback callback, Object state) +317
System.Web.Mvc.Controller.System.Web.Mvc.Async.IAsyncController.BeginExecute(RequestContext requestContext, AsyncCallback callback, Object state) +15
System.Web.Mvc.<>c__DisplayClass8.<BeginProcessRequest>b__2(AsyncCallback asyncCallback, Object asyncState) +71
System.Web.Mvc.Async.WrappedAsyncResult`1.Begin(AsyncCallback callback, Object state, Int32 timeout) +130
System.Web.Mvc.MvcHandler.BeginProcessRequest(HttpContextBase httpContext, AsyncCallback callback, Object state) +249
System.Web.Mvc.MvcHandler.BeginProcessRequest(HttpContext httpContext, AsyncCallback callback, Object state) +50
System.Web.Mvc.MvcHandler.System.Web.IHttpAsyncHandler.BeginProcessRequest(HttpContext context, AsyncCallback cb, Object extraData) +16
System.Web.CallHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute() +301
System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously) +155
What exactly is in this Filter context? This works without any further configuration when I use ADFS or Forms based authentication but when using Windows based authentication I have had to do the following to get IsInRole method working:
this.UserName = System.Security.Principal.WindowsIdentity.GetCurrent().Name;
if (this.UserName.Contains("\\"))
{
string[] stringArray = this.UserName.Split(new Char[] { '\\' });
this.UserName = stringArray[1];
MyUser identity = userRepository.Get(u => u.Username == this.UserName).FirstOrDefault();
HttpContext.Current.User = identity;
}
Do I need to configure some other HttpContext proper in order for Authorize attribute to work in same manner as IsInRole method?
In the forms case, it could be anything but it is very common to implement a username password form with a lookup by username in a user table, based on the code presented it looks like the repository expects just a username, it just turns out that windows.identity.name returns domain\user. That's where the extra effort comes in to split into domain, user. example below:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
namespace MvcApplication6
{
public class DemoAuthAttribute : AuthorizeAttribute
{
// create a file like auth.cs in the mvc project
// called
// [DemoAuth("BAR")]
// as an attibute on a controller method
private string _role;
public DemoAuthAttribute(string role)
{
_role = role; // should be exapanded to handle more than one
}
protected override bool AuthorizeCore(HttpContextBase httpContext)
{
return httpContext.Request.IsAuthenticated && _role == "FOO";
// lookup the current user in database does the user have role as specificed by the attribute?
// if yes sucess if not fail.
}
public override void OnAuthorization(AuthorizationContext filterContext)
{
if (filterContext == null)
{
throw new ArgumentNullException("filterContext");
}
if (AuthorizeCore(filterContext.HttpContext))
{
// your custom logic here
string text = string.Format("<u><h5>Auth successfull.....</h5></u></br>");
filterContext.HttpContext.Response.Write(text);
}
else
{
// RedirectResult, etc.
string text = string.Format("<u><h5>Auth unsuccessfull.....</h5></u></br>");
filterContext.HttpContext.Response.Write(text);
}
}
}
}