Wednesday 29 May 2013

Custom File Adapter not releasing file lock

Recently, I got a chance to customize the file adapter to be able to access a remote location, providing UserName and Password.

I started with the File Adapter sample provided with BizTalk. The changes were easy , modifying the ReceiveLocation.xsd schema allowed to me to add properties like Domain, UserName and Password to the adapter properties. And some code changes to access remote location after providing username and password to receive files.

Deploying the new changes I faced one issue, my new adapter properties were not visible on BizTalk Admin Console.
I had correctly deployed my dlls to GAC, my registry settings were correct, pointing to correct dlls. So changes should have been there. After some investigation, I found that we need to close and reopen BizTalk Admin Console in order for the changes to appear. Ha... so
-> Add the adapter under Platform settings. Restart Host Instance.
-> Close Admin Console and then reopen, you will have your new changes.

So, now I could access the files on remote location after providing correct username and password. However, I was facing a strange issue.
My files were being renamed to .BTS_WIP and were not being deleted. In event log I had errors saying, "Cannot delete file because it is being used by another process".
Now, what was using my file. I could not manually delete files as well. Only after I stopped Host Instance, I was able to delete the file.

After debugging the code, it turned out that there is some cleanup code which calls GC.Collect() to release resources in the sample. Before the GC.Collect() is completed, File.Delete() was being called in a separate thread ofcourse.
So , I thought of placing my File.Delete() with in a try catch block and in the catch block, I called :
System.GC.Collect();
System.GC.WaitForPendingFinalizers();
File.Delete()

It did the trick!!!