Forum: help

Monitor Forum | Start New Thread Start New Thread
Which version Mono.Security.dll does Npgql 2.1.3 include? [ reply ]
By: Takehiro Nakamura on 2014-06-16 07:33

Npgql includes Mono.Security.dll. But I cannot identify the version of Mono.Security.dll from the source code of Npgql 2.1.3.

Could you let me know:
- Which version Mono.Security.dll is included?
- Whether Mono.Security.dll is modified in Npgsql project?

I would like to confirm license of Mono.Security.dll.

Please use our new forum:!forum/npgsql-help [ reply ]
By: Francisco Figueiredo jr. on 2014-07-07 18:33
Please use our new forum:!forum/npgsql-help to post any new question.

Thanks in advance.

Which version Mono.Security.dll does Npgsql 2.1.3 include? [ reply ]
By: Takehiro Nakamura on 2014-07-04 05:00

Npgsql includes Mono.Security.dll. But I cannot identify the version of Mono.Security.dll from the source code of Npgsql 2.1.3.

Could you let me know:
- Which version Mono.Security.dll is included?
- Whether Mono.Security.dll is modified in Npgsql project?

I would like to confirm license of Mono.Security.dll.


Help Regarding NpgsqlCopyIn Method [ reply ]
By: Andrew C on 2014-06-23 19:55
I am currently in the process of writing a C# program to transfer over data from an Advantage database to a PostgreSQL database. I am attempting to use an OdbcDataReader in conjunction with the NpgsqlCopyIn method; however, I cannot get it to work.

Does anyone have any ideas? Or a different approach to use Npgsql to bulk load data from a different database?

0AM01: Cannot Support Unlisten Statement Yet [ reply ]
By: Declan Hillier on 2014-06-23 07:43
Can anyone give any advice on why I'm receiving this error and what I should do about it. I'm receiving it whenever I try to close a connection.

This is with NPGSQL version - run time version v2.0.50727.
We're using PostGre as a front end to a Hawq Database. I'm afraid I don't have the specific details of the HAWQ database but could request specific details from the administrators if they're useful.

I've worked out the problem occurs when I close the connection by dummying up a quick app myself but the intended use is to pass a data reader to a third party dll. The thrid party dll does the closing itself and this is therefore abstracted away from me. The upshot of which is is that I can't simply swallow the error with a try catch block.

Any help or just a pointer in the right direction would be hugely apreciated.

Queries hanging [ reply ]
By: George Pierce on 2014-06-13 15:08
Since last Friday, we started experiencing our application hang running queries to our RedShift server. No exceptions, just the process stuck running. We originally were using an older version of NPGSQl, I updated to the lastest release version Monday.
With this update, there was a bug with: permission denied to set parameter "lc_monetary" to "C", I commented this line out as noted by a topic I found on stackoverflow.

What seems to be happening is the code is just stuck at various method calls. When I paused the application after it hangs, I see the current execution stuck at the For example, in the NPGsqlState.BackendResponseV3.cs, this line was stuck BackEndMessageCode message = (BackEndMessageCode) stream.ReadByte();

Also this particular function I witnessed hung the most in my testing,

inside the PGUTil class, CheckStreamRead function, the line: bytes_from_stream = stream.Read(buffer, offset + total_bytes_read, readSize);

When this was noticed Monday, it looks like the code was stuck from Friday until Monday morning. This is even with a CommandTimeout on the queries set to 30 minutes and our redshift server setting a max query length to 1 hour and 30 minutes.

I tried enabling SSL when we create our NPGSQLConnection, as we were not using SSL previously. I also tried to change the timeouts on our RedShift server and the command timeout for the npgsql connection. Lastly, we fully opened up the port 5439 we use for our connection to RedShift on our router to ensure there was no issue with that. None of these solutions have worked, and I am still experiencing the hang ups. These seem to happen randomly on various queries, nothing in particular seems to set it off.

Npgsql and IIS Trust Level Medium [ reply ]
By: Fabiano Lima on 2014-06-09 17:01
I'm using the provider Npgsql with NHibernate + Fluent. After some updating on the server where the application is installed I am getting the following error:

'Npgsql.NpgsqlException.GetObjectData(System.Runtime.Serialization.SerializationInfo, System.Runtime.Serialization.StreamingContext)'. Security accessibility of the overriding method must match the security accessibility of the method being overriden.

I believe the problem is the support Npgsql provider with "IIS Medium trust level."
Even using the instructions as [Assembly: SecurityRules(SecurityRuleSet.Level1)] in AssemblyInfo.cs I'm not succeeding in the execution of the application.

Does Npgsql is compatible with IIS medium trust level?

Error closing connection: cannot execute UNLISTEN during recovery (hot standby) [ reply ]
By: Luke Hill on 2013-05-27 23:04
We're using WAL file shipping to replicate data between a primary and a secondary PostgreSQL server.

After executing a read-only query via Npgsql to the secondary PostgreSQL server (running in "hot standby" mode), attempting to dispose of the connection causes the following error:

Stack Trace:

[NpgsqlException (0x80004005): ERROR: 25006: cannot execute UNLISTEN during recovery]
Npgsql.<ProcessBackendResponses_Ver_3>d__a.MoveNext() in C:\projects\Npgsql2\src\Npgsql\NpgsqlState.cs:842
Npgsql.NpgsqlState.IterateThroughAllResponses(IEnumerable`1 ienum) in C:\projects\Npgsql2\src\Npgsql\NpgsqlState.cs:319
Npgsql.NpgsqlConnectorPool.UngetPooledConnector(NpgsqlConnection Connection, NpgsqlConnector Connector) in C:\projects\Npgsql2\src\Npgsql\NpgsqlConnectorPool.cs:567
Npgsql.NpgsqlConnectorPool.ReleasePooledConnector(NpgsqlConnection Connection, NpgsqlConnector Connector) in C:\projects\Npgsql2\src\Npgsql\NpgsqlConnectorPool.cs:282
Npgsql.NpgsqlConnection.Close() in C:\projects\Npgsql2\src\Npgsql\NpgsqlConnection.cs:616
NHibernate.Connection.ConnectionProvider.CloseConnection(IDbConnection conn) +95

Our postgresql.conf file on the secondary server contains:
hot_standby = on

Our postgresql.conf file on the primary server contains:
wal_level = hot_standby
archive_mode = on

Is there any way to configure Npgsql to skip the UNLISTEN statement on closing/disposing a connection?
If not, can support for read-only queries to hot standby servers be built-in to the next Npgsql release?

Currently, we're only executing a single query on the secondary server (to monitor the replication status), so are catching and silencing the NpgsqlException with Code == 25006, however we intend to use the secondary server for far more widespread queries, so this workaround is less than ideal.

(Using Npgsql.dll version

Windows .NET to Unix Server using GSS Patch [ reply ]
By: Mike Kock on 2011-06-10 15:52
I was hoping to use Windows Authentication between a Windows .NET app and a FreeBSD unix Postgresql server. Postgresql was configured for GSS authentication and I was able to connect successfully with my Windows credentials using PGAdmin. However when I tried to connect in my .NET project I would get the following error:

Npgsql.NpgsqlException: Only AuthenticationClearTextPassword and AuthenticationMD5Password supported for now. Received: AuthenticationGSS.

So I dug into the npgsql code and made some changes to get GSS based authentication working. I am not sure if everything I did is perfect but it appears to work. Below is a link to a zip containing 4 diff files. If someone double check this and integrate it into the main source tree that would be great!

Here is a brief summary of what I changed:

1. Now handle authType AuthenticationRequestType.AuthenticationGSS. This just falls into the existing AuthenticationSSPI code.

2. The existing code was using a principal name of POSTGRES/[IP Address]. I had to change that to POSTGRES/[hostname] to get the authentication working. There is always a chance that is due to how something is configured in our domain. This is only done for authType AuthenticationGSS since I assume the SSPI code works fine as is.

3. If using authType AuthenticationGSS call AcquireCredentialsHandle with "kerberos" instead of "negotiate".

4. When sending the password the code no longer appends an extra 0 (null) byte to the end. This caused the GSS authentication to fail. It appears the plain text password still works without the null but I don't know if that is actually "correct" or not. I wanted to special case this for only AuthenticationGSS but I couldn't find a easy/clean way to get this information passed into the static interface functions that were being called.

I have only tested this in my environment with GSS and plaintext passwords. Perhaps someone with more insight into the code base can make any needed changes to clean up the code before integrating it into the main code base.

Thanks everyone for all of the work that has been done on this driver!


Kerberos 5 connectivity [ reply ]
By: Aram Azhari on 2014-05-12 13:39

We are trying to connect from:
Windows 7 64-bit - pgAdmin 1.18.1
Linux 64-bit Kerberos authenticated server that has postgre server installed and set up.

Unfortunately on I received an NpgsqlUnhandledException :

Only AuthenticationClearTextPassword and AuthenticationMD5Password supported for now. Received: AuthenticationKerberosV5

How can I solve this? Where should I start looking if I want to help with the development on this?


New version of npgsql 2.1.3 throws error when trying to insert an array [ reply ]
By: Sandra Moritz on 2014-05-07 09:29
Hello there

hopefully somebody knows a solution to my problem. Until I updated to the newest Npgsql version I had no problem with my arrays in a statement. Then I updated the version of npgsql and until then I get the error 22P02: Dimension value is missing. I changed nothing in my code, so probably something was changed in npgsql in declaring arrays. Here is my code:
command.Parameters.Add(new NpgsqlParameter("value", NpgsqlTypes.NpgsqlDbType.Array | NpgsqlTypes.NpgsqlDbType.Varchar));
command.Parameters[3].Value = project.eligibleUserNames; (this is a SerializableSortedSet, and it worked with that beforehand. I also tried List<String>, but still get the same error)

I then tried to go back to an older version of npgsql, but get still the same error. Does anybody know what might be the error? I call a stored procedure in the database, and the procedure is running nicely in the database itself. So whats wrong?

DataAnnotations for Ref Cursor are not considered in Entity Framework 6 [ reply ]
By: Devesh Sharma on 2014-05-06 05:56
I have a function in postgres that returns a ref cursor which I am calling from Entity framework. I am using latest Npgsql v

The data from refcursor is fetched but it does not recognises Column Attribute as I have some properties with different name as that coming from ref cursor.

Function in postgres looks something like:

CREATE OR REPLACE FUNCTION mypostgresschema.sp_test(refcursor, fromdate timestamp without time zone, todate timestamp without time zone)
RETURNS refcursor AS

SELECT row_number() OVER (ORDER BY column1ofrefcursor desc) rno, *
SELECT 'str1' column1ofrefcursor, 'str2' column2ofrefcursor
SELECT 'str3', 'str4'
SELECT 'str5', 'str6'
SELECT 'str7', 'str8'

LANGUAGE plpgsql;

my POCO entity in .Net looks like:

public class MyDTO
public string Prop1 { get; set; }

public string Prop2 { get; set; }

public long RNo { get; set; }

finally I am calling this function through .net as:

using (var context = new myDbContext())
var transaction = context.Database.Connection.BeginTransaction();
using (var command = context.Database.Connection.CreateCommand())
command.Transaction = transaction;

command.CommandType = CommandType.StoredProcedure;
command.CommandText = "mypostgresschema.sp_test";

new NpgsqlParameter[3]{
new NpgsqlParameter{ ParameterName="refcursor", NpgsqlDbType=NpgsqlDbType.Refcursor, Value="RefCursor1", Direction=System.Data.ParameterDirection.InputOutput},
new NpgsqlParameter{ ParameterName="fromdate", NpgsqlDbType=NpgsqlDbType.Timestamp, Value=fromDate},
new NpgsqlParameter{ ParameterName="toDate", NpgsqlDbType=NpgsqlDbType.Timestamp, Value=toDate}

using (var reader = command.ExecuteReader())

var myDtoList = ((IObjectContextAdapter)context)
return myDtoList;


The above code works when I change the property name as is coming from ref cursor.

Array of double and paramenters issue [ reply ]
By: storto aranci on 2014-05-02 11:01

code.txt (7) downloads

this is my first thread and i hope it's not redundant since i was not able to find a solution online.

I need to call a function passing an array of double but an error occur:

Unable to cast object of type 'System.Double[]' to type 'System.IFormattable'

if I change type to string problem persist.

The problem is related to paramenters "Quantity" and "AmountOriginalCurrency".

changing type to string for the params do not solve the issue.

A part of the code is attached as text.

I hope someone can help me.

thank you.

Array of double issue [ reply ]
By: storto aranci on 2014-05-02 11:00

this is my first thread and i hope it's not redundant since i was not able to find a solution online.

I need to call a function passing an array of double but an error occur:

Unable to cast object of type 'System.Double[]' to type 'System.IFormattable'

if I change type to string problem persist.

The problem is related to paramenters "Quantity" and "AmountOriginalCurrency".

changing type to string for the params do not solve the issue.

A part of the code is attached as text.

I hope someone can help me.

thank you.

PING to a server [ reply ]
By: Mahoni Oyea on 2014-03-05 12:09
Hello, ¿is there any option to test the connection of the server of NpgsqlConnection?

For example:

//do all things


returning using output parameter [ reply ]
By: Eric Schneider on 2014-04-02 19:35
Trying to run the following sql returning and output parameter, I have done this in Oracle but does not seem to work in PostgreSql.

Shouldn't this work?

FYI: ErrorId is a SERIAL column.

Insert into ERRORS ( ErrorId, Date, ErrorInfo ) values ( :ItemDate, :Text ) returning ErrorId into :ID

How to install for Excel [ reply ]
By: David Quastler on 2014-03-24 13:12
Hi, I need some help. I am not a developer and am not familiar with .Net. I am simply trying to connect from Excel (PowerPivot) to a Postgres database and was referred to this site by Microsoft to get a supported driver. Is there a simple way to install and register the driver? I looked thru the instructions and do not use Visual Studio so i'm a little lost.

invalid sql with parameters [ reply ]
By: Roberto Quintela on 2014-03-16 15:31

This SQL sentence doesn`t get my any row but in the SQL windows of Postgre works fine

select * from nominatim where usuario='us00000010' and etiqueta='county'

any idea?


How to capture msg of RAISE NOTICE from plpgsql SQL function with Npgset in C#? [ reply ]
By: Charles Chen on 2014-03-16 03:33
I want to capture message of RAISE NOTICE from plpgsql SQL function with Npgset in C#? Is this doable? If yes, please provide some sample code. Thank you in advance.

Using npgsql in MS SQL Server CLR objects development [ reply ]
By: pier pier on 2014-04-11 10:52
I need to send data from a MS SQL Server table to a PostgreSQL table on INSERT/UPDATE. I'm thinking about developing a CLR trigger on the source SQL Server table: the assmbly refereces the npgsql.dll and the, establishes a connection to the PostgreSQL server, sends the data, closes the connection.
To deply the trigger in SQL Server I need to create the assembly first using the next T-SQL code:

create assembly SimpleTrigger
authorization dbo
from 'd:\TTC\ArchivioCircolare\Lavoro\Tests\SimpleTrigger\SimpleTrigger\bin\Debug\SimpleTrigger.dll'

When I run that code I got the following exception:

Msg 6218, Level 16, State 2, Line 1
CREATE ASSEMBLY for assembly 'SimpleTrigger' failed because assembly 'Mono.Security' failed verification. Check if the referenced assemblies are up-to-date and trusted (for external_access or unsafe) to execute in the database. CLR Verifier error messages if any will follow this message
[ : Mono.Math.BigInteger+Kernel::Multiply][mdToken=0x600005d][offset 0x0000001C][trovato address of Int32][previsto unmanaged pointer] Tipo non previsto nello stack.
[ : Mono.Math.BigInteger+Kernel::Multiply][mdToken=0x600005d][offset 0x00000039][trovato address of Int32][previsto unmanaged pointer] Tipo non previsto nello stack.
[ : Mono.Math.BigInteger+Kernel::Multiply][mdToken=0x600005d][offset 0x00000059][trovato address of Int32][previsto unmanaged pointer] Tipo non previsto nello stack.
[ : Mono.Math.BigInteger+Kernel::Multiply][mdToken=0x600005d][offset 0x0000005A] I puntatori non gestiti non sono un tipo verificabile.
[ : Mono.Math.BigInteger+Kernel::Multiply][mdToken=0x600005d][offset 0x0000004C] Tipi non compatibili nello stack a seconda del percorso.
[ : Mono.Math.BigInteger+Kernel::MultiplyMod2p32pmod][mdToken=0x600005e][offset 0x0000001C][trovato address of Int32][previsto unmanaged pointer] Tipo non previsto nello stack.
[ : Mono.Math.BigInteger+Kernel::MultiplyMod2p32pmod][mdToken=0x600005e][offset 0x00000039][trovato address of Int32][previsto unmanaged pointer] Tipo non previsto nello stack.
[ : Mono.Math.BigInteger+Kernel::MultiplyMod2p32pmod][mdToken=0x600005e][offset 0x00000059][trovato address of Int32][previsto unmanaged pointer] Tipo non previsto nello stack.
[ : Mono.Math.BigInteger+Kernel::MultiplyMod2p32pmod][mdToken=0x600005e][offset 0x0000005A] I puntatori non gestiti non sono un tipo verificabile.
[ : Mono.Math.BigInteger+Kernel::MultiplyMod2p32pmod][mdToken=0x600005e][offset 0x0000004C] Tipi non compatibili nello stack a seconda del percorso.
[ : Mono.Math.BigInteger+Kernel::SquarePositive][mdToken=0x600005f][offset 0x0000003C][trovato address of Int32][previsto unmanaged pointer] Tipo ...

Any suggestion? Any other way to send data from MS SQL Server to PostgreSQL Server?

Thank you in advance, regards

How to connect using SSPI [ reply ]
By: t oka on 2013-12-02 02:27
Though a question was asked before, it has been unsolvable yet.
I have set up a windows domain trying to use SSPI.
In the same server, it is no problem.
It is a problem when divided into AP server and DB server.

AP Server and DB Server are set as the same domain.

Windows firewall on DB Server setup.
It enables it to connect the port of PostgreSQL to DB Server from AP Server.

The login roll of the same name as the login user of Windows is added to the login roll of PostgreSQL on DB Server.

Method of pg_hba.conf of PostgreSQL of DB Server is changed into SSPI.
host all all sspi
host all all ::1/0 sspi

I run my .NET client program on AP server.

NpgsqlConnection conn = new NpgsqlConnection("Server=APserver;Port=5432;Database=postgres; Integrated Security= true;");
NpgsqlCommand command = conn.CreateCommand();
command.CommandText = "select * from pg_locks";

pg_log file
FATAL: could not accept SSPI security context
Detail:The token supplied to the function is invalid

When running client program on DB Server, it has connected using SSPI.
When using md5, id and password were set up and it has connected from AP Server.

Are there those who have connected using SSPI?
Please teach me a method.

I hope you don't mind my poor English.

Npgsql and Membership, FormsAuthentication [ reply ]
By: Martin v on 2014-01-29 07:41
I'm developing asp net application with postgresql and need to run it in linux uisng mono. I wanna use Membership and FormsAuthentication for users login and so on. Tried to find if Npgsql supports this but wasn't able to. Can anyone tell if its possible with Npgsql or should i look elsewhere and if so maybe can anyone propose anything else to use.

Connection establishment timeout [ reply ]
By: Quentin Le Guennec on 2014-01-30 15:45
mono version: 3.2.3
postgres version: 9.3.2

client: #1 SMP PREEMPT
Linux x86_64 GNU/Linux

server: #1 SMP PREEMPT
Linux 3.10.27-2-ARCH armv6l GNU/Linux

Hi, i'm trying to use Npgsql via the mono compiler, and i can't manage to connect to my remote database.
Here's my connection string
:dbcon = new NpgsqlConnection ("Server=" + server + ";" +
"Port=" + port + ";" +
"Database=" + database + ";" +
"User Id=" + user + ";" +
"Password=" + password + ";Pooling=True;MINPOOLSIZE=4;MAXPOOLSIZE=15" );

I tried different values for Pooling, MINPOOLSIZE and MAXPOOLSIZE. I triple checked the values for server, port, database, user id and password. Debugging shows that monodevelop seems to spawn various threads (i guess it's mandatory)

Finally, here's the exception thrown:

Unhandled Exception:
Connection establishment timeout. Increase Timeout value in ConnectionString.
at Npgsql.NpgsqlClosedState.Open (Npgsql.NpgsqlConnector context) [0x001a5] in /build/mono/src/mono-3.2.3/mcs/class/Npgsql/Npgsql/NpgsqlClosedState.cs:154
at Npgsql.NpgsqlConnector.Open () [0x00056] in /build/mono/src/mono-3.2.3/mcs/class/Npgsql/Npgsql/NpgsqlConnector.cs:674
at Npgsql.NpgsqlConnectorPool.GetPooledConnector (Npgsql.NpgsqlConnection Connection) [0x000db] in /build/mono/src/mono-3.2.3/mcs/class/Npgsql/Npgsql/NpgsqlConnectorPool.cs:340
Connection establishment timeout. Increase Timeout value in ConnectionString.
at Npgsql.NpgsqlClosedState.Open (Npgsql.NpgsqlConnector context) [0x001a5] in /build/mono/src/mono-3.2.3/mcs/class/Npgsql/Npgsql/NpgsqlClosedState.cs:154
at Npgsql.NpgsqlConnector.Open () [0x00056] in /build/mono/src/mono-3.2.3/mcs/class/Npgsql/Npgsql/NpgsqlConnector.cs:674
at Npgsql.NpgsqlConnectorPool.GetPooledConnector (Npgsql.NpgsqlConnection Connection) [0x000db] in /build/mono/src/mono-3.2.3/mcs/class/Npgsql/Npgsql/NpgsqlConnectorPool.cs:340

System.NullReferenceException at Npgsql.NpgsqlState.d__a.MoveNext() [ reply ]
By: Jochen Wezel on 2014-01-27 12:10
After using command text
"SELECT * FROM GeneralProperties WHERE upper(PropertyName) = upper(:PropertyName) LIMIT 1"

I get following exception:
System.NullReferenceException: Der Objektverweis wurde nicht auf eine Objektinstanz festgelegt.
bei Npgsql.NpgsqlState.d__a.MoveNext()
bei Npgsql.ForwardsOnlyDataReader.GetNextResponseObject()
bei Npgsql.ForwardsOnlyDataReader.GetNextRowDescription()
bei Npgsql.ForwardsOnlyDataReader.NextResult()
bei Npgsql.ForwardsOnlyDataReader..ctor(IEnumerable`1 dataEnumeration, CommandBehavior behavior, NpgsqlCommand command, NotificationThreadBlock threadBlock, Boolean synchOnReadError)
bei Npgsql.NpgsqlCommand.GetReader(CommandBehavior cb)
bei Npgsql.NpgsqlCommand.ExecuteReader(CommandBehavior cb)
bei Npgsql.NpgsqlCommand.ExecuteDbDataReader(CommandBehavior behavior)
bei System.Data.Common.DbCommand.System.Data.IDbCommand.ExecuteReader(CommandBehavior behavior)
bei CompuMaster.Data.DataQuery.AnyIDataProvider.ExecuteReader(IDbCommand dbCommand, Automations automations) in G:\svn_repository\compumaster_products\tools\CompuMaster.Data\CompuMaster.Data\CompuMaster.Data.DataQuery.AnyIDataProvider.vb:Zeile 832.

And this is my line which throws the error:
Result = MyCmd.ExecuteReader(CommandBehavior.CloseConnection)

I notice that this problem occurs on 1 workstation regularly, other workstations don't have got such issue.

Using SSPI to connect to remote PostgreSQL server using Npgsql [ reply ]
By: Apar V on 2014-01-27 11:40
I am using nHibernate + Npgsql to connect to PostgreSQL server using windows authentication (SSPI). I have added the windows user to the Postgres and have configured the settings as recommended by

Here is my connection string: "Server=;Port=5432;Database=;Integrated Security=true"

This is my code:

if (!sessionFactories.TryGetValue(sessionFactoryConfigPath, out sessionFactory))
Configuration cfg = new Configuration();
if (sessionFactoryConfigPath != DefaultConfigFile)
// "The config file at '" + sessionFactoryConfigPath + "' could not be found");



// Now that we have our Configuration object, create a new SessionFactory
sessionFactory = cfg.BuildSessionFactory();
When I run this I get the following error at sessionFactory = cfg.BuildSessionFactory(); "FATAL: XX000: could not accept SSPI security context"

When I checked the PostgreSQL logs the following entry was found: "The token supplied to the function is invalid (80090308)"

What am I missing here? Please help.

The given assembly name or codebase was invalid. (Exception from HRESULT: 0x8013 [ reply ]
By: Phil Arena on 2014-01-26 17:38
I am trying to get npgsql working on a default project in VS2013.

I am getting the following error. Any help would be appreciated.

The given assembly name or codebase was invalid. (Exception from HRESULT: 0x80131047)

Source Error:

Line 28: public SimpleMembershipInitializer()
Line 29: {
Line 30: Database.SetInitializer<UsersContext>(null);
Line 31:
Line 32: try

web config:
<?xml version="1.0" encoding="utf-8"?>
For more information on how to configure your ASP.NET application, please visit
<section name="entityFramework" type="System.Data.Entity.Internal.ConfigFile.EntityFrameworkSection, EntityFramework, Version=, Culture=neutral, PublicKeyToken=b77a5c561934e089" requirePermission="false" />
<!-- For more information on Entity Framework configuration, visit -->
<add name="DefaultConnection" providerName="Npgsql" connectionString="Server=;Port=5432; Database=completrance; User Id=philarena; Password=RasterOpsx3!;"/>
<!-- <add name="DefaultConnection2" connectionString="Data Source=(LocalDb)\v11.0;Initial Catalog=aspnet-Test-20140125180531;Integrated Security=SSPI;AttachDBFilename=|DataDirectory|\aspnet-Test-20140125180531.mdf" providerName="System.Data.SqlClient" /> -->
<add key="webpages:Version" value="" />
<add key="webpages:Enabled" value="false" />
<add key="PreserveLoginUrl" value="true" />
<add key="ClientValidationEnabled" value="true" />
<add key="UnobtrusiveJavaScriptEnabled" value="true" />
<compilation debug="true" targetFramework="4.5.1" />
<httpRuntime targetFramework="4.5.1" />
<authentication mode="Forms">
<forms loginUrl="~/Account/Login" timeout="2880" />
<add namespace="System.Web.Helpers" />
<add namespace="System.Web.Mvc" />
<add namespace="System.Web.Mvc.Ajax" />
<add namespace="System.Web.Mvc.Html" />
<add namespace="System.Web.Optimization" />
<add namespace="System.Web.Routing" />
<add namespace="System.Web.WebPages" />
<validation validateIntegratedModeConfiguration="false" />
<remove name="ExtensionlessUrlHandler-ISAPI-4.0_32bit" />
<remove name="ExtensionlessUrlHandler-ISAPI-4.0_64bit" />
<remove name="ExtensionlessUrlHandler-Integrated-4.0" />
<add name="ExtensionlessUrlHandler-ISAPI-4.0_32bit" path="*." verb="GET,HEAD,POST,DEBUG,PUT,DELETE,PATCH,OPTIONS" modules="IsapiModule" scriptProcessor="%windir%\Microsoft.NET\Framework\v4.0.30319\aspnet_isapi.dll" preCondition="classicMode,runtimeVersionv4.0,bitness32" responseBufferLimit="0" />
<add name="ExtensionlessUrlHandler-ISAPI-4.0_64bit" path="*." verb="GET,HEAD,POST,DEBUG,PUT,DELETE,PATCH,OPTIONS" modules="IsapiModule" scriptProcessor="%windir%\Microsoft.NET\Framework64\v4.0.30319\aspnet_isapi.dll" preCondition="classicMode,runtimeVersionv4.0,bitness64" responseBufferLimit="0" />
<add name="ExtensionlessUrlHandler-Integrated-4.0" path="*." verb="GET,HEAD,POST,DEBUG,PUT,DELETE,PATCH,OPTIONS" type="System.Web.Handlers.TransferRequestHandler" preCondition="integratedMode,runtimeVersionv4.0" />
<assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
<assemblyIdentity name="DotNetOpenAuth.Core" publicKeyToken="2780ccd10d57b246" />
<bindingRedirect oldVersion="" newVersion="" />
<assemblyIdentity name="DotNetOpenAuth.AspNet" publicKeyToken="2780ccd10d57b246" />
<bindingRedirect oldVersion="" newVersion="" />
<assemblyIdentity name="System.Web.Helpers" publicKeyToken="31bf3856ad364e35" />
<bindingRedirect oldVersion="" newVersion="" />
<assemblyIdentity name="System.Web.Mvc" publicKeyToken="31bf3856ad364e35" />
<bindingRedirect oldVersion="" newVersion="" />
<assemblyIdentity name="System.Web.WebPages" publicKeyToken="31bf3856ad364e35" />
<bindingRedirect oldVersion="" newVersion="" />
<assemblyIdentity name="WebGrease" publicKeyToken="31bf3856ad364e35" />
<bindingRedirect oldVersion="" newVersion="" />
<assemblyIdentity name="Npgsql" PublicKeyToken="5d8b90d52f46fda7"/>
<!-- <bindingRedirect oldVersion="" newVersion="2.1.0-beta1"/> -->
<defaultConnectionFactory type="System.Data.Entity.Infrastructure.SqlConnectionFactory, EntityFramework" />
<provider invariantName="Npgsql" type="Npgsql.NpgsqlFactory, Npgsql, Version=2.1.0-beta1, Culture=neutral, PublicKeyToken=5d8b90d52f46fda7"/>
<!-- <provider invariantName="System.Data.SqlClient" type="System.Data.Entity.SqlServer.SqlProviderServices, EntityFramework.SqlServer" /> -->
<!-- <provider invariantName="Npgsql" type="Npgsql.NpgsqlServices, Npgsql.EntityFramework" /> -->

Stack Trace:

[FileLoadException: The given assembly name or codebase was invalid. (Exception from HRESULT: 0x80131047)]
System.RuntimeTypeHandle.GetTypeByName(String name, Boolean throwOnError, Boolean ignoreCase, Boolean reflectionOnly, StackCrawlMarkHandle stackMark, IntPtr pPrivHostBinder, Boolean loadTypeFromPartialName, ObjectHandleOnStack type) +0
System.RuntimeTypeHandle.GetTypeByName(String name, Boolean throwOnError, Boolean ignoreCase, Boolean reflectionOnly, StackCrawlMark& stackMark, IntPtr pPrivHostBinder, Boolean loadTypeFromPartialName) +70
System.RuntimeType.GetType(String typeName, Boolean throwOnError, Boolean ignoreCase, Boolean reflectionOnly, StackCrawlMark& stackMark) +39
System.Type.GetType(String typeName, Boolean throwOnError) +34
System.Data.Entity.Infrastructure.DependencyResolution.ProviderServicesFactory.GetInstance(String providerTypeName, String providerInvariantName) +15
System.Data.Entity.Internal.AppConfig.<.ctor>b__2(ProviderElement e) +71
System.Linq.WhereSelectEnumerableIterator`2.MoveNext() +145
System.Collections.Generic.List`1..ctor(IEnumerable`1 collection) +381
System.Linq.Enumerable.ToList(IEnumerable`1 source) +58
System.Data.Entity.Internal.AppConfig.<.ctor>b__1() +83
System.Lazy`1.CreateValue() +415
System.Lazy`1.LazyInitValue() +152
System.Lazy`1.get_Value() +75
System.Data.Entity.Internal.AppConfig.get_DbProviderServices() +9
System.Data.Entity.Infrastructure.DependencyResolution.AppConfigDependencyResolver.RegisterDbProviderServices() +18
System.Data.Entity.Infrastructure.DependencyResolution.AppConfigDependencyResolver.GetServiceFactory(Type type, String name) +92
System.Data.Entity.Infrastructure.DependencyResolution.<>c__DisplayClass1.<GetService>b__0(Tuple`2 t) +42
System.Collections.Concurrent.ConcurrentDictionary`2.GetOrAdd(TKey key, Func`2 valueFactory) +72
System.Data.Entity.Infrastructure.DependencyResolution.AppConfigDependencyResolver.GetService(Type type, Object key) +140
System.Data.Entity.Infrastructure.DependencyResolution.DbDependencyResolverExtensions.GetServiceAsServices(IDbDependencyResolver resolver, Type type, Object key) +13
System.Data.Entity.Infrastructure.DependencyResolution.AppConfigDependencyResolver.GetServices(Type type, Object key) +9
System.Data.Entity.Infrastructure.DependencyResolution.<>c__DisplayClass6.<GetServices>b__5(IDbDependencyResolver r) +19
System.Linq.<SelectManyIterator>d__14`2.MoveNext() +234
System.Linq.<ConcatIterator>d__71`1.MoveNext() +111
System.Linq.<OfTypeIterator>d__aa`1.MoveNext() +86
System.Data.Entity.Utilities.IEnumerableExtensions.Each(IEnumerable`1 ts, Action`1 action) +78
System.Data.Entity.Infrastructure.DependencyResolution.InternalConfiguration.Lock() +136
System.Data.Entity.Infrastructure.DependencyResolution.DbConfigurationManager.<.ctor>b__1() +90
System.Lazy`1.CreateValue() +415
System.Lazy`1.LazyInitValue() +152
System.Lazy`1.get_Value() +75
System.Data.Entity.Infrastructure.DependencyResolution.DbConfigurationManager.GetConfiguration() +207
System.Data.Entity.Database.SetInitializer(IDatabaseInitializer`1 strategy) +78
Test.Filters.SimpleMembershipInitializer..ctor() in c:\Users\Evolution\Documents\Visual Studio 2013\Projects\Test\Test\Filters\InitializeSimpleMembershipAttribute.cs:30

[TargetInvocationException: Exception has been thrown by the target of an invocation.]
System.RuntimeTypeHandle.CreateInstance(RuntimeType type, Boolean publicOnly, Boolean noCheck, Boolean& canBeCached, RuntimeMethodHandleInternal& ctor, Boolean& bNeedSecurityCheck) +0
System.RuntimeType.CreateInstanceSlow(Boolean publicOnly, Boolean skipCheckThis, Boolean fillCache, StackCrawlMark& stackMark) +113
System.RuntimeType.CreateInstanceDefaultCtor(Boolean publicOnly, Boolean skipCheckThis, Boolean fillCache, StackCrawlMark& stackMark) +232
System.Activator.CreateInstance(Type type, Boolean nonPublic) +83
System.Activator.CreateInstance(Type type) +6
System.Threading.LazyHelpers`1.ActivatorFactorySelector() +68
System.Threading.LazyInitializer.EnsureInitializedCore(T& target, Boolean& initialized, Object& syncLock, Func`1 valueFactory) +115
System.Threading.LazyInitializer.EnsureInitialized(T& target, Boolean& initialized, Object& syncLock) +106
Test.Filters.InitializeSimpleMembershipAttribute.OnActionExecuting(ActionExecutingContext filterContext) in c:\Users\Evolution\Documents\Visual Studio 2013\Projects\Test\Test\Filters\InitializeSimpleMembershipAttribute.cs:23
System.Web.Mvc.Async.AsyncControllerActionInvoker.InvokeActionMethodFilterAsynchronously(IActionFilter filter, ActionExecutingContext preContext, Func`1 nextInChain) +69
System.Web.Mvc.Async.<>c__DisplayClass3b.<BeginInvokeActionMethodWithFilters>b__35() +22
System.Web.Mvc.Async.AsyncControllerActionInvoker.InvokeActionMethodFilterAsynchronously(IActionFilter filter, ActionExecutingContext preContext, Func`1 nextInChain) +492
System.Web.Mvc.Async.<>c__DisplayClass3b.<BeginInvokeActionMethodWithFilters>b__35() +22
System.Web.Mvc.Async.<>c__DisplayClass37.<BeginInvokeActionMethodWithFilters>b__31(AsyncCallback asyncCallback, Object asyncState) +190
System.Web.Mvc.Async.WrappedAsyncResult`1.Begin(AsyncCallback callback, Object state, Int32 timeout) +129
System.Web.Mvc.Async.AsyncControllerActionInvoker.BeginInvokeActionMethodWithFilters(ControllerContext controllerContext, IList`1 filters, ActionDescriptor actionDescriptor, IDictionary`2 parameters, AsyncCallback callback, Object state) +182
System.Web.Mvc.Async.<>c__DisplayClass25.<BeginInvokeAction>b__1e(AsyncCallback asyncCallback, Object asyncState) +445
System.Web.Mvc.Async.WrappedAsyncResult`1.Begin(AsyncCallback callback, Object state, Int32 timeout) +129
System.Web.Mvc.Async.AsyncControllerActionInvoker.BeginInvokeAction(ControllerContext controllerContext, String actionName, AsyncCallback callback, Object state) +302
System.Web.Mvc.<>c__DisplayClass1d.<BeginExecuteCore>b__17(AsyncCallback asyncCallback, Object asyncState) +30
System.Web.Mvc.Async.WrappedAsyncResult`1.Begin(AsyncCallback callback, Object state, Int32 timeout) +129
System.Web.Mvc.Controller.BeginExecuteCore(AsyncCallback callback, Object state) +338
System.Web.Mvc.Async.WrappedAsyncResult`1.Begin(AsyncCallback callback, Object state, Int32 timeout) +129
System.Web.Mvc.Controller.BeginExecute(RequestContext requestContext, AsyncCallback callback, Object state) +316
System.Web.Mvc.Controller.System.Web.Mvc.Async.IAsyncController.BeginExecute(RequestContext requestContext, AsyncCallback callback, Object state) +15
System.Web.Mvc.<>c__DisplayClass8.<BeginProcessRequest>b__2(AsyncCallback asyncCallback, Object asyncState) +71
System.Web.Mvc.Async.WrappedAsyncResult`1.Begin(AsyncCallback callback, Object state, Int32 timeout) +129
System.Web.Mvc.MvcHandler.BeginProcessRequest(HttpContextBase httpContext, AsyncCallback callback, Object state) +251
System.Web.Mvc.MvcHandler.BeginProcessRequest(HttpContext httpContext, AsyncCallback callback, Object state) +48
System.Web.Mvc.MvcHandler.System.Web.IHttpAsyncHandler.BeginProcessRequest(HttpContext context, AsyncCallback cb, Object extraData) +16
System.Web.CallHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute() +301
System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously) +155

Npgsql version for Entityframework 6.0.2 [ reply ]
By: bhupendra singh on 2014-01-24 04:14
Hi All,

Which version of Npgsql is compatible with EF 6.0.2 in VS2012.
If anybody have the web config setting for that then Please share.

Thanks in advance

ProviderIncompatibleException while doing &quot;update model-&gt; database&quot; in [ reply ]
By: Seva Zaslavsky on 2014-01-03 22:21
I'm getting this error while doing "update model-> database".

This was working fine under I'm using VS 2012, EF 5.0, Postgres 9.0.8

It started to break when I changed the Npgsql version in machine.conf from to

Microsoft Visual Studio
An error occurred while connecting to the database. The database might be unavailable. An exception of type 'System.Data.ProviderIncompatibleException' occurred. The error message is: 'The store data provider failed to return information for the StoreSchemaDefinition request. See the inner exception for details.

The inner exception caught was of type 'System.ArgumentNullException', with this error message: 'Value cannot be null.

Parameter name: input'.'.

IncompatibleProviderException [ reply ]
By: bhupendra singh on 2014-01-23 12:49
Hi All,

I am trying to connect PostgreSQL 9.3.2 with Entity Framework in VS2012 using Npgsql provider.

I get error about provider.

A null was returned after calling the 'get_ProviderFactory' method on a store provider instance of type 'Npgsql.NpgsqlConnection'. The store provider might not be functioning correctly.

Which version of EF and Npgsql is compatible and what will be the setting in app.config file?

Please suggest me working code for this.
Thanks in advance


Entity Framework DatabaseGeneratedOption.Identity and DEFAULT uuid_generate_v4 [ reply ]
By: Vladimir Grishin on 2013-12-27 06:12

Please correct me if I`am wrong. Is it true that Npgsql( does not support uuid keys with DEFAULT uuid_generate_v4()?

Sample code below

public class User
public Guid ID { get; set; }

[Required, MaxLength(20)]
public string Name { get; set; }

[Required, MaxLength(20)]
public string Password { get; set; }

SQL code


CREATE TABLE "dbo"."User" (
"ID" uuid NOT NULL DEFAULT uuid_generate_v4(),
"Name" varchar(20) NOT NULL,
"Password" varchar(20) NOT NULL,

Let's add some user

public partial class MyDbContext : DbContext
public IDbSet<User> Users { get; set; }

var user = new User
Name = "User1",
Password = "Pwd1"
context.SaveChanges(); // exception here

Exception message
A null storage-generated value was returned for a non-nullable member 'ID' of type 'Guid'.

Postgres log contains sql code
INSERT INTO "dbo"."User"("Name","Password") VALUES ('User1','Pwd1');SELECT currval(pg_get_serial_sequence('"dbo"."User"', 'ID')) AS "ID"

Thank you

MVC Npgsql Linq EF6 insert bool value [ reply ]
By: Jean-Philippe Chenel on 2013-12-03 21:26

I'm using Entity Framework 6 and Npgsql (2.0.13 beta 1) to query, insert, update, delete. Working fine for querying, but I've a problem to insert value of boolean type.

public bool active { get; set; }


I've an error when the SaveChanges() occurs saying that the field etrue, or efalse don't exist. I think that the e in the front of the false or true is comming from the last letter of the active field. Also, the ModelState.IsValid return always false when I've a bool datatype in the Model.

Thank you very much,

Error with npgsql on EF6 [ reply ]
By: Daniel Yeung on 2013-12-17 04:10
I added the latest version using Nuget.
Modified the Web.config as follows:

<defaultConnectionFactory type="System.Data.Entity.Infrastructure.LocalDbConnectionFactory, EntityFramework">
<parameter value="v11.0" />
<provider invariantName="System.Data.SqlClient" type="System.Data.Entity.SqlServer.SqlProviderServices, EntityFramework.SqlServer" />
<provider invariantName="Npgsql" type="Npgsql.NpgsqlFactory, Npgsql" />

<!--07/15/2013 DY <></> added here for postgres as given in chinookconsole example
Also added connection strings as shown at top of file-->
<add name="Npgsql Data Provider" invariant="Npgsql" description="Data Provider for PostgreSQL" type="Npgsql.NpgsqlFactory, Npgsql" />

When I try to enable-migrations, get the following error:

PM> enable-migrations -ContextTypeName DIPS_Context -MigrationsDirectory DataContexts\DIPS_Migrations -verbose

The 'Instance' member of the Entity Framework provider type 'Npgsql.NpgsqlFactory, Npgsql, Version=, Culture=neutral, PublicKeyToken=5d8b90d52f46fda7' did not return an object that inherits from 'System.Data.Entity.Core.Common.DbProviderServices'. Entity Framework providers must inherit from this class and the 'Instance' member must return the singleton instance of the provider. This may be because the provider does not support Entity Framework 6 or later; see for more information.

What did I do wrong?

Any suggestions will be most helpful.



how to use source code from link [ reply ]
By: Andrus Moor on 2013-11-19 20:28
npgsql source code was downloaded from git and added as existing project to VS 2013 Express colution.

This project was referenced from other class library project in this solution by adding npgsql project to its references.

In this project line

using Npgsql;

causes compile error

The type or namespace name 'Npgsql' could not be found (are you missing a using directive or an assembly reference?)

How to try latest npgsql from git ?

Intellisense works, eq. typing Npgsql. in code shows npgsql members.
Cleaning solution does not fix it. I removed refereneces to npgsql production dll in every project in solution and added reference to npgsql project instead, re-build solution but problem persist.

It worked if I tried it in month ago in VS2012 . No idea why it does not work anymore.

I posted it also in

The value of HasRows changes by a row position [ reply ]
By: t oka on 2013-11-26 07:36
The value of HasRows changes by a row position.
Is it Npgsql's specification or bug?
Since Oracle and SQL Server differ from a result, I am troubled.

I hope you don't mind my poor English.

NpgsqlCommand command = conn.CreateCommand();
command.CommandText = "select * from trimspace";

NpgsqlDataReader reader;
reader = command.ExecuteReader();

while (reader.Read())


Oracle's document:
The value of HasRows does not change based on the row position. For example, even if the application has read all the rows from the result set and the next Read method invocation will return false, the HasRows property still returns true since the result set was not empty to begin with.
Rows are fetched to determine the emptiness of the OracleDataReader when HasRows property is accessed for the first time after the creation of the OracleDataReader object.

Connection Pool and multi-threading [ reply ]
By: Marcelo Zabani on 2013-12-01 17:55
Hi there, I'm getting the following exception from time to time:

System.NotSupportedException: Backend sent unrecognized response type: i at Npgsql.NpgsqlState+d__a.MoveNext () [0x00000] in :0 at Npgsql.ForwardsOnlyDataReader.GetNextResponseObject () [0x00000] in :0

I have read that it is because the same connection is being used in different threads. Let me explain exactly my context: I have one thread that receives HTTP connections and dispatches them to the application in a System.Threading.Tasks.Task so that it can keep receiving new connections.
The application then uses NHibernate+Npgsql to do its database work, and sometimes I get the exception shown above.

I would like to further understand how the connection pool works. I'm afraid that two different requests may be running in the same thread and as such may be getting the same connection from the pool, leading to problems.

Am I right this could be the cause of this problem? If so, what can I do? What other care should I take with this approach?

Thank you in advance,

Failed to establish a connection to ''. [ reply ]
By: Maxim Lastname on 2013-11-30 15:13

image.jpg (32) downloads
FreeBSD 9.2
PostgreeSQL 9.3
Monodevelop 4.0.12
Mono JIT compiler version 3.2.3

Error connecting
What could be the reason?

Backend sent unrecognized response type: e [ reply ]
By: Adao Silva on 2013-11-21 14:20
This error occurs when executing a simple insert table in the middle of a transaction.
If the insert command is isolated and executed in the pgAdmin/Query tool there's no problem.
It occurs in only one specific situation hard to give details. No problem in the most of situations.
I've tried this using the following versions: and


false parameter value is passed as true [ reply ]
By: Andrus Moor on 2013-10-17 10:38

Using code from git master and NauckIt membershipprovider, false parameter value is passed as true server.

Tried NauckIT PgMembershipProvicer.cs modified ResetPassword method:

using (NpgsqlCommand dbUpdateCommand = dbConn.CreateCommand())
dbUpdateCommand.CommandText = string.Format(CultureInfo.InvariantCulture, "UPDATE kasutaja SET Passwordha = @Password, LastPasswordChangedDate = @LastPasswordChangedDate WHERE kasutaja = trim(upper(@Username)) and islocked = @IsLockedOut");

dbUpdateCommand.Parameters.Add("@Password", NpgsqlDbType.Varchar, 128).Value = EncodePassword(newPassword);
dbUpdateCommand.Parameters.Add("@LastPasswordChangedDate", NpgsqlDbType.TimestampTZ).Value = DateTime.Now;
dbUpdateCommand.Parameters.Add("@Username", NpgsqlDbType.Varchar, 255).Value = username;

// actually true is passed to server:
dbUpdateCommand.Parameters.Add("@IsLockedOut", NpgsqlDbType.Boolean).Value = false;
rowsAffected = dbUpdateCommand.ExecuteNonQuery();

output in server log:

LOG: execute npgsqlplan2: UPDATE kasutaja SET Passwordha = $1::varchar(128), LastPasswordChangedDate = $2::timestamptz WHERE kasutaja = trim(upper($3::varchar(255))) and islocked = $4::bool
2013-10-17 12:23:09 EEST DETAIL: parameters: $1 = 'ya6PS3VfXHL2VT3/8H6eC7JJ9ZU=', $2 = '2013-10-17 12:23:07.042988+03', $3 = 'ADMIN', $4 = 't'

note that $4 value is passed as true mut in code it is passed as false.

islocked is defined as ebool:

CREATE TABLE kasutaja( ... islocked ebool )

ebool is defined as


How to fix ?


Same Query For one cient is 16x faster than for another [ reply ]
By: Seva Zaslavsky on 2013-11-06 22:19
I have written a simple test to measure the round-trip time for a trivial query using Npgsql. The objective of this test is to measure the overhead due to Npgsql and network.

The results are:

Client A is approx 1 ms (although it drops to .6 ms at times) for each query
Client B is consistently 15-16 ms. for each query

So I'm trying to figure out what is causing the high overhead on Client B.

The test does the following 1000 trivial select commands:

select 1;
select 2;
select 999;
select 1000;

Client Machines A and B sit in the same rack, on the same subnet and connected to the same postgres 9.2.4 server. They are both high-end servers, similarly configured

with Windows Server 2008 R2. The only major difference is that Machine A has MSVS 2010 and MSVS 2012 Professional installed and Machine B does not.

I've tried a number of things.

The results of the test are unchanged when:

- I switch from npgsql to
- I switch from .net 4 to .net 4.5
- I use npgsql in the GAC or in the local directory
- I run the code using a local copy or from a shared drive
- Run elevated permissions
- turn firewalls on/off

I checked all of the tcp parameters in the registry and they are the same between Client A and Client B.

The issue does not appear to be in the network because:

- the results of pgbench.exe are very similar on both machines
- Analyzing the output of Sysinternals Process Monitor revealed that the intervals between timestamps of the

requests/responses are equally fast on both machines so the postgres server is not discriminating against Client B in any way

- I created a SQL script with the equivalent sql select statements and used psql.exe to send it to the server. The results were similarly fast on both machines.

I ran the test in a profiler (Eqatec) on both machines and there are significant differences that I observed. They center around the calls to Socket.Poll:

(Calls / Total Time (ms))

Client A:

NpgContextholder.ProcessServerMessages (3432 ms / 3426 calls = 1 ms / call)
NpgSqlState.ProcessBackendResponseEnum(0 ms / 1000 calls = 0 ms/call)
NpgSqlConnector.socket.Poll(3432 ms / 4426 calls = 0.8 ms / call )

Client B:

NpgContextholder.ProcessServerMessages (18162 ms / 1191 calls= 15 ms / call)
NpgSqlState.ProcessBackendResponseEnum(156 ms / 1000 calls = 0.2 ms / call)
NpgSqlConnector.socket.Poll(18318 ms / 2191 calls = 8.4 ms / call)

It appears to me that there is some kind of delay between the receipt of the data on the socket and Poll() exiting. So I turned on .Net network tracing on Machine B and it actually ran faster! Unfortunately the data in the .net network tracing output is accurate to 16 ms and therefore not very useful.

There is clearly an issue with Machine B, but I have other machines that suffer the same problem that do not have Visual Studio installed. In addition to Machine A I have another machine that returns fast results and that machine also has Visual Studio installed. So the the fast results are correlated with having visual studio installed. This doesn't make sense because I run all tests from the command line.

Can you think of some explanation or another test to try?

How to reset session of a connection in connection pool? [ reply ]
By: Suresh Balasubramanian on 2013-07-25 11:31

How to reset session (my worry is sequence info) once I am done with the connection? What I want is, if I run currval('xxxx_id_seq') using a new connection I should get 'sequence not defined' instead of last inserted value.

If I close my program and open again I am getting the desired behavior. But I want this when switching between forms.

I tried appending the below commands to clear the session. But that doesn't seem to reset the sequence info retained in the session.

SELECT pg_advisory_unlock_all();

Please help.

Suresh Bala

Infinite exceptions thrown by ExecuteNonQuery() [ reply ]
By: Michał Dimmich on 2013-11-07 13:30

When I'm calling ExecuteNonQuery(or ExecuteReader) on some command, which is illegal in my database, and database throws an exception, the function throws infinite exceptions. Here is a code snippet:

command = new NpgsqlCommand("DELETE FROM COMPANY WHERE id='1';", conn);
int rowAffected = command.ExecuteNonQuery();
catch (Exception e)
throw e;

The try catch didn't catch any exceptions. I did get a message "The application stopped working" though.

So I tried handling "AppDomain.CurrentDomain.FirstChanceException += CurrentDomain_FirstChanceException;".

It turned out, the system is flooded with exceptions:
The first is a postgresql exception, but the rest are "There is already a DataReader associated with this command which must be closed first."

Am I missing something? How is one supposed to handle those exceptions?

   Older Messages
Powered By FusionForge