Tuesday, 9 February 2016

.Net remoting (via Spring.net) System.Security.SecurityException ReflectionEmit NHIbernate

Using Spring.Net to implement .Net remoting. Console app is server doing db connection va NHibernate. MVC website is client. Connected okay and server returned NHibernate entity-object when successfully logged in. Problem came when the Client attempted to call a remote object passing in the NHibernate entity. The call generated exception:
2016-02-09 11:31:30,503 [5] ERROR ControllerErrors - xxxxxxx.Common.MVCBase.ActionFilters.HandleException: Index: Exception has been thrown by the target of an invocation.
System.Reflection.TargetInvocationException: Exception has been thrown by the target of an invocation. ---> System.Security.SecurityException: Request for the permission of type 'System.Security.Permissions.ReflectionPermission, mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089' failed.
   at System.Security.CodeAccessSecurityEngine.Check(Object demand, StackCrawlMark& stackMark, Boolean isPermSet)
   at System.Security.CodeAccessPermission.Demand()
   at System.Reflection.Emit.AssemblyBuilder.DefineDynamicModuleInternalNoLock(String name, Boolean emitSymbolInfo, StackCrawlMark& stackMark)
   at System.Reflection.Emit.AssemblyBuilder.DefineDynamicModuleInternal(String name, Boolean emitSymbolInfo, StackCrawlMark& stackMark)
   at System.Reflection.Emit.AssemblyBuilder.DefineDynamicModule(String name, Boolean emitSymbolInfo)
   at Castle.DynamicProxy.ModuleScope.CreateModule(Boolean signStrongName)
   at Castle.DynamicProxy.ModuleScope.ObtainDynamicModuleWithWeakName()
   at Castle.DynamicProxy.ModuleScope.ObtainDynamicModule(Boolean isStrongNamed)
   at Castle.DynamicProxy.Generators.Emitters.ClassEmitter.CreateTypeBuilder(ModuleScope modulescope, String name, Type baseType, Type[] interfaces, TypeAttributes flags, Boolean forceUnsigned)
   at Castle.DynamicProxy.Generators.Emitters.ClassEmitter..ctor(ModuleScope modulescope, String name, Type baseType, Type[] interfaces, TypeAttributes flags, Boolean forceUnsigned)
   at Castle.DynamicProxy.Generators.Emitters.ClassEmitter..ctor(ModuleScope modulescope, String name, Type baseType, Type[] interfaces, TypeAttributes flags)
   at Castle.DynamicProxy.Generators.Emitters.ClassEmitter..ctor(ModuleScope modulescope, String name, Type baseType, Type[] interfaces)
   at Castle.DynamicProxy.Generators.BaseProxyGenerator.BuildClassEmitter(String typeName, Type parentType, Type[] interfaces)
   at Castle.DynamicProxy.Generators.BaseProxyGenerator.BuildClassEmitter(String typeName, Type parentType, IList interfaceList)
   at Castle.DynamicProxy.Generators.ClassProxyGenerator.GenerateCode(Type[] interfaces, ProxyGenerationOptions options)
   at Castle.DynamicProxy.Serialization.ProxyObjectReference.RecreateClassProxy()
   at Castle.DynamicProxy.Serialization.ProxyObjectReference.RecreateProxy()
   at Castle.DynamicProxy.Serialization.ProxyObjectReference..ctor(SerializationInfo info, StreamingContext context)
The action that failed was:
Demand
The type of the first permission that failed was:
System.Security.Permissions.ReflectionPermission
The first permission that failed was:


The demand was for:


The only permitted permissions were:




The method that caused the failure was:
System.Runtime.Remoting.Channels.ServerProcessing ProcessMessage(System.Runtime.Remoting.Channels.IServerChannelSinkStack, System.Runtime.Remoting.Messaging.IMessage, System.Runtime.Remoting.Channels.ITransportHeaders, System.IO.Stream, System.Runtime.Remoting.Messaging.IMessage ByRef, System.Runtime.Remoting.Channels.ITransportHeaders ByRef, System.IO.Stream ByRef)
   --- End of inner exception stack trace ---
Searching internet, it appeared it was to do with Trust Level of client. After lots of testing of trust settings & configuration was still getting the error. Noticed the in the stack trace the reference to Castle.DynamicProxy - made me think it was to do with NHibernate. Bit more researching and think I found the reason - code was throwing exception when serializing proxy object (which was a property of the NHibernate entity). Solution: On server app, set the TCP channel to have binary formatter with Full level filter-type. App.config:
<system.runtime.remoting> <application> <channels> <channel ref="tcp" port="8005" /> <serverProviders> <formatter ref="binary" typeFilterLevel="Full" /> </serverProviders> <clientProviders> <formatter ref="binary" /> </clientProviders> </channels> </application> </system.runtime.remoting>
Except... this didn't work. Under debugging, after the RemotingConfiguration.Configure("myapp.exe.config",false); call the RegisteredChannel still had a server-provider with Low level filter-type. To get it working had to change code to programmatically setup the channel:
                //// Creating a custom formatter for a TcpChannel sink chain.
                BinaryServerFormatterSinkProvider provider = new BinaryServerFormatterSinkProvider();
                provider.TypeFilterLevel = TypeFilterLevel.Full; // required for serialize/deserialize of NHibernate proxy objects
                IDictionary props = new Hashtable();
                props["port"] = 8005;
                //// Pass the properties for the port setting and the server provider in the server chain argument. (Client remains null here.)
                TcpChannel chan = new TcpChannel(props, null, provider);
                ChannelServices.RegisterChannel(chan, false);
