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.
Related
I have used the code below to open a SQLite database file that sits on a network computer for more than a year now almost on a daily basis. Suddenly this morning, I am not able to open the file programmatically.
private Boolean Connect(String strPathFile)
{
// Initialize the connection object.
this.DbConnection = null;
try
{
// DATABASE: Create the connection string and set the settings.
String strConnection = #"Data Source=" + strPathFile + #";Version=3;";
// DATABASE: Connect to the database.
this.DbConnection = new SQLiteConnection(strConnection);
this.DbConnection.Open();
return true;
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
return false;
}
The file is a network resource in the form "\Server\ShareName\FileName.db" (less the double quotes).
Here is the interesting thing. SQLite Administrator has no issues opening up the network database file, none, and repeatedly. I can also open up the file locally. I copied the file to my local drive and simply changed the path inside Visual Studio 2012 (VS2012).
The server seemed fine. It had gone through a reboot at some point since the last time that I checked on it. I presume a Microsoft Update. File Explorer has no issues browsing the folder, and as I said SQLite Administrator can open the network file.
I checked once again on permissions and everyone has full control as well as the server's users have full control, both on the security permissions and on the share permissions. I checked the folder and file, and permissions are the same. I expected as much, because SQLite Administrator can open the file. The server does not have a firewall set up, Windows Firewall or otherwise. I rechecked that this morning as well. Again, SQLite Administrator would have complained about that.
I verified writing, by making a copy of the file on the network drive using File Explorer. That had no issues.
The sever is a Windows Server 2003. I am using Windows 7 Professional 64-bit.
I also tried to open up the database in read only mode, but that failed as well. I was expecting that behavior. SQLite Administrator still works nicely.
I tried various other connection strings including SQLiteConnectionStringBuilder() just to see what happens, and all roads lead to Rome, namely:
System.Data.SQLite.SQLiteException occurred
HResult=-2147467259
Message=unable to open database file
Source=System.Data.SQLite
ErrorCode=14
StackTrace:
at System.Data.SQLite.SQLite3.Open(String strFilename, SQLiteConnectionFlags connectionFlags, SQLiteOpenFlagsEnum openFlags, Int32 maxPoolSize, Boolean usePool)
at System.Data.SQLite.SQLiteConnection.Open()
at SQL.cSQL.Connect(String strPathFile) in C:\<Path to source file>:line 367
InnerException:
Thoughts?
in version > 1.0.82.0
Double the leading two backslashes in the file name
(e.g. "\\\\network\share\file.db").
Use a mapped drive letter.
Use the SQLiteConnection constructor that takes the parseViaFramework
boolean argument and pass 'true' for that argument.
See the SQL post here
Assuming the db file is accessible (e.g. "because SQLite Administrator can open the file"), then option #2 from the answer by ranmoro and GEEF seems to work. This becomes:
bool parseViaFramework = true;
con = new SQLiteConnection( cs, parseViaFramework );
in code. The rationale is discussed in the SQLite check-in comment "mistachkin added on 2013-05-25 21:06:45" in https://system.data.sqlite.org/index.html/info/bbdda6eae2
My connection strings are of the form:
URI=file:\\SERVER\Data\SqlData\History.db
for UNC paths, or
URI=file:C:\Data\SqlData\History.db
for local paths.
I am using:
Visual Studio 2022
<TargetFramework>net5.0-windows</TargetFramework>
<PackageReference Include="System.Data.SQLite.Core" Version="1.0.115.5" />
I had a similar issue. Replacing the UNC (\server\share\folder\file.db) with a mapped drive path (S:\folder\file.db) resolve the issue in my instance.
The error message is very misleading + irritating. Applications working fine in the local environment get failed to start in client server situation.
It has mostly noting to do with the code. Its related to server side.
Make sure the Write access is available for the server folder containing the file.
UNC [IP based server path] is not supported still, the network path/folder should be mapped to overcome this issue.
Some sites+users are saying to mention the Version No. in the connection string. All my applications are working fine without using it.
Connection String:
Data Source=[Mapped Server Location]\[SubFolders]\[FileName].db;
Update:
I tried to prepend \\ to the UNC path and it worked (added additional \\ in the beginning only, not in-between).
Data Source=\\[UNC]\[SubFolders]\[FileName].db;
Is it possible to use a lock on one xml file that can potentially be written to from multiple aspx pages at the same time?
I'm asking because MSDN suggest that the lock statement should be used with a private static object instance as the expression, and since there are multiple pages involved i guess i can't use the same object on all the pages?
You can use the File.Open overload that takes a FileShare enum that is set to None. No other thread will be able to open the file until closed.
FileStream fs = File.Open(path, FileMode.Open, FileAccess.Read, FileShare.None);
This piece of code will open the (existing) file specified in the path argument, for reading and without any sharing.
I am developing an application to read an excel spreadsheet, validate the data and then map it to a sql table. The process is to read the file via a streamreader, validate the data, manually make corrections to the excel spreadsheet, validate again -- repeat this process until all data validates.
If the excel spreadsheet is open, then when I attempt to read the data via a streamreader I get an error, "The process cannot access the file ... because it is being used by another process." Is there a way to remove the lock or otherwise read the data into a streamreader without having to open and close excel each time?
When you call File.Open to get the stream are you using the overload that allows you to specify FileAccess?
http://msdn.microsoft.com/en-us/library/y973b725.aspx
Note the parameters:
public static FileStream Open(
string path,
FileMode mode,
FileAccess access,
FileShare share
)
You can pass FileAccess.Read to the third param to indicate you only need read-only access. You should also set FileShare.Read to allow others to open the file read-only instead of locking it yourself. Note that if MS Excel opens the file with FileShare.None, you probably wont be able to access it.
On a number of machines (with Asp.net 1 and 2) we have seen the below error with a random file name (with .dll extension) produced each time we try to make the web service call.
In the past we have had to reinstall asp.net and that seems to have fixed it.
However, on one occasion we tried to get the command prompt and windows came back with a error about low resources. Rebooting the server seemed to have fixed this issue.
Any ideas what is causing this error?
Error below:
System.Web.Services.Protocols.SoapException: Server was unable to process request. ---> System.IO.FileNotFoundException: Could not find file 'c:\windows\Temp\aweww1ss.dll'.
File name: 'c:\Windows\Temp\aweww1ss.dll'
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, FileShare share)
at Microsoft.CSharp.CSharpCodeGenerator.FromFileBatch(CompilerParameters options, String[] fileNames)
at Microsoft.CSharp.CSharpCodeGenerator.FromSourceBatch(CompilerParameters options, String[] sources)
at Microsoft.CSharp.CSharpCodeGenerator.System.CodeDom.Compiler.ICodeCompiler.CompileAssemblyFromSourceBatch(CompilerParameters options, String[] sources)
at System.CodeDom.Compiler.CodeDomProvider.CompileAssemblyFromSource(CompilerParameters options, String[] sources)
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.FromMappings(XmlMapping[] mappings, Evidence evidence)
at System.Web.Services.Protocols.SoapServerType..ctor(Type type, WebServiceProtocols protocolsSupported)
at System.Web.Services.Protocols.SoapServerProtocol.Initialize()
at System.Web.Services.Protocols.ServerProtocol.SetContext(Ty
If rebooting solved the issue that means your machine basically ran out of temp file storage space, your regular expressions and lot of tools that involve dynamic compilation (aspx etc), creates lot of temp files, and rebooting server or cleaning temp file should solve issue.
.NET apps are little bad to run for long time, we had server issues when we were not restarting them for days... then as days pass by, the logs, the memory defragmentation etc goes bigger and bigger and i think that sometimes slows everything down. .NET apps usually dont remove locks on resources they opened, its not developer's fault but .net garbage collection isnt that smart, so your temp files may grow if files werent closed and deleted.
Best is to do soft reboot on regular intervals like once a week on sunday night etc will help managing .net apps well.
Does this happen for every call to the web service? If so, then it is probably a permission problem on the C:\Windows\Temp folder.
For web services the .NET runtime creates a dynamic serialization assembly in the temp folder.
To resolve the issue, you need to grant the identity your service is running under write access to the temp folder.
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!