Reg. Unit Testing an Html Helper with AutoFixture - autofixture

The original question is :
Unit Testing an Html Helper with AutoFixture
Not sure I should re-open the original question; however since I marked the original question as resolved I decided to create a new one. Apologies if I did this wrong.
I was using Mark’s suggested approach but I got stuck while using the Freeze.
Below is the complete source code…
Class Under Test:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
namespace MvcDemo2.Helpers
{
public static class Keys
{
public static readonly string SomeKey = "SomeKey";
}
public static class SampleHelpers
{
public static MvcHtmlString SampleTable(this HtmlHelper helper,
SampleModel model, IDictionary<string, object> htmlAttributes)
{
if (helper == null)
{
throw new ArgumentNullException("helper");
}
if (model == null)
{
throw new ArgumentNullException("model");
}
TagBuilder tagBuilder = new TagBuilder("table");
tagBuilder.MergeAttributes(htmlAttributes);
tagBuilder.GenerateId(helper.ViewContext.
HttpContext.Items[Keys.SomeKey].ToString());
return MvcHtmlString.Create(
tagBuilder.ToString(TagRenderMode.Normal));
}
}
}
public class SampleModel
{
}
}
Unit Test is to ensure the Html returned as expected for the specified key within HttpContext
public void SampleTableHtmlHelper_WhenKeyExistWithinHttpContext_ReturnsExpectedHtml()
I configured the Fixture as below
var fixture = new Fixture().Customize(new AutoMoqCustomization());
Then the Freeze on ViewContext:
var vc = fixture.Freeze<ViewContext>();
I get the below exception:
Error 1 Test
'MvcDemo2.Tests.Controllers.SampleHelpersTestsAutoFixture.SampleTableHtmlHelper_WhenKeyExistWithinHttpContext_ReturnsExpectedHtml'
failed: System.Reflection.TargetInvocationException : Exception has
been thrown by the target of an invocation.
---- System.NotImplementedException : The method or operation is not
implemented. at
System.RuntimeMethodHandle._InvokeMethodFast(IRuntimeMethodInfo
method, Object target, Object[] arguments, SignatureStruct& sig,
MethodAttributes methodAttributes, RuntimeType typeOwner) at
System.RuntimeMethodHandle.InvokeMethodFast(IRuntimeMethodInfo method,
Object target, Object[] arguments, Signature sig, MethodAttributes
methodAttributes, RuntimeType typeOwner) at
System.Reflection.RuntimeMethodInfo.Invoke(Object obj, BindingFlags
invokeAttr, Binder binder, Object[] parameters, CultureInfo culture,
Boolean skipVisibilityChecks) at
System.Reflection.RuntimeMethodInfo.Invoke(Object obj, BindingFlags
invokeAttr, Binder binder, Object[] parameters, CultureInfo culture)
at System.Reflection.RuntimePropertyInfo.SetValue(Object obj, Object
value, BindingFlags invokeAttr, Binder binder, Object[] index,
CultureInfo culture) at
System.Reflection.RuntimePropertyInfo.SetValue(Object obj, Object
value, Object[] index) at
Ploeh.AutoFixture.Kernel.AutoPropertiesCommand1.Execute(T specimen,
ISpecimenContext context) at
Ploeh.AutoFixture.Kernel.Postprocessor1.Create(Object request,
ISpecimenContext context) at
Ploeh.AutoFixture.Kernel.CompositeSpecimenBuilder.<>c__DisplayClass6.b__1(ISpecimenBuilder
b) at System.Linq.Enumerable.WhereSelectListIterator2.MoveNext()
at System.Linq.Enumerable.WhereSelectEnumerableIterator2.MoveNext()
at System.Linq.Enumerable.d__a51.MoveNext()
at System.Linq.Enumerable.FirstOrDefault[TSource](IEnumerable1
source) at
Ploeh.AutoFixture.Kernel.CompositeSpecimenBuilder.Create(Object
request, ISpecimenContext context) at
Ploeh.AutoFixture.Kernel.RecursionGuard.Create(Object request,
ISpecimenContext context) at
Ploeh.AutoFixture.Kernel.SpecimenContext.Resolve(Object request) at
Ploeh.AutoFixture.Kernel.SeedIgnoringRelay.Create(Object request,
ISpecimenContext context) at
Ploeh.AutoFixture.Kernel.CompositeSpecimenBuilder.<>c__DisplayClass6.b__1(ISpecimenBuilder
b) at System.Linq.Enumerable.WhereSelectListIterator2.MoveNext()
at System.Linq.Enumerable.WhereSelectEnumerableIterator2.MoveNext()
at System.Linq.Enumerable.d__a51.MoveNext()
at System.Linq.Enumerable.FirstOrDefault[TSource](IEnumerable1
source) at
Ploeh.AutoFixture.Kernel.CompositeSpecimenBuilder.Create(Object
request, ISpecimenContext context) at
Ploeh.AutoFixture.Kernel.Postprocessor1.Create(Object request,
ISpecimenContext context) at
Ploeh.AutoFixture.Kernel.CompositeSpecimenBuilder.<>c__DisplayClass6.<Create>b__1(ISpecimenBuilder
b) at System.Linq.Enumerable.WhereSelectListIterator2.MoveNext()
at System.Linq.Enumerable.WhereSelectEnumerableIterator2.MoveNext()
at System.Linq.Enumerable.<DefaultIfEmptyIterator>d__a51.MoveNext()
at System.Linq.Enumerable.FirstOrDefault[TSource](IEnumerable1
source) at
Ploeh.AutoFixture.Kernel.CompositeSpecimenBuilder.Create(Object
request, ISpecimenContext context) at
Ploeh.AutoFixture.Kernel.RecursionGuard.Create(Object request,
ISpecimenContext context) at
Ploeh.AutoFixture.Kernel.SpecimenContext.Resolve(Object request) at
Ploeh.AutoFixture.SpecimenFactory.CreateAnonymous[T](ISpecimenContext
context, T seed) at
Ploeh.AutoFixture.SpecimenFactory.CreateAnonymous[T](ISpecimenBuilderComposer
composer, T seed) at
Ploeh.AutoFixture.FixtureFreezer.Freeze[T](IFixture fixture, T seed)
at
MvcDemo2.Tests.Controllers.SampleHelpersTestsAutoFixture.SampleTableHtmlHelper_WhenKeyExistWithinHttpContext_ReturnsExpectedHtml()
in C:\Users\...:line 78
----- Inner Stack Trace ----- at
System.Web.HttpContextBase.get_Items() at
System.Web.Mvc.ViewContext.ScopeCache.Get(IDictionary2 scope,
HttpContextBase httpContext) at
System.Web.Mvc.ViewContext.SetClientValidationEnabled(Boolean enabled,
IDictionary`2 scope, HttpContextBase httpContext) at
System.Web.Mvc.ViewContext.set_ClientValidationEnabled(Boolean
value) C:\Users... 78
Seems it fails on when it try to set the value of property
ViewContext.SetClientValidationEnabled.
I’m stuck on this. Any thoughts greatly appreciated.

Well, if you consider the inner stack trace you'll notice that the exception is being thrown by HttpContextBase.Items. If you were to look at the implementation using a reflection tool you would find that this virtual method throws a NotImplementedException - talk about a POLA violation. A lot of the Web abstractions in the BCL does exactly that, which is really, really painful to deal with.
I'm not sure it'll help you further on, but you can get past this particular issue by turning off AutoProperties for the ViewContext class like this:
fixture.Customize<ViewContext>(c => c.OmitAutoProperties());

Thanks Mark. I find AutoFixture is very useful but when I Unit Test MVC, I find bit trickier to apply the API. It is probably because I’m still new to the API.
With….
fixture.Customize<ViewContext>(c => c.OmitAutoProperties());
var vc = fixture.Freeze<ViewContext>();
The above works fine, but as you suspected it fails again when I try to add items to
vc.HttpContext.Items.Add(Keys.SomeKey, "foo");
Exceptiion: The method or operation is not implemented.
The reflector on HttpContextBase...
public virtual IDictionary Items
{
get
{
throw new NotImplementedException();
}
}
So the only way I can think is to create my own implementation of HttpContextBase
private class FakeHttpContext : HttpContextBase
{
private Dictionary<object, object> _items = new Dictionary<object, object>();
public override IDictionary Items { get { return _items; } }
}
Then below is the confusing bit..
fixture.Inject<HttpContextBase>(new FakeHttpContext());
var hc = fixture.CreateAnonymous<HttpContextBase>();
If I swap these two lines (which creates the anonymouse instance first and then inject the fake instance) causes the error..
AutoFixture was unable to create an instance from
System.Web.HttpContextBase, most likely because it has no public
constructor.
So far I can come up with a test like this...
public void SampleTableHtmlHelper_WhenKeyExistWithinHttpContext_ReturnsExpectedHtml()
{
//Arrange
var fixture = new Fixture();
fixture.Customize<ViewContext>(c => c.OmitAutoProperties());
var vc = fixture.Freeze<ViewContext>();
fixture.Inject<HttpContextBase>(new FakeHttpContext());
var hc = fixture.CreateAnonymous<HttpContextBase>();
vc.HttpContext = hc;
vc.HttpContext.Items.Add(Keys.SomeKey, "foo");
var htmlHelper = fixture.CreateAnonymous<HtmlHelper>();
var sampleModel = fixture.CreateAnonymous<SampleModel>();
//Act
var result = SampleHelpers.SampleTable(htmlHelper, sampleModel, null).ToString();
//Assert
Assert.Equal("<table id=\"foo\"></table>", result);
}
Also removed new AutoMoqCustomization() as it seems to have no effect on the test.
Once I get more familiar with AutoFixture I might be able to come up with a better version. Thanks for the help.

Seems it fails on when it try to set the value of property ViewContext.SetClientValidationEnabled.
That problem was fixed for me by this answer, see how he gets an HtmlHelper (see also here).

Related

RavenDB Silverlight error Debugging resource strings are unavailable

RavenDB has started throwing this error when i attempt to edit a document via the ravenDB silverlight interface. it appears machine specific at the moment, any idea whats causing this error?
[Arg_TargetInvocationException] Arguments: Debugging resource strings
are unavailable. Often the key and arguments provide sufficient
information to diagnose the problem. See
http://go.microsoft.com/fwlink/?linkid=106663&Version=4.0.60531.0&File=mscorlib.dll&Key=Arg_TargetInvocationException
at System.RuntimeMethodHandle.InvokeMethodFast(IRuntimeMethodInfo
method, Object target, Object[] arguments, SignatureStruct& sig,
MethodAttributes methodAttributes, RuntimeType typeOwner) at
System.Reflection.RuntimeMethodInfo.Invoke(Object obj, BindingFlags
invokeAttr, Binder binder, Object[] parameters, CultureInfo culture,
Boolean skipVisibilityChecks) at
System.Reflection.RuntimeMethodInfo.Invoke(Object obj, BindingFlags
invokeAttr, Binder binder, Object[] parameters, CultureInfo culture)
at Caliburn.Micro.ViewLocator.InitializeComponent(Object element)
at Caliburn.Micro.ViewLocator.<.cctor>b_3(Type viewType) at
Caliburn.Micro.ViewLocator.<.cctor>b_9(Type modelType,
DependencyObject displayLocation, Object context) at
Raven.Studio.StudioViewLocator.LocateForModelType(Type modelType,
DependencyObject viewLocation, Object context, Func4 original) at
Raven.Studio.AppBootstrapper.<>c__DisplayClassc.<ConfigureConventions>b__9(Type
t, DependencyObject v, Object c) at
Caliburn.Micro.ViewLocator.<.cctor>b__a(Object model, DependencyObject
displayLocation, Object context) at
Caliburn.Micro.View.OnModelChanged(DependencyObject targetLocation,
DependencyPropertyChangedEventArgs args) at
System.Windows.DependencyObject.RaisePropertyChangeNotifications(DependencyProperty
dp, Object oldValue, Object newValue) at
System.Windows.DependencyObject.UpdateEffectiveValue(DependencyProperty
property, EffectiveValueEntry oldEntry, EffectiveValueEntry& newEntry,
ValueOperation operation) at
System.Windows.DependencyObject.RefreshExpression(DependencyProperty
dp) at System.Windows.Data.BindingExpression.SendDataToTarget()
at
System.Windows.Data.BindingExpression.SourcePropertyChanged(PropertyPathListener
sender, PropertyPathChangedEventArgs args) at
System.Windows.PropertyPathListener.RaisePropertyPathStepChanged(PropertyPathStep
source) at
System.Windows.PropertyAccessPathStep.RaisePropertyPathStepChanged(PropertyListener
source) at
System.Windows.CLRPropertyListener.SourcePropertyChanged(Object
sender, PropertyChangedEventArgs args) at
System.Windows.Data.WeakPropertyChangedListener.PropertyChangedCallback(Object
sender, PropertyChangedEventArgs args) at
System.ComponentModel.PropertyChangedEventHandler.Invoke(Object
sender, PropertyChangedEventArgs e) at
Caliburn.Micro.PropertyChangedBase.RaisePropertyChangedEventCore(String
propertyName) at
Caliburn.Micro.PropertyChangedBase.<>c__DisplayClass3.<NotifyOfPropertyChange>b__2()
at
Caliburn.Micro.Execute.<>c__DisplayClass2.<InitializeWithDispatcher>b__0(Action
action) at Caliburn.Micro.Execute.OnUIThread(Action action) at
Caliburn.Micro.PropertyChangedBase.NotifyOfPropertyChange(String
propertyName) at
Caliburn.Micro.ConductorBaseWithActiveItem1.ChangeActiveItem(T
newItem, Boolean closePrevious) at
Caliburn.Micro.Conductor1.<>c__DisplayClass1.<ActivateItem>b__0(Boolean
canClose, IEnumerable1 items) at
Caliburn.Micro.DefaultCloseStrategy1.Evaluate(Boolean result,
IEnumerator1 enumerator, Action2 callback) at
Caliburn.Micro.DefaultCloseStrategy1.<>c_DisplayClass4.b_0(Boolean
canClose) at Caliburn.Micro.Screen.CanClose(Action1 callback)
at Caliburn.Micro.DefaultCloseStrategy1.Evaluate(Boolean result,
IEnumerator1 enumerator, Action2 callback) at
Caliburn.Micro.DefaultCloseStrategy1.Execute(IEnumerable1 toClose,
Action2 callback) at Caliburn.Micro.Conductor1.ActivateItem(T
item) at
Raven.Studio.Features.Database.DatabaseExplorer.ActivateItem(Object
item) at
Caliburn.Micro.ConductorBase1.Caliburn.Micro.IConductor.ActivateItem(Object
item) at
Raven.Studio.Framework.Extensions.ScreenExtensions.TrackNavigationTo[T](T
conductor, IScreen newScreen, IEventAggregator events, Action
setContext) at
Raven.Studio.Features.Database.DatabaseExplorer.Caliburn.Micro.IHandle<Raven.Studio.Messages.DatabaseScreenRequested>.Handle(DatabaseScreenRequested
message) at
Caliburn.Micro.EventAggregator.<>c__DisplayClasse1.b_c()
at
Caliburn.Micro.Execute.<>c_DisplayClass2.b_0(Action
action) at Caliburn.Micro.Execute.OnUIThread(Action action) at
Caliburn.Micro.EventAggregator.Publish[TMessage](TMessage message)
at Raven.Studio.Commands.EditDocument.Execute(DocumentViewModel
document)
thanks
Build 531 fixed this issue.
RavenDB google group
seems like its a DD/MM issue thats hitting everyone today, reset the clock PC to last week (06/Nov/2011) and it works..oops will be expecting a fix asap :)
https://groups.google.com/group/ravendb/browse_thread/thread/62e55f335ffd7fdd

WinForm Design Error: Why am I seeing this page?

Object of type 'System.Collections.Generic.List`1[Jud.Itd.Cmis.BusinessObjects.AddressType]' cannot be converted to type 'System.Collections.Generic.IList`1[Jud.Itd.Cmis.BusinessObjects.AddressType]'.
Closing Visual Studio and reopening and recompiling all fixes it, so I would say that this is clearly a bug and a huge nuisance.
The question is, is there a work around other than restarting VS or living without the Designer? Cleaning the app and recompiling all doesn't do it.
Instances of this error (1)
1. Hide Call Stack
at System.RuntimeType.CheckValue(Object value, Binder binder, CultureInfo culture, BindingFlags invokeAttr)
at System.Reflection.RtFieldInfo.InternalSetValue(Object obj, Object value, BindingFlags invokeAttr, Binder binder, CultureInfo culture, Boolean doVisibilityCheck, Boolean doCheckConsistency)
at System.Reflection.RtFieldInfo.InternalSetValue(Object obj, Object value, BindingFlags invokeAttr, Binder binder, CultureInfo culture, Boolean doVisibilityCheck)
at System.Runtime.Serialization.SerializationFieldInfo.InternalSetValue(Object obj, Object value, BindingFlags invokeAttr, Binder binder, CultureInfo culture, Boolean requiresAccessCheck, Boolean isBinderDefault)
at System.Runtime.Serialization.FormatterServices.SerializationSetValue(MemberInfo fi, Object target, Object value)
at System.Runtime.Serialization.ObjectManager.CompleteObject(ObjectHolder holder, Boolean bObjectFullyComplete)
at System.Runtime.Serialization.ObjectManager.DoNewlyRegisteredObjectFixups(ObjectHolder holder)
at System.Runtime.Serialization.ObjectManager.RegisterObject(Object obj, Int64 objectID, SerializationInfo info, Int64 idOfContainingObj, MemberInfo member, Int32[] arrayIndex)
at System.Runtime.Serialization.Formatters.Binary.ObjectReader.RegisterObject(Object obj, ParseRecord pr, ParseRecord objectPr, Boolean bIsString)
at System.Runtime.Serialization.Formatters.Binary.ObjectReader.ParseObjectEnd(ParseRecord pr)
at System.Runtime.Serialization.Formatters.Binary.ObjectReader.Parse(ParseRecord pr)
at System.Runtime.Serialization.Formatters.Binary.__BinaryParser.Run()
at System.Runtime.Serialization.Formatters.Binary.ObjectReader.Deserialize(HeaderHandler handler, __BinaryParser serParser, Boolean fCheck, Boolean isCrossAppDomain, IMethodCallMessage methodCallMessage)
at System.Runtime.Serialization.Formatters.Binary.BinaryFormatter.Deserialize(Stream serializationStream, HeaderHandler handler, Boolean fCheck, Boolean isCrossAppDomain, IMethodCallMessage methodCallMessage)
at System.Runtime.Serialization.Formatters.Binary.BinaryFormatter.Deserialize(Stream serializationStream)
at System.Resources.ResXDataNode.GenerateObjectFromDataNodeInfo(DataNodeInfo dataNodeInfo, ITypeResolutionService typeResolver)
at System.Resources.ResXDataNode.GetValue(ITypeResolutionService typeResolver)
at System.Resources.ResXResourceReader.ParseDataNode(XmlTextReader reader, Boolean isMetaData)
at System.Resources.ResXResourceReader.ParseXml(XmlTextReader reader)
Help with this error
MSDN Help
Forum posts about this error
Search the MSDN Forums for posts related to this error
I might have an answer. I just encountered the same error and I found out that this is produced if there are some errors in a Form constructor or the Form_Load() method. I tried to comment out code in these methods and when it didn't helped I realized that there must be en error in some component.
And it was. If you use some custom component and it have some properties set to null even after a constructor of this component is called it could cause this rendering error.
You can find these properties in your Form.resx file. They will have value in the Value column set to (Nothing/null).
What helped me was to delete these bad lines there and mark my properties with the following attributes.
[Browsable(false), DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
The WinForm Designer has a bug. In fact, this bug rates as the most complained about bug in WinForm development. Live with it.

Silverlight security: giving a permission to access anonymous classes to a class library

I'm porting an existing class library to Silverlight. I used lambda expression compilation a lot and now I'm experiencing security problems because of it.
In particular, if an anonymous class from a client SL app is participating in a lambda expression, I cannot compile it: I get a MethodAccessException with the following stack trace:
MethodBase.PerformSecurityCheck(Object obj, RuntimeMethodHandle method, IntPtr parent, UInt32 invocationFlags)
RuntimeMethodInfo.Invoke(Object obj, BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture, Boolean skipVisibilityChecks)
RuntimeMethodInfo.Invoke(Object obj, BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture)
MethodBase.Invoke(Object obj, Object[] parameters)
Expression.Lambda(Type delegateType, Expression body, IEnumerable<T> parameters)
Expression.Lambda(Type delegateType, Expression body, ParameterExpression[] parameters)
Expression.Lambda(Expression body, ParameterExpression[] parameters)
I tried to use InternalsVisibleTo in the client SL app to expose anonymous classes to my class library, but it didn't help. Actually it should help, but I cannot understand why it does not.
Any ideas?
UPDATE:
I've figured out that the problem is not in lambda expressions, but in dynamic generic method invocation:
If we have the following code in a class library:
public class LibClass
{
public static void StaticReceive<T>(T x)
{
Process<T>(x);
}
public static void DynamicReceive(object x)
{
typeof(LibClass).GetMethod("Process", BindingFlags.NonPublic | BindingFlags.Static)
.MakeGenericMethod(x.GetType())
.Invoke(null, new object[] { x });
}
static void Process<T>(T x)
{
// some work with typed x
}
}
and we call the StaticReceive method from the app like this:
class InternalClass { }
void MethodInUserApp()
{
var x = new InternalClass();
LibClass.StaticReceive(x);
}
it works OK, but if we use DynamicReceive, it fails. It looks like CLR considers the x parameter in the Process method as of type InternalClass, not generic T, and since InternalClass is not accessible for the library, forbids its invocation.
It looks like a bug, no?
Solved: Add the following code to your AssemblyInfo.cs:
[assembly: InternalsVisibleTo("System.Core, PublicKey=" +
"00240000048000009400000006020000002400005253413100040000010001008d56c76f9e8649" +
"383049f383c44be0ec204181822a6c31cf5eb7ef486944d032188ea1d3920763712ccb12d75fb7" +
"7e9811149e6148e5d32fbaab37611c1878ddc19e20ef135d0cb2cff2bfec3d115810c3d9069638" +
"fe4be215dbf795861920e5ab6f7db2e2ceef136ac23d5dd2bf031700aec232f6c6b1c785b4305c" +
"123b37ab")]
Discussed in the Silverlight forum

RIA Services does not support entities that are decorated by NHibernate mapping attributes?

I'm working on a project where entities are being decorated by NHibernate mapping attributes such as [Property] and [Class]. Unfortunately RIAServices doesn't seem to support most of these attributes, which causes a failure when RIAServices is trying to generate the Silverlight Client Code.
When I try to build a DomainService that uses an entity decorated with the [Class] or [Property] attribute, I get an ArgumentNullException with the following error message:
Error 2 The "CreateRiaClientFilesTask" task failed unexpectedly.
System.Reflection.TargetInvocationException: Exception has been thrown by the target of an invocation. ---> System.ArgumentNullException: Value cannot be null.
Parameter name: TypeName
at System.RuntimeType.PrivateGetType(String typeName, Boolean throwOnError, Boolean ignoreCase, Boolean reflectionOnly, StackCrawlMark& stackMark)
at System.Type.GetType(String typeName)
at NHibernate.Mapping.Attributes.ClassAttribute.get_NameType()
--- End of inner exception stack trace ---
at System.RuntimeMethodHandle._InvokeMethodFast(Object target, Object[] arguments, SignatureStruct& sig, MethodAttributes methodAttributes, RuntimeTypeHandle typeOwner)
at System.RuntimeMethodHandle.InvokeMethodFast(Object target, Object[] arguments, Signature sig, MethodAttributes methodAttributes, RuntimeTypeHandle typeOwner)
at System.Reflection.RuntimeMethodInfo.Invoke(Object obj, BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture, Boolean skipVisibilityChecks)
at System.Reflection.RuntimeMethodInfo.Invoke(Object obj, BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture)
at System.Reflection.RuntimePropertyInfo.GetValue(Object obj, BindingFlags invokeAttr, Binder binder, Object[] index, CultureInfo culture)
at System.Reflection.RuntimePropertyInfo.GetValue(Object obj, Object[] index)
at System.Web.DomainServices.Tools.StandardCustomAttributeBuilder.GetPropertyValues(IEnumerable`1 propertyMaps, Attribute attribute)
at System.Web.DomainServices.Tools.StandardCustomAttributeBuilder.GetAttributeDeclaration(Attribute attribute)
at System.Web.DomainServices.Tools.CustomAttributeGenerator.GenerateCustomAttributes(ClientProxyGenerator proxyGenerator, CodeTypeDeclaration referencingType, IEnumerable`1 attributes, CodeCommentStatementCollection comments)
at System.Web.DomainServices.Tools.CustomAttributeGenerator.GenerateCustomAttributes(ClientProxyGenerator proxyGenerator, CodeTypeDeclaration referencingType, IEnumerable`1 attributes, CodeAttributeDeclarationCollection outputCollection, CodeCommentStatementCollection comments)
at System.Web.DomainServices.Tools.EntityProxyGenerator.Generate()
at System.Web.DomainServices.Tools.ClientProxyGenerator.GenerateProxyClass(String& generatedCode)
at System.Web.DomainServices.Tools.CreateRiaClientFilesTask.GenerateClientProxies()
at System.Web.DomainServices.Tools.CreateRiaClientFilesTask.Execute()
at Microsoft.Build.Framework.ITask.Execute()
at Microsoft.Build.BuildEngine.TaskEngine.ExecuteInstantiatedTask(EngineProxy engineProxy, ItemBucket bucket, TaskExecutionMode howToExecuteTask, ITask task, Boolean& taskResult) SL
I know that using Fluent NHibernate should solve the problem because it removes the need for NHibernate dependencies, but I want to make sure first that there aren't any other solutions before moving to Fluent NHibernate. Any thoughts on solving this problem?
As I mentioned in the comments it sounds like the issue is with NHibernate throwing up during the code generation. If you really want to use the attributes I would suggest getting the NHibernate source code and trying to attach the VS debugger to the VS instance that is doing the code generation, might help you figure out why it is failing.
Probably a better approach would be to follow this post by Brada on using NHibernate with RIA Services or watching this screencast on NHibernate with RIA Services. Both of those places seem to have working examples of them working together, so maybe start there instead of going down the route you're going.
You can add preprocessor directives to your entities so that when compiled for silverlight the attributes are missing.
#if SILVERLIGHT
//nothing
#else
[class]
#endif
public class entity{
}
We had the same issue. Solution: Get rid of the attributes and just use XML for mapping.