Job done!

Thursday, 19 January 2012

Spring.Net - Could not load type ....

Was getting this error with Spring that came down to the fact one Dll was out of date - the Dll was Risk.dll and the config file throwing the error was Risk.xml.config  but this was clouded by another config file trying to set the same object also throwing the error.

I think Spring loaded the Risk.dll assembly and stored the bad/old reference e.g. IMyMovedObject as belonging to the old library so other objects which had reference to the same type also threw this error even though their build was up to date.

Thursday, 17 November 2011

NHibernate - HQL - No Persister for xxx

Was getting strange error ' No Persister for System.String' when doing HQL query using a parameter.

Turned out it was because I was using SetEntity to assign the parameter value instead of SetString

All because of cutting and pasting!

Monday, 19 October 2009

NHibernate - Entity property is an Interface - mapping

If you have a class that maps to a table and a property of the class is an association to another table (i.e. 1:M Property) you may get the following error if the property is defined as an interface type:

 

NHibernate An association from the table XYZ refers to an unmapped class

 

This occurs because NHibernate will not have a mapping file for the interface type and cannot instantiate it because it is an interface. To fix the problem you need to include in the mapping file the actual class the property represents.

e.g.

 

IAccount MainAccount;

 

may map to

 

<many-to-one name="MainAccount" column="MainAccountID" class="BankingCore.BusinessEntities.Account, BankingCore"/>

 

where BankingCore.BusinessEntities.Account is the actual class to be instantiated for the property.

Friday, 4 September 2009

Released: Who is to blame visual studio / subversion utility

Released free utility application: Who is to blame which allows the user to paste in warnings and errors from Visual Studio then get a report via Subversions Blame program of who edited the line.

Released Crystal Reports user library for BM+ pick-list lookup

Today we released for free download a user-library for substituting BM+ pick-list values into Crystal Reports.

The library can be downloaded by following the u2lBMPick link from Fairmort.com/Products

Monday, 24 August 2009

NHibernate HQL Query : could not resolve property

If you get

could not resolve property: ID: of

error for a HQL query and you know the property exists and is spelt correctly check that the query parameters are defined correctly.

Had this problem when query text was:

 

..... TaskStatus:=status ....

 

The problem is that the colon is the wrong side of the equals, should be

 

..... TaskStatus=:status ....

 

Error is easy typo to make but had to spot.

Friday, 20 February 2009

Task Scheduler : XP & Win 2003

WIN2003: Ensure Console is not logged in if trying to run task via Remote Console -

Following information taken from MS knowledge base: http://support.microsoft.com/kb/308558

 

Checking the Task Status

Periodically check the status of scheduled tasks, because sometimes you may not be aware that a scheduled task did not run. Use the Detail view in the Scheduled Task window to see the following information about each task:
  • Schedule - The schedule for the task.
  • Next Run Time - The time and date that the task is next scheduled to run.
  • Last Run Time - The time and date the task was last run.
  • Status - The current status of the task.
  • Last Result - Code that indicates the result of the last run.
The Status column has the following status and description information:
  • Blank - The task is not running, or it ran and was successful.
  • Running - The task is currently running.
  • Missed - One or more attempts to run this task was missed.
  • Could not start - The most recent attempt to start the task did not work.
The Last Result column displays a completion code. You can obtain a full explanation of all Windows completion codes from MSDN, but the common codes for scheduled tasks are:
  • 0x0: The operation completed successfully.
  • 0x1: An incorrect function was called or an unknown function was called.
  • 0xa: The environment is incorrect.
If the result code has the "C0000XXX" format, the task did not complete successfully (the "C" indicates an error condition). The most common "C" error code is "0xC000013A: The application terminated as a result of a CTRL+C".
Also check the following data in the task's properties:
  • Make sure the check box that turns on the task has a check mark.
  • Check the path to the program and make sure that it is correct. Also check the program to see if it requires some command-line parameters that are missing.
For a full explanation of Windows completion codes, visit the following Web site:

http://msdn2.microsoft.com/en-us/library/aa364454.aspx (http://msdn2.microsoft.com/en-us/library/aa364454.aspx)

Back to the top

