How to configure NHibernate class mapping from IronPython? - nhibernate

I try to use NHibernate from IronPython. I have copied the NHibernate dependencies to my C:\Users\shamel\python\HelloPy\libs directory.
I have this IronPython code:
import sys
sys.path.append("C:\Users\shamel\python\HelloPy\libs")
import clr
clr.AddReference("NHibernate")
clr.AddReference("LinFu.DynamicProxy")
clr.AddReference("NHibernate.ByteCode.LinFu")
from Entities.Entity import Customer
from NHibernate.Cfg import Configuration
configuration = Configuration();
configuration.Configure("PocoLib.cfg.xml");
configuration.AddXmlFile("Customer.hbm.xml");
factory = configuration.BuildSessionFactory();
My entity classes are defined in Entity.py in the Entity package. That explains the from Entities.Entity import Customer.
Here is what my Customer.hbm.xml file look like
<?xml version="1.0" encoding="utf-8" ?>
<hibernate-mapping xmlns="urn:nhibernate-mapping-2.2"
assembly="Entities"
namespace="Entities">
<class name="Customer" lazy="false">
...
</class>
The program fails on the configuration.AddXmlFile("Customer.hbm.xml"); line:
configuration.AddXmlFile("Customer.hbm.xml");
StandardError: Could not compile the mapping document: Customer.hbm.xml
ERROR: Module: nhtests could not be imported.
I suppose NHibernate is not able to resolve the assembly and namespace specified in the hibernate-mapping header. (The problem is not that the xml file is not found; I tried with a name that does not exist and I get a different error)
Any help will be greatly appreciated.
Sly
EDIT: 27 Dec 2009: Here is the stack trace. I think it confirms that NHibernate is not able to find my types.
*** Outer ***
MappingException
persistent class Entities.Customer, Entities not found
at Microsoft.Scripting.Actions.Calls.MethodCandidate.Caller.CallWithInstance(Object[] args, Boolean& shouldOptimize)
at IronPython.Runtime.Types.BuiltinFunction.BuiltinMethodCaller`2.Call1(CallSite site, CodeContext context, TFuncType func, T0 arg0)
at System.Dynamic.UpdateDelegates.UpdateAndExecute3[T0,T1,T2,TRet](CallSite site, T0 arg0, T1 arg1, T2 arg2)
at Microsoft.Scripting.Utils.InvokeHelper`6.Invoke(Object arg0, Object arg1, Object arg2, Object arg3, Object arg4)
at Microsoft.Scripting.Utils.ReflectedCaller.Invoke(Object[] args)
at Microsoft.Scripting.Interpreter.CallInstruction.Run(InterpretedFrame frame)
at Microsoft.Scripting.Interpreter.Interpreter.Run(InterpretedFrame frame)
*** Inner ***
MappingException
persistent class Entities.Customer, Entities not found
at NHibernate.Cfg.XmlHbmBinding.Binder.ClassForFullNameChecked(String fullName, String errorMessage)
at NHibernate.Cfg.XmlHbmBinding.ClassBinder.BindClass(XmlNode node, IDecoratable classMapping, PersistentClass model, IDictionary`2 inheritedMetas)
at NHibernate.Cfg.XmlHbmBinding.RootClassBinder.Bind(XmlNode node, HbmClass classSchema, IDictionary`2 inheritedMetas)
at NHibernate.Cfg.XmlHbmBinding.MappingRootBinder.AddRootClasses(XmlNode parentNode, IDictionary`2 inheritedMetas)
at NHibernate.Cfg.XmlHbmBinding.MappingRootBinder.Bind(XmlNode node)
at NHibernate.Cfg.Configuration.AddValidatedDocument(NamedXmlDocument doc)
*** Inner Inner ***
FileNotFoundException
Could not load file or assembly 'Entities' or one of its dependencies. The system cannot find the file specified.
at System.Reflection.Assembly._nLoad(AssemblyName fileName, String codeBase, Evidence assemblySecurity, Assembly locationHint, StackCrawlMark& stackMark, Boolean throwOnFileNotFound, Boolean forIntrospection)
at System.Reflection.Assembly.nLoad(AssemblyName fileName, String codeBase, Evidence assemblySecurity, Assembly locationHint, StackCrawlMark& stackMark, Boolean throwOnFileNotFound, Boolean forIntrospection)
at System.Reflection.Assembly.InternalLoad(AssemblyName assemblyRef, Evidence assemblySecurity, StackCrawlMark& stackMark, Boolean forIntrospection)
at System.Reflection.Assembly.InternalLoad(String assemblyString, Evidence assemblySecurity, StackCrawlMark& stackMark, Boolean forIntrospection)
at System.Reflection.Assembly.Load(String assemblyString)
at NHibernate.Util.ReflectHelper.TypeFromAssembly(AssemblyQualifiedTypeName name, Boolean throwOnError)
at NHibernate.Util.ReflectHelper.ClassForName(String name)
at NHibernate.Cfg.XmlHbmBinding.Binder.ClassForFullNameChecked(String fullName, String errorMessage)
EDIT 29 Dec 2009 :
Even after I solve the namespace/assembly name issue, I don't think Nhibernate will be able to save/load my Python entities. As far as a now understand, when a Python instance is passed to a statically typed library (such as NHibernate), that library does not see its members. So Nhibernate will not find any property on my type because those properties are not visible to statically typed libraries. In order for this to work, NHibernate would have to support DLR integration, possibly using the C# 4.0 Dynamic keyword. To be continued...

It is not possible to use NHibernate from IronPython on entities defines in IronPython.

Related

Akka.Net Persistence with MongoDB

I'm trying to implement Akka Persistence using Mongodb and I am getting an error that says
"Method 'DeleteAsync' in type
'Akka.Persistence.MongoDb.Snapshot.MongoDbSnapshotStore' from assembly
'Akka.Persistence.MongoDb, Version=1.0.4.1, Culture=neutral,
PublicKeyToken=null' does not have an implementation"
Here is my configuration:
var config = ConfigurationFactory.ParseString(#"
akka {
persistence {
publish-plugin-commands = on
snapshot-store {
plugin = ""akka.persistence.snapshot-store.mongodb""
mongodb {
class = ""Akka.Persistence.MongoDb.Snapshot.MongoDbSnapshotStore, Akka.Persistence.MongoDb""
connection-string = ""mongodb://user:pass#paulo.mongohq.com:10083/DbName""
collection = ""AkkaSnapshotStore""
}
}
journal {
plugin = ""akka.persistence.journal.mongodb""
mongodb {
class = ""Akka.Persistence.MongoDb.Journal.MongoDbJournal, Akka.Persistence.MongoDb""
connection-string = ""mongodb://user:pass#paulo.mongohq.com:10083/DbName""
collection = ""AkkaEventJournal""
}
}
}
}");
I think i have created an actor system correctly:
https://gist.github.com/amarwadi/a887b26e14b0d42191b7
and am sending a message to a Persistent Actor and I keep getting the following message infinitely
[ERROR][1/2/2016 2:36:36 AM][Thread 0011][akka://example123/user/section-actor] Method 'DeleteAsync' in type 'Akka.Persistence.MongoDb.Snapshot.MongoDbSnapshotStore' from assembly 'Akka.Persistence.MongoDb, Version=1.0.4.1, Culture=neutral, PublicKeyToken=null' does not have an implementation.
Cause: System.TypeLoadException: Method 'DeleteAsync' in type 'Akka.Persistence.MongoDb.Snapshot.MongoDbSnapshotStore' from assembly 'Akka.Persistence.MongoDb, Version=1.0.4.1, Culture=neutral, PublicKeyToken=null' does not have an implementation.
at System.RuntimeTypeHandle.GetTypeByName(String name, Boolean throwOnError, Boolean ignoreCase, Boolean reflectionOnly, StackCrawlMarkHandle stackMark, IntPtr pPrivHostBinder, Boolean loadTypeFromPartialName, ObjectHandleOnStack type)
at System.RuntimeTypeHandle.GetTypeByName(String name, Boolean throwOnError, Boolean ignoreCase, Boolean reflectionOnly, StackCrawlMark& stackMark, IntPtr pPrivHostBinder, Boolean loadTypeFromPartialName)
at System.RuntimeType.GetType(String typeName, Boolean throwOnError, Boolean ignoreCase, Boolean reflectionOnly, StackCrawlMark& stackMark)
at System.Type.GetType(String typeName, Boolean throwOnError)
at Akka.Persistence.PersistenceExtension.CreatePlugin(String configPath, Func2 dispatcherSelector) at Akka.Persistence.PersistenceExtension.<>c__DisplayClass13_0.<SnapshotStoreFor>b__0() at System.Lazy1.CreateValue()
--- End of stack trace from previous location where exception was thrown ---
at System.Lazy`1.get_Value()
at Akka.Persistence.PersistenceExtension.SnapshotStoreFor(String snapshotPluginId)
at Akka.Persistence.Eventsourced.get_SnapshotStore()
at Akka.Persistence.Eventsourced.LoadSnapshot(String persistenceId, SnapshotSelectionCriteria criteria, Int64 toSequenceNr)
at Akka.Persistence.Eventsourced.b__76_0(Receive receive, Object message)
at Akka.Persistence.Eventsourced.AroundReceive(Receive receive, Object message)
at Akka.Actor.ActorCell.ReceiveMessage(Object message)
at Akka.Actor.ActorCell.Invoke(Envelope envelope)
Per an update from the developers of Akka.NET Persistence on MongoDB, this was broken in persistence in mongo with the introduction of 1.0.5. It will be corrected shortly.
https://github.com/akkadotnet/Akka.Persistence.MongoDB/issues/12

Visual Studio 2013 designer trying to load wrong version of project DLL

I have a visual studio project in a solution that references a class library project from the same solution. The project compiles and executes just fine. However, when I try to open one form in the designer I get a message:
Could not load file or assembly 'MyLibName, Version=1.0.5477.26907, Culture=neutral, PublicKeyToken=null' or one of its dependencies. The system cannot find the file specified.
However, the current version of the DLL is: 1.0.5510.41110
Why is the designer trying to look for an old version? How can I open my form in the designer?
I've tried removing this library from all the projects that reference it in my project and re-adding it. And, of course, I've tried cleaning and rebuilding the project from scratch. Any help appreciated.
Here's the stack trace:
at System.Reflection.RuntimeAssembly._nLoad(AssemblyName fileName, String codeBase, Evidence assemblySecurity, RuntimeAssembly locationHint, StackCrawlMark& stackMark, IntPtr pPrivHostBinder, Boolean throwOnFileNotFound, Boolean forIntrospection, Boolean suppressSecurityChecks)
at System.Reflection.RuntimeAssembly.nLoad(AssemblyName fileName, String codeBase, Evidence assemblySecurity, RuntimeAssembly locationHint, StackCrawlMark& stackMark, IntPtr pPrivHostBinder, Boolean throwOnFileNotFound, Boolean forIntrospection, Boolean suppressSecurityChecks)
at System.Reflection.RuntimeAssembly.InternalLoadAssemblyName(AssemblyName assemblyRef, Evidence assemblySecurity, RuntimeAssembly reqAssembly, StackCrawlMark& stackMark, IntPtr pPrivHostBinder, Boolean throwOnFileNotFound, Boolean forIntrospection, Boolean suppressSecurityChecks)
at System.Reflection.RuntimeAssembly.InternalLoad(String assemblyString, Evidence assemblySecurity, StackCrawlMark& stackMark, IntPtr pPrivHostBinder, Boolean forIntrospection)
at System.Reflection.RuntimeAssembly.InternalLoad(String assemblyString, Evidence assemblySecurity, StackCrawlMark& stackMark, Boolean forIntrospection)
at System.Reflection.Assembly.Load(String assemblyString)
at System.UnitySerializationHolder.GetRealObject(StreamingContext context)
at System.Runtime.Serialization.ObjectManager.ResolveObjectReference(ObjectHolder holder)
at System.Runtime.Serialization.ObjectManager.DoFixups()
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)
Finally got it--seems I'd accidentally serialized an instantiation of an object from the older library version in a user control's public property on this form.
To resolve the issue:
1) I manually edited the .resx file in notepad and removed the base64 encoded binary data for the accidentally serialized property.
2) I followed the directions here to prevent my property from being serialized in the future, ie. I added this attribute:
[DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]

