Using Moq for an indexer property causes InvalidCastException from Castle - c#

When trying to use Moq to setup an indexer property, the underlying Castle library throws an InvalidCastException. I am using Moq 4.0.10827, the details follow. Thanks in advance if anyone can help me get the simple test (below) to run. I am rewriting unit tests with Moq and I am trying to re-do the test for the following method:
public INetwork GetInputNetwork(IInputPortMgr inPortMgr)
{
var port = inPortMgr[0];
return port.InputNetwork;
}
The IInputPortMgr interface is as follows:
public interface IInputPortMgr
{
IInputPort this[int index] { get; }
}
The test I wrote (and tried numerous variations) can be summarized by:
[Test]
public void GetInputNetwork_Returns_InputNetwork_From_InputPort()
{
var mockInPortMgr = new Mock<IInputPortMgr>();
var mockInPort = new Mock<IInputPort>();
var mockNet = new Mock<INetwork>();
mockInPortMgr.Setup(m => m[0]).Returns(mockInPort.Object); // exception here
mockInPort.Setup(m => m.InputNetwork).Returns(mockNet.Object);
// Assertions Here
}
But when run the unit test fails because an exception is thrown by the line
mockInPortMgr.Setup(m => m[0]).Returns(mockInPort.Object);
The details of the exception are:
System.InvalidCastException : Unable to cast object of type 'System.Collections.ObjectModel.ReadOnlyCollection`1[System.Reflection.CustomAttributeTypedArgument]' to type 'System.Array'.
at System.Reflection.Emit.CustomAttributeBuilder.EmitValue(BinaryWriter writer, Type type, Object value)
at System.Reflection.Emit.CustomAttributeBuilder.InitCustomAttributeBuilder(ConstructorInfo con, Object[] constructorArgs, PropertyInfo[] namedProperties, Object[] propertyValues, FieldInfo[] namedFields, Object[] fieldValues)
at Castle.DynamicProxy.AttributeUtil.CreateBuilder(CustomAttributeData attribute)
at Castle.DynamicProxy.AttributeUtil.<GetNonInheritableAttributes>d__0.MoveNext()
at Castle.DynamicProxy.Generators.MetaProperty.BuildPropertyEmitter(ClassEmitter classEmitter)
at Castle.DynamicProxy.Contributors.CompositeTypeContributor.ImplementProperty(ClassEmitter emitter, MetaProperty property, ProxyGenerationOptions options)
at Castle.DynamicProxy.Contributors.CompositeTypeContributor.Generate(ClassEmitter class, ProxyGenerationOptions options)
at Castle.DynamicProxy.Generators.InterfaceProxyWithoutTargetGenerator.GenerateType(String typeName, Type proxyTargetType, Type[] interfaces, INamingScope namingScope)
at Castle.DynamicProxy.Generators.InterfaceProxyWithTargetGenerator.GenerateCode(Type proxyTargetType, Type[] interfaces, ProxyGenerationOptions options)
at Castle.DynamicProxy.ProxyGenerator.CreateInterfaceProxyWithoutTarget(Type interfaceToProxy, Type[] additionalInterfacesToProxy, ProxyGenerationOptions options, IInterceptor[] interceptors)
at Moq.Proxy.CastleProxyFactory.CreateProxy(ICallInterceptor interceptor, Type[] interfaces, Object[] arguments)
at Moq.Mock`1.<InitializeInstance>b__0()
at Moq.Mock`1.InitializeInstance()
at Moq.Mock`1.OnGetObject()
at Moq.Mock`1.get_Object()
at Tests.Psi.Type6.Fx.Type6Fixture.GetInputNetwork() in Type6Fixture.cs: line 293
Any ideas or could anyone point me in the right direction? Thanks.

It's a bug in the version of the Castle DynamicProxy that is merged into the moq binary (Castle.Core 2.5.0.0). It looks to affect attributes that accepts a params argument. I am assuming IInputPort is decorated with such an attribute since the code is not provided?
You could compile moq with the latest version of Castle.Core (3.0.0.0) (ideal).
Or (less ideal), download the latest moq release from Google Code, which includes a moq.dll version without Castle.Core embedded. Reference this in your project along with Castle.Core 3.0.0.0 and add the following binding redirect in your app.config. Since this is a major point upgrade I can't vouch for it's backward compatibility, but I tested this with your code (and an IInputPort interface decorated with an attribute that surfaces the bug in 2.5.0.0) and it worked.
<runtime>
<assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
<dependentAssembly>
<assemblyIdentity name="Castle.Core"
publicKeyToken="407dd0808d44fbdc"
culture="neutral" />
<bindingRedirect oldVersion="2.5.0.0"
newVersion="3.0.0.0" />
</dependentAssembly>
</assemblyBinding>
</runtime>