Silverlight, Unity and INotifyPropertyChanged

I'm starting a new Silverlight project at the moment, and I'm having issues where by Unity is throwing an exception if my ViewModel (which it is instantiating for me) contains the RaisePropertyChanged event.
I looks like this:
public class AddNewClientViewModel : ViewModelBase {
private Visibility _extraClientFieldsVisible;
public Visibility ExtraClientFieldsVisible {
get {
return _extraClientFieldsVisible;
}
set {
_extraClientFieldsVisible = value;
base.RaisePropertyChanged("ExtraClientFieldsVisible");
}
}
public AddNewClientViewModel(IMyInterface blah) {
ExtraClientFieldsVisible = Visibility.Collapsed;
}
ViewModelBase which it inherits looks like this:
public abstract class ViewModelBase : INotifyPropertyChanged {
public event PropertyChangedEventHandler PropertyChanged;
public void RaisePropertyChanged(string propertyName) {
PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
}
}
The full stack trace is noted below, but it seems like calling the RaisePropertyChanged event during the constructor causes Unity to blowup.
Here's the full stack trace of the error:
Microsoft.Practices.Unity.ResolutionFailedException was unhandled by user code
Message="Resolution of the dependency failed, type = \"ClientSide.ViewModels.AddNewClientViewModel\", name = \"\". Exception message is: The current build operation (build key Build Key[ClientSide.ViewModels.AddNewClientViewModel, null]) failed: Object reference not set to an instance of an object. (Strategy type BuildPlanStrategy, index 3)"
TypeRequested="AddNewClientViewModel"
StackTrace:
at Microsoft.Practices.Unity.UnityContainer.DoBuildUp(Type t, Object existing, String name)
at Microsoft.Practices.Unity.UnityContainer.DoBuildUp(Type t, String name)
at Microsoft.Practices.Unity.UnityContainer.Resolve(Type t, String name)
at Microsoft.Practices.Unity.UnityContainerBase.Resolve(Type t)
at Microsoft.Practices.Unity.UnityContainerBase.Resolve[T]()
at ClientSide.Framework.ServiceLocator.get_AddNewClientViewModel()
InnerException: Microsoft.Practices.ObjectBuilder2.BuildFailedException
Message="The current build operation (build key Build Key[ClientSide.ViewModels.AddNewClientViewModel, null]) failed: Object reference not set to an instance of an object. (Strategy type BuildPlanStrategy, index 3)"
BuildKey="Build Key[ClientSide.ViewModels.AddNewClientViewModel, null]"
ExecutingStrategyIndex=3
ExecutingStrategyTypeName="BuildPlanStrategy"
StackTrace:
at Microsoft.Practices.ObjectBuilder2.StrategyChain.ExecuteBuildUp(IBuilderContext context)
at Microsoft.Practices.ObjectBuilder2.Builder.BuildUp(IReadWriteLocator locator, ILifetimeContainer lifetime, IPolicyList policies, IStrategyChain strategies, Object buildKey, Object existing)
at Microsoft.Practices.Unity.UnityContainer.DoBuildUp(Type t, Object existing, String name)
InnerException: System.NullReferenceException
Message="Object reference not set to an instance of an object."
StackTrace:
at ClientSide.ViewModels.ViewModelBase.RaisePropertyChanged(String propertyName)
at ClientSide.ViewModels.AddNewClientViewModel.set_ExtraClientFieldsVisible(Visibility value)
at ClientSide.ViewModels.AddNewClientViewModel..ctor(IDataCore dataCore)
at BuildUp_ClientSide.ViewModels.AddNewClientViewModel(IBuilderContext )
at Microsoft.Practices.ObjectBuilder2.DynamicMethodBuildPlan.BuildUp(IBuilderContext context)
at Microsoft.Practices.ObjectBuilder2.BuildPlanStrategy.PreBuildUp(IBuilderContext context)
at Microsoft.Practices.ObjectBuilder2.StrategyChain.ExecuteBuildUp(IBuilderContext context)
InnerException:
So I'm hitting a NullReferenceException. I can't just work out how...
Why not just check for null in RaisePropertyChanged()?
After all, it's not going to cause adverse side effects...

Resources