System.InvalidOperationException on Sample Code

I am using some existing sample code given to me from FedEx.com for tracking packages. However, I cannot get it to work for the life of me. Would anyone know what the following means:
System.InvalidOperationException was unhandled
Message="Unable to generate a temporary class (result=1). error CS0029: Cannot implicitly convert
type 'AddressValidationWebServiceClient.AddressValidationWebReference.ParsedElement'
to 'AddressValidationWebServiceClient.AddressValidationWebReference.ParsedElement[]' "
Source="System.Xml"
StackTrace:
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.GetSerializersFromCache(XmlMapping[] mappings, Type type)
at System.Xml.Serialization.XmlSerializer.FromMappings(XmlMapping[] mappings, Type type)
at System.Web.Services.Protocols.SoapClientType..ctor(Type type)
at System.Web.Services.Protocols.SoapHttpClientProtocol..ctor()
at AddressValidationWebServiceClient.AddressValidationWebReference.AddressValidationService..ctor() in C:\Documents and Settings\jessey\My Documents\Visual Studio 2008\Projects\AddressValidationWebServiceClient\Web References\AddressValidationWebReference\Reference.vb:line 40
at AddressValidationWebServiceClient.AddressValidationWebServiceClient.Main() in C:\Documents and Settings\jessey\My Documents\Visual Studio 2008\Projects\AddressValidationWebServiceClient\AddressValidationWebServiceClient.vb:line 28
at System.AppDomain._nExecuteAssembly(Assembly assembly, String[] args)
at System.AppDomain.ExecuteAssembly(String assemblyFile, Evidence assemblySecurity, String[] args)
at Microsoft.VisualStudio.HostingProcess.HostProc.RunUsersAssembly()
at System.Threading.ThreadHelper.ThreadStart_Context(Object state)
at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state)
at System.Threading.ThreadHelper.ThreadStart()
The offending line of code is:
Dim service As AddressValidationService = New AddressValidationService()

