BizTalk BRE InvalidCastException - biztalk

I have configured a new VM (MS Virtual Server running Windows Server 2003) as a copy of an existing VM hosting BizTalk server 2006. I have run into a problem with BRE processing. The policy is deployed and vocabulary published exactly as on the working VM.
An orchestration calls a helper component which in turn makes use of the BRE components. The last line in the helper component that seems to execute is:
Policy workflowPolicy = new Policy(policyName)
I have pasted the stack trace from the event log below:
Exception type: InvalidCastException
Source: Microsoft.RuleEngine
Target Site: Int32 GetInt32(System.String, Int32)
The following is a stack trace that identifies the location where the exception occured
at Microsoft.RuleEngine.Configuration.GetInt32(String key, Int32 defaultValue)
at Microsoft.RuleEngine.ReteTranslator.RuleSetToReteTranslatorImpl.Translate(RuleSet ruleset, Int32 duration)
at Microsoft.RuleEngine.ReteTranslator.RuleSetToReteTranslator.Translate(RuleSet ruleset, Int32 duration)
at Microsoft.RuleEngine.RuleEngine..ctor(RuleSet ruleSet, Boolean doOptimizations)
at Microsoft.RuleEngine.RuleEngineCache.Allocate(String rulesetName, Int32 majorRevision, Int32 minorRevision, TrackingConfiguration& trackingConfig)
at Microsoft.RuleEngine.RuleEngineCache.Allocate(String rulesetName, TrackingConfiguration& trackingConfig)
at Microsoft.RuleEngine.Policy..ctor(String policyName)
at Tesco.BRE.Services.PolicyServices.Direct.OrderWorkflowServices.Commands.GetNextTaskList.Execute()
at Tesco.DataSources.Integration.Common.CommandBase.CommandDecorators.CommandLoggingDecorator`1.Execute()
at Tesco.DataSources.Integration.Common.CommandBase.CommandUtilities.GetCommandResponse[T](CommandBase`1 command)
at Tesco.BRE.Services.PolicyServices.Direct.OrderWorkflowServices.OrderWorkflowOperations.GetNextTaskList(String currentTaskName, String currentTaskStatus, XmlDocument order)
at Tesco.Direct.OrderManagement.Orchestrations.FollowTaskResult.segment2(StopConditions stopOn)
at Microsoft.XLANGs.Core.SegmentScheduler.RunASegment(Segment s, StopConditions stopCond, Exception&
It looks like Microsoft.RuleEngine.Configuration.GetInt32 is being passed a value that cannot be cast to an Int32?
I have tried un-configuring / re-configuring the BRE. As far as I can tell everything on the new server is configured exactly as per the working server.
Any help, gratefully receive - I've been stuck with this all day!

If one follow the stack trace one could read "cache" and "tracking". I would try to restart the host and uncheck any rule tracking in HAT.

Thanks for your response Martin. I have now fixed the issue. The problem was user error (mine) in making a registry change. I had to create a reg setting as follows
HKLM\SOFTWARE\Microsoft\BusinessRules\3.0\StaticSupport (DWORD), value 2
in order to enable the BRE to make use of static methods. This is described at: http://technet.microsoft.com/en-us/library/dd298814.aspx
Although I had made the addition when configuring the server, I had inadvertently used a string rather than a dword. Since this cost me over a day to figure out - I won't be making the same mistake any time soon!

Related

EntityException: The underlying provider failed on Open. Can one server closing a db connection, make another server fail on opening?

I am experiencing database connection errors with an ASP.NET application written in VB, running on three IIS servers. The underlying database is MS Access, which is on a shared network device. It uses Entity Framework, code first implementation and JetEntityFrameworkProvider.
The application is running stable. But, approximately 1 out of 1000 attempts to open the database connection fails with either one of the following two errors:
06:33:50 DbContext "Failed to open connection at 2/12/2020 6:33:50 AM +00:00 with error:
Cannot open database ''. It may not be a database that your application recognizes, or the file may be corrupt.
Or
14:04:39 DbContext "Failed to open connection at 2/13/2020 2:04:39 PM +00:00 with error:
Could not use ''; file already in use.
One second later, with refreshing (F5), the error is gone and it works again.
Details about the environment and used code.
Connection String
<add name="DbContext" connectionString="Provider=Microsoft.Jet.OLEDB.4.0;Data Source=x:\thedatabase.mdb;Jet OLEDB:Database Password=xx;OLE DB Services=-4;" providerName="JetEntityFrameworkProvider" />
DbContext management
The application uses public property to access DbContext. DbContext is kept in the HttpContext.Current.Items collection for the lifetime of the request, and is disposed at it’s end.
Public Shared ReadOnly Property Instance() As DbContext
Get
SyncLock obj
If Not HttpContext.Current.Items.Contains("DbContext") Then
HttpContext.Current.Items.Item("DbContext") = New DbContext()
End If
Return HttpContext.Current.Items.Item("DbContext")
End SyncLock
End Get
End Property
BasePage inits and disposes the DbContext.
Protected Overrides Sub OnInit(e As EventArgs)
MyBase.OnInit(e)
DbContext = Data.DbContext.Instance
...
End Sub
Protected Overrides Sub OnUnload(e As EventArgs)
MyBase.OnUnload(e)
If DbContext IsNot Nothing Then DbContext.Dispose()
End Sub
What I have tried
Many of the questions on SO which address above error messages, deal with generally not being able to establish a connection to the database – they can’t connect at all. That’s different with this case. Connection works 99,99% of the time.
Besides that, I have checked:
Permissions: Full access is granted for share where .mdb (database) and .ldb (locking file) resides.
Network connection: there are no connection issues to the shared device; it’s a Gigabit LAN connection
Maximum number of 255 concurrent connections is not reached
Maximum size of database not exceeded (db has only 5 MB)
Changed the compile option from “Any CPU” to “x86” as suggested in this MS Dev-Net post
Quote: I was getting the same "Cannot open database ''" error, but completely randomly (it seemed). The MDB file was less than 1Mb, so no issue with a 2Gb limit as mentioned a lot with this error.
It worked 100% on 32 bit versions of windows, but I discovered that the issues were on 64 bit installations.
The app was being compiled as "Any CPU".
I changed the compile option from "Any CPU" to "x86" and the problem has disappeared.
Nothing helped so far.
To gather more information, I attached an Nlog logger to the DbContext which writes all database actions and queries to a log file.
Shared Log As Logger = LogManager.GetLogger("DbContext")
Me.Database.Log = Sub(s) Log.Debug(s)
Investigating the logs I figured out that when one of the above errors occured on one server, another one of the servers (3 in total) has closed the db connection at exactly the same time.
Here two examples which correspond to the above errors:
06:33:50 DbContext "Closed connection at 2/12/2020 6:33:50 AM +00:00
14:04:39 DbContext "Closed connection at 2/13/2020 2:04:39 PM +00:00
Assumption
When all connections of a DbContext have been closed, the according record is removed from the .ldb lock file. When a connection to the db is being opened, a record will be added to the lock file. When these two events occur at the exact same time, from two different servers, there is a write conflict to the .ldb lock file, which results in on of the errors from above.
Question
Can anyone confirm or prove this wrong? Has anyone experienced this behaviour? Maybe I am missing something else. I’d appreciate your input and experience on this.
If my assumption is true, a solution could be to use a helper class for accessing db, which catches and handles this error, waiting for a minimal time period and trying again.
But this feels kind of wrong. So I am also open to suggestions for a “proper” solution.
EDIT: The "proper" solution would be using a DBMS Server (as stated in the comments below). I'm aware of this. For now, I have to deal with this design mistake without being responsible for it. Also, I can't change it in the short run.
I write this as an aswer because of space but this is not really an answer.
It's for sure an OleDb provider issue.
I think that is a sharing issue.
You could do some tries:
use a newer OleDb provider instead of Microsoft.Jet.OLEDB.4.0. (if you have try 64 bits you could already have try another provider because Jet.OLEDB.4.0 is 32 bits only)
Implement a retry mechanism on the new DbContext()
Reading your tests this is probaly not your case. I THINK that Dispose does not always work properly on Jet.OLEDB.4.0 connections. I noted it on tests and I solved it using a different testing engine. Before giving up I used this piece of code
GC.Collect(GC.MaxGeneration, GCCollectionMode.Forced, true);
GC.WaitForPendingFinalizers();
GC.Collect(GC.MaxGeneration, GCCollectionMode.Forced, true);
As you can understand reading this code, they are tries and the latest solution was changing the testing engine.
If your app is not too busy you could try to lock the db using a different mechanism (for example using a lock file). This is not really different from new DbContext() retries.
In late '90s I remember I had an issue related to disk sharing OS (I were using Novel Netware). Actually I have not experience in using mdb files on a network share. You could try to move the mdb on a folder shared with Windows
Actually I use Access databases only for tests. If you really need to use a single file database you could try other solutions: SQL Lite (you need a library, also this written by me, to apply code first https://www.nuget.org/packages/System.Data.SQLite.EF6.Migrations/ ) or SQL Server CE
Use a DBMS Server. This is for sure the best solution. As the writer of JetEntityFrameworkProvider I think that single file databases are great for single user apps (for this apps I suggest SQL Lite), for tests (I think that for tests JetEntityFrameworkProvider is great), for transfering data or, also, for readonly applications. In other cases use a DBMS Server. As you know, with EF, you can change from JetEntityFrameworkProvider to SQL Server or to MySql without effort.
You went wrong at the design stage: The MS Access database engine is unfit for ASP.Net sites, and this is explicitly stated on multiple places, e.g. the official download page under details.
The Access Database Engine 2016 Redistributable is not intended .... To be used by ... a program called from server-side web application such as ASP.NET
If you really have to work with an Access database, you can run a helper class that retries in case of common errors. But I don't recommend it.
The proper solution here is using a different RDBMS which exhibits stateless behavior. I recommend SQL Server Express, which has limitations, but if you exceed those you will be far beyond what Access supports, and wont cause errors like this.

ASP .net core time out error using Oracle

I'm new to ASP .Net Core and am working my way through a demo project to learn the tech stack.
My project is using .net core 2.2 and Oracle.ManagedDataAccess.Core and Oracle.EntityFramework.Core.
I created a model and then went and scaffolded my view and controller through VS 2019. I've set up ConfigureService(...) to use Oracle. I added an HTML link on my main index page to hook into the view created for my model. When it calls the Controller::Index() function, I end up getting the following timeout error
OracleException: Connection request timed out
OracleInternal.ConnectionPool.PoolManager<PM, CP, PR>.Get(ConnectionString csWithDiffOrNewPwd, bool bGetForApp, OracleConnection connRefForCriteria, string affinityInstanceName, bool bForceMatch)
Any help or guidance as to what I could be doing wrong would be greatly appreciated!
It looks like a error connecting to the database.
There are some things you should check:
Make sure the connection string to the database, stored in the appsettings.json is correct.
Make sure to have a firewall rule which allows inbound traffic to the port from where the Oracle db is listening.
If the problem persists then you should provide the code you are using to access the database.

Unable to cast object of type 'System.Guid' to type 'System.IConvertible'

I'm trying to use the WCF-SQL adaptor in BizTalk 2013 to return records from a stored procedure.
I followed a simple online walkthrough that seemed to get me what I need.
However I keep getting a casting error when the Receive Location runs. I dont have any GUID's in my SP. I have even simplified my SP to a SQL statement returning hard coded strings.
SELECT [Description] , PackageName FROM ( SELECT 'ABC' [Description] ,'123' as PackageName ) as ResponseTable
the Schema expects two fields of type string.
See error below.
The receive location "Receive - Package" with URL "mssql://xxx/xxx?InboundId=PackageErrors" is shutting down. Details:"Microsoft.ServiceModel.Channels.Common.AdapterException: Unable to cast object of type 'System.Guid' to type 'System.IConvertible'.. Endpoint Address - mssql://xxx/xxx?InboundId=PackageErrors ---> <b>System.InvalidCastException: Unable to cast object of type 'System.Guid' to type 'System.IConvertible'.</b>
at Microsoft.Adapters.Sql.SqlAdapterInboundHandler.Polling_WaitForMessage(TimeoutHelper timeoutHelper)
at Microsoft.Adapters.Sql.SqlAdapterInboundHandler.WaitForMessage(TimeSpan timeout)
--- End of inner exception stack trace ---
at Microsoft.Adapters.Sql.SqlAdapterInboundHandler.WaitForMessage(TimeSpan timeout)
at Microsoft.ServiceModel.Channels.Common.Channels.AdapterInputChannel.WaitForMessage(TimeSpan timeout)
at System.ServiceModel.Dispatcher.ErrorHandlingReceiver.WaitForMessage()".
That walk through is wrong in one aspect.
Rather than using the "Add Adapter Metadata" you would be better of using the "Consume Adapter Service", select the sqlBinding, Configure the URI, Connect, select Service (Inbound operations) for the contract type and select your stored procedure from there.
This will have the added benefits creating a binding file for your receive location, which you can then import and will be correctly configured. It doesn't create an Orchestration like the Add Adapter Metadata, but I actually prefer that.

Inner SecurityException while using XmlSerializer

While creating a custom Sharepoint web service I received an error while attempting to serialise a class for transmission.
There are no errors with my serializable classes. They are structured in a manner I have used before and can be serialised successfully on a local test environment, the issue only arises when the Sharepoint web service has been deployed.
System.InvalidOperationException was caught
Message=There was an error generating the XML document.
Source=System.Xml
StackTrace:
at System.Xml.Serialization.XmlSerializer.Serialize(XmlWriter xmlWriter, Object o, XmlSerializerNamespaces namespaces, String encodingStyle, String id)
at System.Xml.Serialization.XmlSerializer.Serialize(TextWriter textWriter, Object o, XmlSerializerNamespaces namespaces)
at SPServiceExtensions.DTOSerializerHelper.SerializeDTO(SharepointDTO dto)
InnerException: System.Security.SecurityException
Message=Request failed.
Source=xo46jp-i
StackTrace:
at Microsoft.Xml.Serialization.GeneratedAssembly.XmlSerializationWriterSharepointDTO.Write4_SharepointDTO(String n, String ns, SharepointDTO o, Boolean isNullable, Boolean needType)
at Microsoft.Xml.Serialization.GeneratedAssembly.XmlSerializationWriterSharepointDTO.Write5_SharepointDTO(Object o)
InnerException:
The inner SecurityException was unfamiliar. What is causing this Exception?
ASP.NET uses different trust levels for it's security policies. This is so applications cannot access the data from other unrelated applications.
Microsoft Sharepoint has two additional code access levels of its own and by default runs on WSS_Minimal.
As the webservice is operating as a local application on the Sharepoint server it requires Full Trust
However Microsoft discourages applying full trust willy nilly. I gather that it potentially allows other applications to call your code which has the potential of being used maliciously to exploit the system.
So a better way to prevent the SecurityException is to modify the projects AssemblyInfo.cs and add this attribute [assembly:AllowPartiallyTrustedCallers] to it.
Microsoft's article on Code Access Security.

Lock Problem in ASP.NET when debugging

I am using lucence.net which creates a file as a 'lock'. From what i can tell it simply creates a file to write to and if it cant the db is locked. I get the exception below
I call lucence_init() excepting it to happen once. I call it in Application_Start after i set the current working folder and other stuff.
I cant tell when this happens but i do know it only happens when i hit F5 in visual studios. And it (obviously) never happens on the first time. I think it happens when i get an exception, hit stop, fix and try to run the code. I need to use the icon in the system tray to stop the VS webserver and rerun the code (occasionally manually deleting the lock file but now i have visual studios doing it as a post build event. Which is weird, maybe i dont need this part)
Anyways because of this init problem my other code isnt run because of the write exception and i cant change the order and dont want to program around it so how might i solve this problem so its less annoying to debug this webapp?
Lock obtain timed out: NativeFSLock#c:\dev\prj\...\App_Data\LuceneIndex_a\write.lock: System.IO.IOException: The process cannot access the file 'c:\dev\prj\...\App_Data\LuceneIndex_a\write.lock' because it is being used by another process.
at System.IO.__Error.WinIOError(Int32 errorCode, String maybeFullPath)
at System.IO.FileStream.Init(String path, FileMode mode, FileAccess access, Int32 rights, Boolean useRights, FileShare share, Int32 bufferSize, FileOptions options, SECURITY_ATTRIBUTES secAttrs, String msgPath, Boolean bFromProxy)
at System.IO.FileStream..ctor(String path, FileMode mode, FileAccess access)
at Lucene.Net.Store.NativeFSLock.Obtain()
Well, if you're sure that you are using only one Lucene.Net index writer at a time, then this exception is happening due to the previously unsuccessful index write, which left write.lock file in your index directory.
The solution is to modify your lucene_init() to explicitly unlock the index directory before creating IndexWriter. Your code may look like this:
IndexWriter writer = null;
try {
writer = new IndexWriter(indexDir, DefaultAnalyzer);
}
catch (LockObtainFailedException ex) {
DirectoryInfo indexDirInfo = new DirectoryInfo(indexDir);
FSDirectory indexFSDir = FSDirectory.Open(indexDirInfo, new Lucene.Net.Store.SimpleFSLockFactory(indexDirInfo));
IndexWriter.Unlock(indexFSDir);
writer = new IndexWriter(indexDir, DefaultAnalyzer);
}
Lucene.Net creates a lock file when your index is opened for the purpose of being written to. If the index is opened but not properly closed, the lock file will remain. When you are debugging, it's possible that the index is being opened but an exception is happening (or you are cancelling the running process) before you close it correctly. It's hard to say what your particular solution is without any more detail, but I'd suggest fixing the problematic code without involving opening the index if possible or explicitly closing the index writer before moving onto the rest of the code.
It seems like the problem was disposing writer. I left it as a member variable instead of having the scope of the one function. Changing this and using .Close() completely fixed it.

Resources