I use NHibernate 3.3.3 in my ASP.NET C# application with SqlServer 2008.
DetachedCriteria _pageCriteria = CriteriaTransformer.Clone(criteria)
.SetMaxResults(maxResult)
.SetFirstResult(firstResult);
_recordCount= _countCriteria.GetExecutableCriteria(session).FutureValue<int>();
var _pageCriteriaFuture = _pageCriteria.GetExecutableCriteria(session).Future<T>();
_pageCriteriaFuture.ToList();
If I try to execute the previous code I get a TimeOut error:
Failed to execute multi criteria[SQL:
SELECT count(*) as y0_ FROM Articoli this_ WHERE ((contains(this_.Oggetto, ?) or contains(this_.CorpoPlaintext, ?) or contains(this_.ParoleChiavi, ?) or contains(this_.SottoTitoloPlainText, ?)));
SELECT TOP (?) this_.Id as Id13_0_, this_.Corpo as Corpo13_0_, this_.CorpoPlaintext as CorpoPla3_13_0_, this_.Data as Data13_0_, this_.DataInserimento as DataInse5_13_0_, this_.LinkPagina as LinkPagina13_0_, this_.Numero as Numero13_0_, this_.Oggetto as Oggetto13_0_, this_.Tag as Tag13_0_, this_.NumeroVisualizzazioni as NumeroV10_13_0_, this_.IsConsigliatoRedazione as IsConsi11_13_0_, this_.ParoleChiavi as ParoleC12_13_0_, this_.SottoTitolo as SottoTi13_13_0_, this_.SottoTitoloPlainText as SottoTi14_13_0_, this_.idArticoloOld as idArtic15_13_0_, this_.IdUser as IdUser13_0_
FROM Articoli this_ WHERE ((contains(this_.Oggetto, ?) or contains(this_.CorpoPlaintext, ?) or contains(this_.ParoleChiavi, ?) or contains(this_.SottoTitoloPlainText, ?))) ORDER BY this_.DataInserimento desc;
]
Inner exception:
{"Timeout expired. The timeout period elapsed prior to completion of the operation or the server is not responding."}
The point is that if I try to execute these steps separately:
_recordCount= _countCriteria.GetExecutableCriteria(session).FutureValue<int>().Value;
It work like a sharm!!
Why, if I try to execute them in the same statemant, I get this error?
It's a lock problem? I try also to execute the same two-query command in MSS management studio and I get no errors!
The principle, the Future queries you've used are working for me. Not only when I tried to reproduce the question, but even on daily bases.
I did experienced the same exception. It was caused by the fact, that there were two sesions opened. The first, running in transaction, was locking the table with update/insert - not commited. The second was asking for result (Future) and time-out stopped it. All that in the same request (horrible)
NOTES: From the snippet (I know it could be just a quick draft, but just in case, that it is copy paste), I am not sure about the naming conventions
(is criteria from outer scope, is the _recordCount member of a DAO
class, because the 'var _pageCriteriaFuture' is definetly local
variable while prefixed with _. The _countCriteria appears in the
snippet without initialization...
That all could mean, that each parts are separated and some of them could already trigger openning/closing of the other Session. So I would suggest, turn on log4net and the full logging for NHIberante, and check, when the transaction was opened. There could be the answer.
Related
hope you guys are fine?
OK.. i am using MySQL.Data client/library to access and use MySQL database. I was using happily it for sometimes on quite a few project. But suddenly facing a new issue that causing me hold on my current project. :(
Because current project makes some (looks like it's a lot) db queries. and i am facing following exception :
Can't create more than max_prepared_stmt_count statements (current value: 16382)
i am closing and disposing the db engine/connection every time i am done with it. But getting damn confused why i am still getting this error.
here is the sample code just to give you idea.. (trimmed out unnecessary parts)
//this loop call an API with pagination and get API response
while(ContinueSalesOrderPage(apiClient, ref pageNum, days, out string response, window) == true)
{
//this handle the API date for the current page, it's normally 500 entry per page, and it throws the error on 4th page
KeyValueTag error = HandleSalesOrderPageData(response, pageNum, out int numOrders, window);
}
private KeyValueTag HandleSalesOrderPageData(string response, int pageNum, out int numOrders, WaitWindow window)
{
numOrders = json.ArrayOf("List").Size;
//init db
DatabaseWriter dbEngine = new DatabaseWriter()
{
Host = dbHost,
Name = dbName,
User = dbUser,
Password = dbPass,
};
//connecting to database
bool pass = dbEngine.Connect();
//loop through all the entry for the page, generally it's 500 entries
for(int orderLoop = 0; orderLoop < numOrders; orderLoop++)
{
//this actually handle the queries, and per loop there could be 3 to 10+ insert/update query using prepared statements
KeyValueTag error = InsertOrUpdateSalesOrder(dbEngine, item, config, pageNum, orderLoop, numOrders, window);
}
//here as you can see, i disconnect from db engine, and following method also close the db connection before hand
dbEngine.Disconnect();
}
//code from DatabaseWriter class, as you see this method close and dispose the database properly
public void Disconnect()
{
_CMD.Dispose();
_engine.Close();
_engine.Dispose();
}
so, as you can see i close/dispose the database connection on each page processing, but still it shows me that error on 4th page. FYI, 4th page data is not the matter i checked that. If i skip the page and only process the 4th page, it process successfully.
and after some digging more in google, i found prepare statement is saved in database server and that needs to be close/deallocate. But i can't find any way to do that using MySQL.Data Client :(
following page says:
https://dev.mysql.com/doc/refman/8.0/en/sql-prepared-statements.html
A prepared statement is specific to the session in which it was created. If you terminate a session without deallocating a previously prepared statement, the server deallocates it automatically.
but that seems incorrect, as i facing the error even after closing connection on each loop
so, i am at dead end and looking for some help here?
thanks in advance
best regards
From the official docs, the role of max_prepared_stmt_count is
This variable limits the total number of prepared statements in the server.
Therefore, you need to increase the value of the above variable, so as to increase the maximum number of allowed prepared statements in your MySQL server's configuration
Open the my.cnf file
Under the mysqld section, there is a variable max_prepared_stmt_count. Edit the value accordingly(remember the upper end of this value is 1048576)
Save and close the file. Restart MySQL service for changes to take place.
You're probably running into bug 77421 in MySql.Data: by default, it doesn't reset connections.
This means that temporary tables, user-declared variables, and prepared statements are never cleared on the server.
You can fix this by adding Connection Reset = True; to your connection string.
Another fix would be to switch to MySqlConnector, an alternative ADO.NET provider for MySQL that fixes this and other bugs. (Disclaimer: I'm the lead author.)
I have an Azure Event hub with readings from my smart electricity meter. I am trying to use an Azure Function to write the meter readings to an Azure SQL DB. I have created a target table in the Azure SQL DB and a Stored Procedure to parse a JSON and store the contents in the table. I have successfully tested the stored procedure.
When I call it from my Azure Function however I am getting an error: The type initializer for 'System.Data.SqlClient.TdsParser' threw an exception. For testing purposes, I have tried to execute a simple SQL select statement from my Azure Function, but that gives the same error. I am lost at the moment as I have tried many options without any luck. Here is the Azure function code:
#r "Microsoft.Azure.EventHubs"
using System;
using System.Text;
using System.Data;
using Microsoft.Azure.EventHubs;
using System.Data.SqlClient;
using System.Configuration;
using Dapper;
public static async Task Run(string events, ILogger log)
{
var exceptions = new List<Exception>();
try
{
if(String.IsNullOrWhiteSpace(events))
return;
try{
string ConnString = Environment.GetEnvironmentVariable("SQLAZURECONNSTR_azure-db-connection-meterreadevents", EnvironmentVariableTarget.Process);
using(SqlConnection conn = new SqlConnection(ConnString))
{
conn.Execute("dbo.ImportEvents", new { Events = events }, commandType: CommandType.StoredProcedure);
}
} catch (Exception ex) {
log.LogInformation($"C# Event Hub trigger function exception: {ex.Message}");
}
}
catch (Exception e)
{
// We need to keep processing the rest of the batch - capture this exception and continue.
// Also, consider capturing details of the message that failed to process so it can be processed again later.
exceptions.Add(e);
}
// Once processing of the batch is complete if any messages in the batch failed process throw an exception so that there is a record of the failure.
if (exceptions.Count > 1)
throw new AggregateException(exceptions);
if (exceptions.Count == 1)
throw exceptions.Single();
}
The events coming in are in JSON form as follows
{
"current_consumption":450,
"back_low":0.004,
"current_back":0,
"total_high":13466.338,
"gas":8063.749,
"current_rate":"001",
"total_low":12074.859,
"back_high":0.011,
"timestamp":"2020-02-29 22:21:14.087210"
}
The stored procedure is as follows:
CREATE PROCEDURE [dbo].[ImportEvents]
#Events NVARCHAR(MAX)
AS
BEGIN
-- SET NOCOUNT ON added to prevent extra result sets from
-- interfering with SELECT statements.
SET NOCOUNT ON
-- Insert statements for procedure here
INSERT INTO dbo.MeterReadEvents
SELECT * FROM OPENJSON(#Events) WITH (timestamp datetime2, current_consumption int, current_rate nchar(3), current_back int, total_low numeric(8, 3), back_high numeric(8, 3), total_high numeric(8, 3), gas numeric(7, 3), back_low numeric(8, 3))
END
I have added a connection string of type SQL AZURE and changed {your password} by the actual password in the string. Any thoughts on how to fix this issue or maybe how to get more logging as the error is very general?.
I managed to fix this exception by re-installing Microsoft.Data.SqlClient.SNI. Then clean and rebuild your project.
I managed to fix the issue by changing the Runtime version to ~2 in the Function App Settings.
Does this mean this is some bug in runtime version ~3 or should there be another way of fixing it in runtime version ~3?
I might be late to the party, in my case the cause of the error was "Target runtime" when publishing, I developed on windows machine but was transferring the file to linux, the solution was to change target runtime to the correct one, initial it was win-x64(merely because I started off by deploying locally), see screenshot below
Try to connect to a local SQL, use SQL profiler, and check what you are sending, and what precisely SQL is trying to do with the command being executed.
It's very hard to replicate your code, because, I obviously do not have your Azure SQL :)
So I would suggest, try to execute each step in the Stored procedure, as direct queries.
See if that works, then try to wrap the statements into store-procedures called back-to-back, and get that to work.
Then combine the commands to a single command, and fiddle with it till you get it to work ;)
Get the most simple query to execute towards the Azure SQL, so you are sure your connection is valid. (Like just a simple select on something)
Because without more information, it is very difficult to assist you.
Pretty silly but I got this after installing the EntityFrameworkCore Nuget package but not EntityFrameworkCore.SqlServer Nuget package. I had the SqlServer version for EntityFramework 6 installed.
I had the same error with a VSTO-application that was installed with a double click in the file explorer. Windows copied not all files to such an automatic location somewhere into ProgramData, so the application was simply not complete!
The solution was to register the VSTO-application manualy in HKEY_CURRENT_USER and pointed the "Manifest" to the complete directory with all the files. (like Microsoft.Data.SqlClient.dll, Microsoft.Data.SqlClient.SNI.x64.dll etc)
Those automatically by Windows chosen installations/directories will give unexpected behaviour. :(
Some ws methods ran fine and other would fail with this same error. I ran ws method that was failing in the browser on the box that the ws was being served from and got a lengthy, and helpful error message. One item was an InnerException that said
<ExceptionMessage>Failed to load C:\sites\TXStockChecker.xxxxxx.com\bin\x64\SNI.dll</ExceptionMessage>
I noticed that that file was right were it was expected in my development environment so I copied it to the matching directory on the prod ws and now all the methods run as expected.
I'm pretty new to NLog so please forgive my basic question.
I've inherited a Winforms application written by some contractors, I'm mainly a database developer but I've managed to do some development of the application but I sometimes struggle with tracking down error messages encountered by users, therefore I'm attempting to retrofit logging into the application via NLog, I first encountered the issue in NLog 4.4.5 and I've since updated to 4.4.12 and that hasn't solved the problem. I've verified that NLog is catching the errors correctly as it will output to a text file but when I try to direct it to a database output I can't get it to work.
This is my database table:
My problem is that I can only get errors written to the database only if I don't pass any parameters to the insert statement (which is pretty useless). That is to say that the following in my NLog.config file works:
<target name="database" xsi:type="Database">
<commandText>INSERT INTO [tblException] (DbVersionID, ExceptionDateTime) SELECT MAX(DbVersionID), GETDATE() FROM tblDbVersion</commandText>
<dbProvider>System.Data.SqlServerCe.4.0</dbProvider>
<connectionString>Data Source=${basedir}\Database.sdf</connectionString>
</target>
But this doesnt':
<target name="database" xsi:type="Database">
<commandText>INSERT INTO [tblException] (DbVersionID, ExceptionDateTime, Message) SELECT MAX(DbVersionID), GETDATE(), #message FROM tblDbVersion</commandText>
<parameter name="#message" layout="${message}" />
<dbProvider>System.Data.SqlServerCe.4.0</dbProvider>
<connectionString>Data Source=${basedir}\Database.sdf</connectionString>
</target>
I've enabled internal logging and the following is what I get:
2017-11-28 11:26:45.8063 Trace Executing Text: INSERT INTO [tblException] (DbVersionID, ExceptionDateTime, Message) SELECT MAX(DbVersionID), GETDATE(), #Message FROM tblDbVersion
2017-11-28 11:26:45.8063 Trace Parameter: '#message' = 'Test Error Message' (String)
2017-11-28 11:26:45.8063 Error Error when writing to database. Exception: System.Data.SqlServerCe.SqlCeException (0x80004005): A parameter is not allowed in this location. Ensure that the '#' sign is in a valid location or that parameters are valid at all in this SQL statement.
at System.Data.SqlServerCe.SqlCeCommand.ProcessResults(Int32 hr)
at System.Data.SqlServerCe.SqlCeCommand.CompileQueryPlan()
at System.Data.SqlServerCe.SqlCeCommand.ExecuteCommand(CommandBehavior behavior, String method, ResultSetOptions options)
at System.Data.SqlServerCe.SqlCeCommand.ExecuteNonQuery()
at NLog.Targets.DatabaseTarget.WriteEventToDatabase(LogEventInfo logEvent)
at NLog.Targets.DatabaseTarget.Write(LogEventInfo logEvent)
It appears that the parameter isn't getting replaced in the query before it's being run. I tried adding single quotes in the command text just in case that would help but it just resulted in the literal string '#message' being inserted into the database field.
I can't see anything that I've done differently to the examples, so any help would be appreciated.
Regards,
Alex
As per the comment from #pmcilreavy
Have you tried temporarily removing the MAX and replacing with a literal and changing to INSERT INTO .. (blah) VALUES (blah, #Message); SqlCe has quite a few limitations and quirks compared to Sql Server so might be worth simplifying things where possible.
The issue appears to be that SQLCE doesn't support parameters in the select part of a select statement.
I have an application where the user draws zones and later I check if a polyline crosses them.
All of a sudden the application crashed out with the error:
A .NET Framework error occurred during execution of user-defined routine or aggregate "geography":
System.ArgumentException: 24144: This operation cannot be completed because the instance is not valid. Use MakeValid to convert the instance to a valid instance. Note that MakeValid may cause the points of a geometry instance to shift slightly.
System.ArgumentException:
at Microsoft.SqlServer.Types.SqlGeography.STIntersects(SqlGeography other)
I was surprised at the message 'Use MakeValid' as I AM using 'MakeValid' as shown below:
Select ZonePolygonId, ZoneName, isHome FROM dbo.SpatialZonePolygons
WHERE Coordinates.STIntersects(geography::STGeomFromText('LINESTRING(51.15826 -0.18398, 51.15855 -0.18404, 51.15883 -0.18414, 51.15903 -0.18427, 51.15915 -0.18437, 51.15922 -0.1845, 51.15918 -0.18493, 51.15882 -0.18748, 51.15975 -0.18783, 51.15994 -0.18793, 51.16056 -0.18846, 51.16055 -0.1885, 51.16054 -0.1886, 51.16057 -0.18877, 51.16061 -0.18884, 51.16067 -0.18888, 51.16072 -0.18889, 51.16078 -0.18888, 51.16086 -0.18878, 51.1609 -0.18861, 51.16087 -0.18843, 51.16085 -0.1884, 51.16175 -0.18677, 51.16203 -0.18625, 51.16227 -0.18587, 51.16246 -0.18566, 51.16263 -0.18552, 51.16319 -0.18513, 51.16333 -0.18502, 51.16351 -0.18481, 51.16362 -0.18462, 51.16371 -0.18437, 51.1638 -0.18386, 51.1643 -0.18029, 51.16466 -0.17755, 51.16466 -0.17715, 51.16458 -0.17674, 51.16441 -0.17635, 51.16414 -0.17593, 51.16386 -0.17558, 51.16367 -0.17538, 51.16369 -0.17534, 51.16372 -0.17524, 51.16371 -0.17514, 51.16369 -0.17505, 51.16365 -0.17498, 51.16359 -0.17494, 51.16354 -0.17493, 51.16351 -0.17494, 51.16348 -0.17482, 51.16346 -0.17473, 51.16341 -0.17459, 51.16278 -0.17353, 51.16262 -0.17324, 51.16255 -0.17308, 51.16254 -0.17298, 51.16256 -0.17275, 51.16282 -0.17248, 51.16305 -0.1723, 51.16321 -0.17222, 51.16334 -0.17219, 51.16347 -0.17219, 51.16367 -0.17225, 51.16385 -0.17237, 51.16403 -0.17256, 51.16427 -0.17292, 51.16459 -0.17345, 51.16476 -0.17363, 51.16665 -0.17706, 51.16728 -0.17817, 51.16728 -0.17823, 51.1673 -0.17835, 51.16734 -0.17842, 51.16741 -0.17851, 51.16747 -0.17854, 51.16756 -0.17853, 51.16765 -0.17845, 51.16771 -0.17831, 51.16772 -0.17815, 51.16771 -0.17807, 51.16776 -0.17743, 51.16798 -0.1769, 51.16831 -0.17611, 51.16848 -0.17578, 51.16881 -0.17529, 51.16925 -0.17463, 51.16976 -0.17384, 51.17095 -0.17214, 51.171 -0.17225, 51.17097 -0.17278, 51.17131 -0.1729, 51.17149 -0.17297, 51.17161 -0.17296, 51.1719 -0.17276, 51.172 -0.17265, 51.17208 -0.17246, 51.1722 -0.17178, 51.17225 -0.17151, 51.17229 -0.17143, 51.17241 -0.17132, 51.17272 -0.17129, 51.17297 -0.17124, 51.17332 -0.17118, 51.17341 -0.17118, 51.17347 -0.17124, 51.17352 -0.17136, 51.17368 -0.17199', 4326).MakeValid())>0
I later found the offending polygon (see image) has been drawn pretty badly and I guess this is causing the issue.
So my specific questions are:
Am I using MakeValid correctly? I thought MakeValid() would resolve this kind of thing...
Obviously I have no control over the drawing skills of my client so if MakeValid doesn't help for badly drawn polygons, is there some other way of er... making this valid?
Many thanks.
OK, so the issue was indeed an invalid polygon zone held in the database.
The 'Use MakeValid' in the error message triggered some wrong assumptions as I was already using MakeValid(). Actually this error was triggered from an invalid Polygon zone and not the PolyLine I was using in the query.
To protect against this I have added MakeValid() to the INSERT SQL Statement so that no invalid polygons can ever exist within the database again.
I have tested inserting an invalid polygon with and without 'MakeValid' within the INSERT statement and can confirm adding 'MakeValid' does resolve the issue.
INSERT INTO SpatialZonePolygons (ZoneName,Coordinates) VALUES ('ValidZone',geography::STGeomFromText('POLYGON([SqlFormattedCoordinates here])', 4326).MakeValid())
I have a basic console application in which i using NHibernate V2.x to learn it. It is configured with FluentHibernate. I am facing a strange exception when executing the hql query to get all the users from user table. I know that user is reserved keyword,
so i tried SELECT * FROM [User] and it worked good with CreateSqlQuery method but then below failed miserably with the exception
Method 'HasAncestor' in type 'NHibernate.Hql.Ast.ANTLR.Tree.ASTNode' from assembly 'NHibernate, Version=2.1.2.4000, Culture=neutral, PublicKeyToken=aa95f207798dfdb4' does not have an implementation.
which is also referred here. Below is all that i have in my console application, could you point out what is wrong
ISessionFactory factory = CreateSessionFactory();
//read using HQL the 500 users
using (ISession dbSession = factory.OpenSession())
{
var users = dbSession.CreateQuery("from user").List();
}
Dropbox Link to Solution ( Source + Database + Configuration ]
https://dl.dropboxusercontent.com/u/29815170/HQL.zip
note: Please do change your database connections inside the code
I would almost for sure say, that this is the lower/upper case issue. The HQL parser (the ANTLR engine) results in case sensitive statements. Because, in C# we use Pascal style for Class names, I would say that your class is User.
HQL is working on top of Entity/C# model. So this should/must be working:
var users = dbSession.CreateQuery("from User").List(); // U is in capital