CannotCreateCustomizationDomainException: Customization could not be loaded because the application domain could not be created

I'm trying to run an Excel 2007 VSTO 3.0 addin we've created. However since installing the ION Trading MarketView Excel Plug-in our add-in no longer seems to load properly and fails with the following error:
Microsoft.VisualStudio.Tools.Applications.Runtime.CannotCreateCustomizationDomainException: Customization could not be loaded because the application domain could not be created. ---> System.IO.FileLoadException: Loading this assembly would produce a different grant set from other instances. (Exception from HRESULT: 0x80131401)
at System.RuntimeTypeHandle.CreateInstance(RuntimeType type, Boolean publicOnly, Boolean noCheck, Boolean& canBeCached, RuntimeMethodHandle& ctor, Boolean& bNeedSecurityCheck)
at System.RuntimeType.CreateInstanceSlow(Boolean publicOnly, Boolean fillCache)
at System.RuntimeType.CreateInstanceImpl(Boolean publicOnly, Boolean skipVisibilityChecks, Boolean fillCache)
at System.Activator.CreateInstance(Type type, Boolean nonPublic)
at System.RuntimeType.CreateInstanceImpl(BindingFlags bindingAttr, Binder binder, Object[] args, CultureInfo culture, Object[] activationAttributes)
at System.Activator.CreateInstance(Type type, BindingFlags bindingAttr, Binder binder, Object[] args, CultureInfo culture, Object[] activationAttributes)
at System.Activator.CreateInstance(String assemblyName, String typeName, Boolean ignoreCase, BindingFlags bindingAttr, Binder binder, Object[] args, CultureInfo culture, Object[] activationAttributes, Evidence securityInfo, StackCrawlMark& stackMark)
at System.Activator.CreateInstance(String assemblyName, String typeName)
at System.AppDomain.CreateInstance(String assemblyName, String typeName)
at System.AppDomain.CreateInstanceAndUnwrap(String assemblyName, String typeName)
at System.AppDomain.CreateInstanceAndUnwrap(String assemblyName, String typeName)
at Microsoft.VisualStudio.Tools.Office.Runtime.DomainCreator.LoadMafPipeline(AppDomain newDomain, IntPtr hostServiceProvider, AddInInformation info, EntryPoints requestedEntryPoints, OfficeApp officeApplication, OfficeVersion officeVersion, IntPtr& executor)
at Microsoft.VisualStudio.Tools.Office.Runtime.DomainCreator.CreateCustomizationDomainInternal(String solutionLocation, String manifestName, String documentName, Boolean showUIDuringDeployment, IntPtr hostServiceProvider, IntPtr& executor)
--- End of inner exception stack trace ---
Does anyone have any idea what could be causing this? Any pointers for how I could investigate further?
Thanks,
Tom
Here are some tips you may find on web, in order to fix the problem:
Reinstall VSTOR
Disable other add-ins
Install framework 3.5 sp1
Fix error in the security configuration on the computer that is running the Visual Studio Tools for Office solution
Modify/Disable custom rule of a company's virus software, blocking the .net framework ability to create the 'shadow copy' version of the vsto .dll.
Turn on .NET programmability support http://sqlblog.com/blogs/davide_mauri/archive/2010/07/30/powerpivot-not-visibile-in-excel.aspx
Move the entire solution to .NET 4.0