Related

Simple Injector - Make sure that the controller has a parameterless public constructor on production

I am stuck with a strange situation. I am following Onion Architecture and my architecture is something like this:
1-Core
- Domain Classes
- Repository Interfaces
- Service Interfaces
2-Infrastructure
- Data
- Dependency Injection // Here I am using Simple Injector as dependency injection
- Repository Interfaces Implementation
- Service Interfaces Implementation
3-WebApi
- Web Api Project
4-WebClient
- My AngularJs App
5-Test
- Test Project
Dependency Injection:
[assembly: PreApplicationStartMethod(typeof(IocConfig), "RegisterDependencies")]
namespace Infrastructure.DependencyResolution
{
public class IocConfig
{
public static void RegisterDependencies()
{
var container = new Container();
container.RegisterWebApiRequest<IRepositoryAsync<Category>, Repository<Category>>();
container.RegisterWebApiRequest<ICategoryService, CategoryService>();
container.RegisterWebApiRequest<IDataContextAsync>(() => new MyContext());
container.Verify();
GlobalConfiguration.Configuration.DependencyResolver =
new SimpleInjectorWebApiDependencyResolver(container);
}
}
}
Web Api Project:
public class HomeController : ApiController
{
private readonly ICategoryService _categoryService;
public HomeController(ICategoryService categoryService)
{
_categoryService = categoryService;
}
}
Everything is working very fine on my local IIS. But now I have published this application to the production server and now it is giving me below error:
{"message":"An error has occurred.","exceptionMessage":"An error
occurred when trying to create a controller of type 'HomeController'.
Make sure that the controller has a parameterless public
constructor.","exceptionType":"System.InvalidOperationException","stackTrace":"
at
System.Web.Http.Dispatcher.DefaultHttpControllerActivator.Create(HttpRequestMessage
request, HttpControllerDescriptor controllerDescriptor, Type
controllerType)\r\n at
System.Web.Http.Controllers.HttpControllerDescriptor.CreateController(HttpRequestMessage
request)\r\n at
System.Web.Http.Dispatcher.HttpControllerDispatcher.d__1.MoveNext()","innerException":{"message":"An
error has occurred.","exceptionMessage":"Type
'JetAdz.WebApi.Controllers.HomeController' does not have a default
constructor","exceptionType":"System.ArgumentException","stackTrace":"
at System.Linq.Expressions.Expression.New(Type type)\r\n at
System.Web.Http.Internal.TypeActivator.Create[TBase](Type
instanceType)\r\n at
System.Web.Http.Dispatcher.DefaultHttpControllerActivator.GetInstanceOrActivator(HttpRequestMessage
request, Type controllerType, Func`1& activator)\r\n at
System.Web.Http.Dispatcher.DefaultHttpControllerActivator.Create(HttpRequestMessage
request, HttpControllerDescriptor controllerDescriptor, Type
controllerType)"}}
Please take a look at the inner exception of the thrown exception. It contains the details that describes why this is happening.
There are multiple problems here. You should make sure that you register all your root types explicitly in the container. Controllers are root types, because they are resolved directly (nothing depends on them, but they have dependencies). If you don't register them explicitly, the container is unable to check if they can be created when you call Verify(). You can register your controllers by calling the following:
container.RegisterWebApiControllers(GlobalConfiguration.Configuration);
This is described in the documentation.
After doing this, you probably directly see the Verify() method fail when you start the application, and in this case you get a very detailed message explaining what is going wrong.
From the inner exception you can see that Web API's DefaultHttpControllerActivator.GetInstanceOrActivator method is calling TypeActivator.Create<T>(Type). This only happens when the call to request.GetDependencyScope().GetService(controllerType) returns null. But this is typically something that can't happen if you hooked in the SimpleInjectorWebApiDependencyResolver into the Web API pipeline. This is because the SimpleInjectorWebApiDependencyResolver will never return null when it is requested to resolve an IHttpController implementation. Instead it will throw an exception when a controller can't be resolved.
So this to me is an indication of a binding redirect problem in your application. This means that the SimpleInjector.Integration.WebApi.dll is referring to a different IHttpController version than what your application is using. Binding redirects are meant to solve this, so make sure that your application has the correct binding. For the System.Web.Http.dll it looks like this (but note that you might need other bindings as well):
<runtime>
<assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
...
<dependentAssembly>
<assemblyIdentity name="System.Web.Http" publicKeyToken="31bf3856ad364e35"
culture="neutral" />
<bindingRedirect oldVersion="0.0.0.0-5.2.3.0" newVersion="5.2.3.0" />
</dependentAssembly>
</assemblyBinding>
</runtime>
Usually the bindings are managed by NuGet package manager, but it fails to do so on a regular basis.
When the binding redirect issue is fixed, you'll see that the inner exception contains information that comes from Simple Injector with the same information you'll see when calling Verify().
You are not registering the correct DependencyResolver for WebApi. According to the WebApi Dependency Injection page and the Simple Injector WebApi page, it is supposed to be done like this.
public static void Register(HttpConfiguration config)
{
var container = new Container();
container.RegisterWebApiRequest<IRepositoryAsync<Category>, Repository<Category>>();
container.RegisterWebApiRequest<ICategoryService, CategoryService>();
container.RegisterWebApiRequest<IDataContextAsync>(() => new MyContext());
container.Verify();
config.DependencyResolver = new SimpleInjectorWebApiDependencyResolver(container);
// Other Web API configuration not shown.
}
The configuration you have shown is for MVC dependency injection (which you may also need).
I use spring XML files to inject variables into my classes. In my case it was a copy/paste bug when I created a new controller.
So while this isn't exactly related to the OP problem it gets the same error message and my help someone else.
I had copied (angle brackets changed to square brackets):
[object id="className" type="Project.ClassName" scope="request"]
[constructor-arg name="OtherClassName" ref="otherclassName"/]
[/object]
when what I needed was:
[object id="className" type="Project.ClassName" scope="request"]
[property name="OtherClassName" ref="otherclassName"/]
[/object]
Note the property instead of constructor-arg.
Because my class didn't have a constructor looking for a parameter.
For me, it was simply that I had forgotten to add SimpleInjectorInitializer.Initialize(); to my Application_Start().
I typically create a SimpleInjectorInitializer class in the App_Start folder these days, within which I do the container.Verify() and GlobalConfiguration.Configuration.DependencyResolver = new SimpleInjectorWebApiDependencyResolver(container); calls; after I've called my GetInitializeContainer() method that's doing all the type registrations, etc.

How can I fake a DbSet<T> using FakeItEasy when the classes are internal?

I'm using Entity Framework 6 and want to unit test some of my business logic code. Following Microsoft's example on how to do this, they provide the following example using MOQ:
var mockSet = new Mock<DbSet<Blog>>();
var mockContext = new Mock<BloggingContext>();
mockContext.Setup(m => m.Blogs).Returns(mockSet.Object);
var service = new BlogService(mockContext.Object);
I'm using FakeItEasy instead of MOQ, and I'd hoped it would be just as simple, however FakeItEasy complains that it can't create a fake of my DbSet using the following:
var fakeDbSet = A.Fake<DbSet<InstalledProduct>>();
I get an exception as follows:
FakeItEasy.Core.FakeCreationException: Failed to create fake of
type "TN.Prs.Persistence.LicenseContext".
Below is a list of reasons for failure per attempted constructor:
No constructor arguments failed:
No usable default constructor was found on the type TN.Prs.Persistence.LicenseContext.
An exception was caught during this call. Its message was:
Access is denied: 'TN.Prs.Persistence.LicenseContext'.
at
FakeItEasy.Core.DefaultExceptionThrower.ThrowFailedToGenerateProxyWithResolvedConstructors(Type
typeOfFake, String reasonForFailureOfUnspecifiedConstructor,
IEnumerable1 resolvedConstructors) at
FakeItEasy.Creation.FakeObjectCreator.TryCreateFakeWithDummyArgumentsForConstructor(Type
typeOfFake, FakeOptions fakeOptions, IDummyValueCreationSession
session, String failReasonForDefaultConstructor, Boolean
throwOnFailure) at
FakeItEasy.Creation.FakeObjectCreator.CreateFake(Type typeOfFake,
FakeOptions fakeOptions, IDummyValueCreationSession session, Boolean
throwOnFailure) at
FakeItEasy.Creation.DefaultFakeAndDummyManager.CreateFake(Type
typeOfFake, FakeOptions options) at
FakeItEasy.Creation.DefaultFakeCreatorFacade.CreateFake[T](Action1
options) at FakeItEasy.A.FakeT at
TN.Prs.RegistrationServices.Specifications.when_activating_a_product_from_a_valid_digitally_signed_activation_key.<.ctor>b__0()
in
My POCO classes are internal rather than public, but I've added the InternalsVisibleTo attributes as appropriate, for DynamicProxyGenAssembly2. When I make the classes public, everything works, but I really don't want to expose these classes publicly. I would appreciate any suggestions.
Here is my context class:
internal class LicenseContext : DbContext
{
public LicenseContext()
{
}
public virtual DbSet<InstalledProduct> ManagedProducts { get; set; }
}
Problem solved!
Before I added the InternalsVisibleTo attributes, FakeItEasy complained and told me to add those attributes and I was delighted to see that it gave me the exact code I needed right in the error message. I even remarked to one of my colleagues, "now THAT is what I call an error message!". The attribute it suggested was:
[assembly: InternalsVisibleTo("DynamicProxyGenAssembly2, PublicKey=0024000004800000940000000602000000240000525341310004000001000100c547cac37abd99c8db225ef2f6c8a3602f3b3606cc9891605d02baa56104f4cfc0734aa39b93bf7852f7d9266654753cc297e7d2edfe0bac1cdcf9f717241550e0a7b191195b7667bb4f64bcb8e2121380fd1d9d46ad2d92d2d15605093924cceaf74c4861eff62abf69b9291ed0a340e113be11e6a7d3113e92484cf7045cc7")]
Unfortunately that doesn't work and I get an 'Access Denied' error. It might be that the public key isn't correct, but since my assemblies are not strong-named, I simply removed the public key from the attributes and everything works.
Eventually I will have to strong-name my assemblies so I will have to solve this public key problem eventually, but I know what to do so it shouldn't be an obstacle.

ResolutionFailedException with Unity

I'm using Patterns and Practices' Unity to inject dependencies into my objects and have hit a weird (to me, anyway) issue. Here's my class definitions:
public class ImageManager : IImageManager
{
IImageFileManager fileManager;
public ImageManager(IImageFileManager fileMgr)
{
this.fileManager = fileMgr;
}
}
public class ImageFileManager : IImageFileManager
{
public ImageFileManager(string folder)
{
FileFolder = folder;
}
}
And here's the code to register my classes
container.RegisterInstance<MainWindowViewModel>(new MainWindowViewModel())
.RegisterType<IPieceImageManager, PieceImageManager>(
new InjectionConstructor(typeof(string)))
.RegisterType<IImageFileManager, ImageFileManager>()
.RegisterType<IImageManager, ImageManager>(
new InjectionConstructor(typeof(IImageFileManager)));
I originally resolved this in the code behind (I know, it defeats the purpose. Bear with me.) of the XAML file like this
IImageManager imageManager = MvvmViewModelLocator.Container.Resolve<IImageManager>(
new ParameterOverride("folder", "/images"));
And it worked. But I created a view model for my main view and when I copied the same line into it, I get an exception. Here are the two most inner exceptions:
InnerException: Microsoft.Practices.Unity.ResolutionFailedException
HResult=-2146233088
Message=Resolution of the dependency failed, type = "SwapPuzzleApp.Model.IImageManager", name = "(none)".
Exception occurred while: while resolving.
Exception is: InvalidOperationException - The type IImageManager does not have an accessible constructor.
At the time of the exception, the container was:
Resolving SwapPuzzleApp.Model.IImageManager,(none)
Source=Microsoft.Practices.Unity
TypeRequested=IImageManager
StackTrace:
at Microsoft.Practices.Unity.UnityContainer.DoBuildUp(Type t, Object existing, String name, IEnumerable`1 resolverOverrides)
at Microsoft.Practices.Unity.UnityContainer.DoBuildUp(Type t, String name, IEnumerable`1 resolverOverrides)
at Microsoft.Practices.Unity.UnityContainer.Resolve(Type t, String name, ResolverOverride[] resolverOverrides)
at Microsoft.Practices.Unity.UnityContainerExtensions.Resolve[T](IUnityContainer container, ResolverOverride[] overrides)
at SwapPuzzleApp.ViewModel.MainWindowViewModel..ctor() in c:\Users\Carole\Documents\Visual Studio 2012\Projects\SwapPuzzle\SwapPuzzle\ViewModel\MainWindowViewModel.cs:line 17
at SwapPuzzleApp.ViewModel.MvvmViewModelLocator..cctor() in c:\Users\Carole\Documents\Visual Studio 2012\Projects\SwapPuzzle\SwapPuzzle\ViewModel\MvvmViewModelLocator.cs:line 51
InnerException: System.InvalidOperationException
HResult=-2146233079
Message=The type IImageManager does not have an accessible constructor.
Source=Microsoft.Practices.Unity
StackTrace:
StackTrace:
at Microsoft.Practices.ObjectBuilder2.DynamicMethodConstructorStrategy.ThrowForNullExistingObject(IBuilderContext context)
at lambda_method(Closure , IBuilderContext )
at Microsoft.Practices.ObjectBuilder2.DynamicBuildPlanGenerationContext.<>c__DisplayClass1.<GetBuildMethod>b__0(IBuilderContext context)
at Microsoft.Practices.ObjectBuilder2.DynamicMethodBuildPlan.BuildUp(IBuilderContext context)
at Microsoft.Practices.ObjectBuilder2.BuildPlanStrategy.PreBuildUp(IBuilderContext context)
at Microsoft.Practices.ObjectBuilder2.StrategyChain.ExecuteBuildUp(IBuilderContext context)
at Microsoft.Practices.Unity.UnityContainer.DoBuildUp(Type t, Object existing, String name, IEnumerable`1 resolverOverrides)
InnerException:
I'm not sure what the problem is, as ImageManager clearly has a public constructor. I thought it might be due to an invalid path, but if I concretely instantiate the object, everything works.
// this line has no problems
IImageManager imageManager = new ImageManager(new ImageFileManager("/images"));
I also wondered if I needed to pass in new InjectionConstructor(typeof(string)) when I register IImageManager, but it doesn't seem to help and why would it be needed now and not before? So I'm stumped. This is my first attempt at using Dependency Injection, so it's probably something basic. I'm just not seeing what, though.
Look very closely at the error message. Notice this part:
Message=The type IImageManager does not have an accessible constructor.
Notice the type name is IImageManager, not ImageManager. Somewhere along the line you lost your type mapping.
Your registration of FileImageManager has a problem as well, since you don't specify the folder parameter in the registration, so Unity has no idea what string to pass.
I was using the examples in this article as my guide. Either the examples in there are way too advanced for an introduction, or there's misinformation in that topic.
After consulting other sources (mainly PluarlSight), I came up with a much simpler and more logical solution.
container.RegisterInstance<TimerViewModel>(new TimerViewModel());
container.RegisterType<IPieceImageManager, PieceImageManager>();
container.RegisterType<IImageFileManager, ImageFileManager>
(new InjectionConstructor("/images"));
container.RegisterType<IImageManager, ImageManager>();
I ran into a similar issue with this error tied directly to a Mock (using automoq) that I was doing for an operation. In this case it turned out that because there were a number of member methods that get called with the object being mocked, that I had to define all of those in the automoq chain to get it to resolve properly
I realize this is an example in instance code, but it could occur in Moqs also. So if you read this and are wondering about an example related to Moqs, look into that first.

access to the Object property after new Mock<RadNumericTextBox>() leads to NullReferenceException

I have to write some tests using moq framework (https://code.google.com/p/moq/). I want to check if some value can be read correctly from a telerik textbox in some ASP.NET application. Therefore I want to mock the telerik text box and give this mock as a parameter to the SUT's method to check if it is read correctly.
Consider:
var telerikFake = new Mock<RadNumericTextBox>();
telerikFake.Setup(x => x.Text).Returns("23,456");
var result = telerikFake.Object; //The exception comes from inside the telerikFake.Object property implementation
Accessing the telerikFake.Object property gives a NullReferenceException with this stack trace:
at Castle.DynamicProxy.AttributeUtil.<GetNonInheritableAttributes>d__0.MoveNext()
at Castle.DynamicProxy.Contributors.ClassProxyInstanceContributor.Generate(ClassEmitter class, ProxyGenerationOptions options)
at Castle.DynamicProxy.Generators.ClassProxyGenerator.GenerateType(String name, Type[] interfaces, INamingScope namingScope)
at Castle.DynamicProxy.Generators.ClassProxyGenerator.GenerateCode(Type[] interfaces, ProxyGenerationOptions options)
at Castle.DynamicProxy.DefaultProxyBuilder.CreateClassProxyType(Type classToProxy, Type[] additionalInterfacesToProxy, ProxyGenerationOptions options)
at Castle.DynamicProxy.ProxyGenerator.CreateClassProxyType(Type classToProxy, Type[] additionalInterfacesToProxy, ProxyGenerationOptions options)
at Castle.DynamicProxy.ProxyGenerator.CreateClassProxy(Type classToProxy, Type[] additionalInterfacesToProxy, ProxyGenerationOptions options, Object[] constructorArguments, IInterceptor[] interceptors)
at Moq.Proxy.CastleProxyFactory.CreateProxy[T](ICallInterceptor interceptor, Type[] interfaces, Object[] arguments)
at Moq.Mock`1.<InitializeInstance>b__0()
at Moq.PexProtector.Invoke(Action action)
Do you have any hints under what circumstances the moq frameworks Mock.Object method leads to this error?
I found a ticket within the MoQ issue list: http://code.google.com/p/moq/issues/detail?id=326 . Are there any developers enabled to fix this issue soon? The ticket was created in 2011.
Regards,
Michael

EF and Webservice Error "System.InvalidOperationException"

I started a new project. Created a class library added EF item to it under a DB namespace and then create a class(Stripped down) for each entity that i can expose in WS. I ref the CL in a windows test app to see if everything was working and it was.So i created a WS add reference addedd the connectionstring for EF and then created a webmethod that retruns the object i created for each entity.
so my namspaces looks like this
[projectName].CL.Item - created object
[projectName].CL.DB.Item - Ef Item
[projectName].WS - Webservice namespace
So i ran the ws and tested it. and i get this lovely little exception.
System.InvalidOperationException: Unable to generate a temporary class (result=1).
error CS0012: The type 'System.Data.Objects.DataClasses.EntityObject' is defined in an assembly that is not referenced. You must add a reference to assembly 'System.Data.Entity, Version=3.5.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089'.
at System.Xml.Serialization.Compiler.Compile(Assembly parent, String ns, XmlSerializerCompilerParameters xmlParameters, Evidence evidence)
at System.Xml.Serialization.TempAssembly.GenerateAssembly(XmlMapping[] xmlMappings, Type[] types, String defaultNamespace, Evidence evidence, XmlSerializerCompilerParameters parameters, Assembly assembly, Hashtable assemblies)
at System.Xml.Serialization.TempAssembly..ctor(XmlMapping[] xmlMappings, Type[] types, String defaultNamespace, String location, Evidence evidence)
at System.Xml.Serialization.XmlSerializer.FromMappings(XmlMapping[] mappings, Evidence evidence)
at System.Web.Services.Protocols.XmlReturn.GetInitializers(LogicalMethodInfo[] methodInfos)
at System.Web.Services.Protocols.XmlReturnWriter.GetInitializers(LogicalMethodInfo[] methodInfos)
at System.Web.Services.Protocols.MimeFormatter.GetInitializers(Type type, LogicalMethodInfo[] methodInfos)
at System.Web.Services.Protocols.HttpServerType..ctor(Type type)
at System.Web.Services.Protocols.HttpServerProtocol.Initialize()
at System.Web.Services.Protocols.ServerProtocol.SetContext(Type type, HttpContext context, HttpRequest request, HttpResponse response)
at System.Web.Services.Protocols.ServerProtocolFactory.Create(Type type, HttpContext context, HttpRequest request, HttpResponse response, Boolean& abortProc
Now this tells me it need reference to data.entity so i added still thinking to myself this is weird never had to do this and i am not return entity object i am returning the created onces but i did it. still the same error
then i saw that no matter what webmethod i select it does this i commented the webmethod out and made a helloworld and it worked.
I looked on google some people suggestthat you add
<add assembly="System.Data.Entity, Version=3.5.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"/>
to the webconfig i did and still same error. i am dumbfounded i do this sort of thing like daily and i never got a error like this. And the EF structure is nothing special 5 tables with foreignkeys.
i even deleted the WS/CL project and recreated it.
pls help
Found the problem...
I have in each POCO class this
namespace CL
{
public class Item
{
public static implicit operator Item(DB.Item db)
{
return new Item
{
Created = db.Created,
Id = db.ItemId
};
}
}
}
that basically converts the DB item into a POCO item.
So if i do this instead
namespace CL.DB
{
public partial class Item
{
public static implicit operator CL.Item(Item db)
{
return new CL.Item
{
Created = db.Created,
Id = db.ItemId
};
}
}
}
it works fine. WTF

Categories