Checking the Scheduled Tasks Log
Scheduled tasks maintains a log file (Schedlgu.txt), in the c:\Windows folder. You can view the log from the Scheduled Tasks window by clicking View Log on the Advanced menu.
The log file size is 32 kilobytes (KB), and when the file reaches its maximum size, it automatically starts to record new information at the beginning of the log file and writes over the old log file information.

Back to the top

Checking the Task Scheduler Service
The Task Scheduler service must be running and properly configured to run tasks. If you had stopped scheduled tasks manually from the Scheduled Tasks window, the service stops and does not initialize the next time you start the computer. If the service is not configured to log on as the local system account, it may not start.
To check the settings for the service:
  1. Click Start, click Control Panel, and then double-click Administrative Tools.
  2. Click Computer Management.
  3. Expand Services and Applications, and then click Services.
  4. Right-click the Task Scheduler service, and then click Properties.
  5. On the General tab, make sure that the startup type is set to automatic, and that the service status is Started. If the service is not running, click Start.
  6. On the Log On tab, make sure that the local system account is selected, and that the Allow service to interact with desktop check box has a check mark.
  7. Click OK, and then quit Computer Management.

Wednesday, 28 January 2009

Asp.Net to PDF export

Interesting article on exporting a GridView to PDF:

 

http://csharpdotnetfreak.blogspot.com/2008/12/export-gridview-to-pdf-using-itextsharp.html

 

Uses open-source project iTextSharp

Friday, 16 January 2009

Asp.Net encrypt connection string in web config

Quick note on how to encrypt the Connection string in the web.config for future reference
Encrypt the Connection string :
aspnet_regiis -pef "ConnectionString" "c:\path\to\website"

Grant Access to IIS to the key
aspnet_regiis -pa "NetFrameworkConfigurationKey" "NT Authority\Network Service"

note aspnet_regiis is in the .net framework directory for the version of .net that you are using

Wednesday, 15 October 2008

Rhino mocks - partial mock calling real method not mocked expectation

Had a few occasions where a Partial mock was calling the real method even though an expectation had been defined.

The reason was that the method being called was not marked as Virtual and so not being overridden by the mock repository.

Thursday, 25 September 2008

Encrypt / Decrypt Web.Config sections

See article here to encrypt or decrypt section of web.config file.

Thursday, 18 September 2008

VS2005 XML Comments not shown

XML Method comments are not being displayed by intellisense for methods of classes other than those in the same project.

Any referenced DLL must have the XML file which contains the comments in the same directory as the DLL itself.

Tuesday, 16 September 2008

Asp.Net - Simulate a windows service

Very interesting article here: CodeProject:AspNetService detailing how to simulate a windows service running completely within Aps.Net using cache item call backs.

Tuesday, 1 July 2008

.Net Setting up Intranet as Full Trust Zone

If the PC does not have the .NET SDK installed then the configuration tool will not be available via Control Panel -> Admin. Tools. Instead a command line tool CasPol.exe must be used:

The command line tool  exists in C:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\
The command for setting Intranet as full trust is:
CasPol.exe -q -m -ag All_Code -zone Intranet FullTrust

Wednesday, 28 May 2008

DataGridView - wrong row edited

When using the Edit functionality of a DataGridView it is easy to fall into the trap of selecting the wrong row to edit when running in a multi-user environment.

When user clicks row to edit you must store the ID of the row (not its index), then just prior to data-bind find the index of the selected ID in the data-source and set the EditIndex, this means if another user adds or removes rows in between the the current user clicking edit the correct row will be selected.

Tuesday, 13 May 2008

SQL Left Join with Criteria

Query to get job title of staff or null if staff not assign a job-title:

 

SELECT     CORE_Staff.ID, CORE_Staff.JobTitleID, CORE_JobTitle.Name
FROM        CORE_Staff  LEFT JOIN CORE_JobTitle
                       ON CORE_JobTitle.ID = CORE_Staff.JobTitleID
where (CORE_JobTitle.Name='Driver') or (CORE_JobTitle.Name is null)

Rhino Mocks - Partial mock not calling base method

Had a problem where I was creating a partial mock then calling a method of the partial mock which was returning 0 (zero).

The base method was not being called even though no expectations had been setup.

The reason for this was that the ReplayAll (and VerifyAll) methods of Rhino Mocks was not being called.

Original code:

            _interestBiz = _mocks.PartialMock<InterestBiz>();
int baseDay = _interestBiz.GetBaseDaysFromAccount(account);
Assert.AreEqual(365, baseDay, "Incorrect base days");


Fixed code:



            _interestBiz = _mocks.PartialMock<InterestBiz>();
using (_mocks.Record())
{

}

using (_mocks.Playback())
{
int baseDay = _interestBiz.GetBaseDaysFromAccount(account);
Assert.AreEqual(365, baseDay, "Incorrect base days");



 



So even though no expectations were set Rhino Mocks needs to no this.

Thursday, 1 May 2008

Good Rhino.Mocks introduction / tutorial

Good Rhino.Mocks introduction / tutorial here