NHibernate + Remoting = ReflectionPermission Exception

We are dealing with a problem when using NHibernate with Remoting in a machine with full trust enviroment (actually that's our dev machine).
The problem happens when whe try to send as a parameter an object previously retrieved from the server, that contains a NHibernate Proxy in one of the properties (a lazy one).
As we are in the dev machine, there's no restriction in the trust level of the web app (it's set to Full) and, as a plus, we've configured NHibernate's and Castle's assemblies to full trust in CAS (even thinking that it'd not be necessary as the remoting app in IIS has the full trust level).
Does anyone have any idea of what can be causing this exception? Stack trace below.
InnerException: System.Security.SecurityException
Message="Falha na solicitação da permissão de tipo 'System.Security.Permissions.ReflectionPermission, mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089'."
Source="mscorlib"
GrantedSet=""
PermissionState="<IPermission class=\"System.Security.Permissions.ReflectionPermission, mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089\"\r\nversion=\"1\"\r\nFlags=\"ReflectionEmit\"/>\r\n"
RefusedSet=""
Url=""
StackTrace:
em System.Security.CodeAccessSecurityEngine.Check(Object demand, StackCrawlMark& stackMark, Boolean isPermSet)
em System.Security.CodeAccessPermission.Demand()
em System.Reflection.Emit.AssemblyBuilder.DefineDynamicModuleInternalNoLock(String name, Boolean emitSymbolInfo, StackCrawlMark& stackMark)
em System.Reflection.Emit.AssemblyBuilder.DefineDynamicModuleInternal(String name, Boolean emitSymbolInfo, StackCrawlMark& stackMark)
em System.Reflection.Emit.AssemblyBuilder.DefineDynamicModule(String name, Boolean emitSymbolInfo)
em Castle.DynamicProxy.ModuleScope.CreateModule(Boolean signStrongName)
em Castle.DynamicProxy.ModuleScope.ObtainDynamicModuleWithWeakName()
em Castle.DynamicProxy.ModuleScope.ObtainDynamicModule(Boolean isStrongNamed)
em Castle.DynamicProxy.Generators.Emitters.ClassEmitter.CreateTypeBuilder(ModuleScope modulescope, String name, Type baseType, Type[] interfaces, TypeAttributes flags, Boolean forceUnsigned)
em Castle.DynamicProxy.Generators.Emitters.ClassEmitter..ctor(ModuleScope modulescope, String name, Type baseType, Type[] interfaces, TypeAttributes flags, Boolean forceUnsigned)
em Castle.DynamicProxy.Generators.Emitters.ClassEmitter..ctor(ModuleScope modulescope, String name, Type baseType, Type[] interfaces, TypeAttributes flags)
em Castle.DynamicProxy.Generators.Emitters.ClassEmitter..ctor(ModuleScope modulescope, String name, Type baseType, Type[] interfaces)
em Castle.DynamicProxy.Generators.BaseProxyGenerator.BuildClassEmitter(String typeName, Type parentType, Type[] interfaces)
em Castle.DynamicProxy.Generators.BaseProxyGenerator.BuildClassEmitter(String typeName, Type parentType, IList interfaceList)
em Castle.DynamicProxy.Generators.ClassProxyGenerator.GenerateCode(Type[] interfaces, ProxyGenerationOptions options)
em Castle.DynamicProxy.Serialization.ProxyObjectReference.RecreateClassProxy()
em Castle.DynamicProxy.Serialization.ProxyObjectReference.RecreateProxy()
em Castle.DynamicProxy.Serialization.ProxyObjectReference..ctor(SerializationInfo info, StreamingContext context)
Thank you in advance.
Actually, I work with Pedro, we found the problem: the serializer of the Remoting Service has to be explicit configured to allow full trust calls in the server side.
Something like (configuration file):
<channels>
<channel ref="http">
<serverProviders>
<provider ref="wsdl" />
<formatter ref="soap" typeFilterLevel=Low />
<formatter ref="binary" typeFilterLevel=Low />
</serverProviders>
</channel>
</channels>
Or (programatically):
BinaryServerFormatterSinkProvider provider = new BinaryServerFormatterSinkProvider();
provider.TypeFilterLevel = TypeFilterLevel.Full;
Hope this helps anyone else.
Regards.