Can't add a claim with ASP.NET Core and identity - postgresql

I try to add a custom claim to an existing Identity user but I get an exception at run-time:
Npgsql.PostgresException: 23502: null value in column "Id" violates not-null constraint
Help!
What I did. I've created a simple web app on windows using the following command line
dotnet new mvc --auth Individual --framework netcoreapp1.1
I made changes found here to make the app use PostgreSQL as the database back-end. The created default webapp works fine. I can register as a new user, login, log out, etc...
Then I modified the Test method of the Home controller (I know the exceptions are ugly):
[Authorize]
public async Task<IActionResult> Test()
{
var user = await GetCurrentUserAsync();
if (user == null) {
_logger.LogWarning("User is null.");
throw new Exception("Not logged in");
}
_logger.LogWarning("User: {0}, {1}", user.Email, user);
var claim = new Claim("TestClaimType", "TestClaimValue");
IdentityResult idRes = IdentityResult.Failed();
if (_userManager.SupportsUserClaim) {
idRes = await _userManager.AddClaimAsync(user, claim); <------- Adding the claim
}
_logger.LogWarning("Return from adding claim");
if (idRes != IdentityResult.Success) {
throw new Exception("Failed to add claim.");
}
return View();
}
After logging in, I trigger the Test method and get the following logging (the PostgresException is near the end):
info: Microsoft.AspNetCore.Hosting.Internal.WebHost[1]
Request starting HTTP/1.1 GET http://localhost:5000/Home/Test
info: Microsoft.AspNetCore.Authentication.Cookies.CookieAuthenticationMiddleware[3]
HttpContext.User merged via AutomaticAuthentication from authenticationScheme: Identity.Application.
info: Microsoft.AspNetCore.Authorization.DefaultAuthorizationService[1]
Authorization was successful for user: mark#mark.com.
info: Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker[1]
Executing action method AlumniConnect.Controllers.HomeController.Test (AlumniConnect) with arguments ((null)) - ModelState is Valid
info: Microsoft.EntityFrameworkCore.Storage.IRelationalCommandBuilderFactory[1]
Executed DbCommand (1ms) [Parameters=[#__get_Item_0='?'], CommandType='Text', CommandTimeout='30']
SELECT "e"."Id", "e"."AccessFailedCount", "e"."ConcurrencyStamp", "e"."Email", "e"."EmailConfirmed", "e"."LockoutEnabled", "e"."LockoutEnd", "e"."NormalizedEmail", "e"."NormalizedUserName", "e"."PasswordHash", "e"."PhoneNumber", "e"."PhoneNumberConfirmed", "e"."SecurityStamp", "e"."TwoFactorEnabled", "e"."UserName"
FROM "AspNetUsers" AS "e"
WHERE "e"."Id" = #__get_Item_0
LIMIT 1
warn: AlumniConnect.Controllers.HomeController[0]
User: mark#mark.com, mark#mark.com
warn: AlumniConnect.Controllers.HomeController[0]
User: mark#mark.com, mark#mark.com
info: Microsoft.EntityFrameworkCore.Storage.IRelationalCommandBuilderFactory[1]
Executed DbCommand (4ms) [Parameters=[#__normalizedUserName_0='?'], CommandType='Text', CommandTimeout='30']
SELECT "u"."Id", "u"."AccessFailedCount", "u"."ConcurrencyStamp", "u"."Email", "u"."EmailConfirmed", "u"."LockoutEnabled", "u"."LockoutEnd", "u"."NormalizedEmail", "u"."NormalizedUserName", "u"."PasswordHash", "u"."PhoneNumber", "u"."PhoneNumberConfirmed", "u"."SecurityStamp", "u"."TwoFactorEnabled", "u"."UserName"
FROM "AspNetUsers" AS "u"
WHERE "u"."NormalizedUserName" = #__normalizedUserName_0
LIMIT 1
info: Microsoft.EntityFrameworkCore.Storage.IRelationalCommandBuilderFactory[1]
Executed DbCommand (33ms) [Parameters=[#p0='?', #p1='?', #p2='?', #p17='?', #p3='?', #p4='?', #p18='?', #p5='?', #p6='?', #p7='?', #p8='?', #p9='?', #p10='?', #p11='?', #p12='?', #p13='?', #p14='?', #p15='?', #p16='?'], CommandType='Text', CommandTimeout='30']
INSERT INTO "AspNetUserClaims" ("ClaimType", "ClaimValue", "UserId")
VALUES (#p0, #p1, #p2)
RETURNING "Id";
UPDATE "AspNetUsers" SET "AccessFailedCount" = #p3, "ConcurrencyStamp" = #p4, "Email" = #p5, "EmailConfirmed" = #p6, "LockoutEnabled" = #p7, "LockoutEnd" = #p8, "NormalizedEmail" = #p9, "NormalizedUserName" = #p10, "PasswordHash" = #p11, "PhoneNumber" = #p12, "PhoneNumberConfirmed" = #p13, "SecurityStamp" = #p14, "TwoFactorEnabled" = #p15, "UserName" = #p16
WHERE "Id" = #p17 AND "ConcurrencyStamp" = #p18;
fail: Microsoft.EntityFrameworkCore.DbContext[1]
An exception occurred in the database while saving changes.
Microsoft.EntityFrameworkCore.DbUpdateException: An error occurred while updating the entries. See the inner exception for details. ---> Npgsql.PostgresException: 23502: null value in column "Id" violates not-null constraint
at Npgsql.NpgsqlConnector.<DoReadMessageAsync>d__6.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
There's lots of logging more but it doesn't seem to add new information. I see the same exception mentioned multiple times throughout the log.
What can I do? Is this a PostgreSQL specific issue? Am I trying to add a claim in the wrong way?
Thanks!

In the migration for Identity, all tables that have a generated Integer id have an annotation for adding auto generation of this id. This annotation is SQL Server specific, like .Annotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn)
The fix for this is to add a Postgres specific annotation to the migration: .Annotation("Npgsql:ValueGenerationStrategy", NpgsqlValueGenerationStrategy.SerialColumn). In older versions of Npgsql.EntityFrameworkCore.PostgreSQL it could be that you need to use .Annotation("Npgsql:ValueGeneratedOnAdd", true).
The part of the migration for creating the AspNetRoleClaims table will then look like:
migrationBuilder.CreateTable(
name: "AspNetRoleClaims",
columns: table => new
{
Id = table.Column<int>(nullable: false)
.Annotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn)
.Annotation("Npgsql:ValueGenerationStrategy", NpgsqlValueGenerationStrategy.SerialColumn),
ClaimType = table.Column<string>(nullable: true),
ClaimValue = table.Column<string>(nullable: true),
RoleId = table.Column<string>(nullable: false)
},
constraints: table =>
{
table.PrimaryKey("PK_AspNetRoleClaims", x => x.Id);
table.ForeignKey(
name: "FK_AspNetRoleClaims_AspNetRoles_RoleId",
column: x => x.RoleId,
principalTable: "AspNetRoles",
principalColumn: "Id",
onDelete: ReferentialAction.Cascade);
});

It appears that when the Claim is added to the database, the 'RETURNING "Id"' clause of the SQL statement suggests the ID is returned. However, the table does not have an auto incrementing ID column.
I verified this by following the instructions from Adding 'serial' to existing column in Postgres.
The problem is now of course that this should have been taken care of automatically...

Related

Flink SQL CLI client CREATE TABLE from Kafka

I am trying to create a table in Apache Flink SQL client. I want to filter my JSON data in Flink, which arrives continously from a Kafka cluster.
The JSON looks like this:
{"lat":25.77,"lon":-80.19,"timezone":"America\/New_York",
"timezone_offset":-14400,
"current.dt":1592151550,
"current.sunrise":1592130546,
"current.sunset":1592179999,
"current.temp":302.77,
"current.feels_like":306.9,
"current.pressure":1017,
"current.humidity":78,
"current.dew_point":298.52,
"current.uvi":11.97,
"current.clouds":75,
"current.visibility":16093,
"current.wind_speed":3.6,
"current.wind_deg":60,
"current.weather.0.id":803,
"current.weather.0.main":"Clouds",
"current.weather.0.description":"broken clouds",
"current.weather.0.icon":"04d"}
The part I am interested in :
"current.weather.0.description":"broken clouds"
I want to filter my data whenever the current.weather description is "moderate rain". I tried to create two tables in Flink:
the Rain table, where the whole JSON arrives, and
where my filtered data will be stored and sent back to another Kafka cluster.
CREATE TABLE Rain (current.weather.0.description varchar) WITH ('connector.type' = 'kafka',
'connector.version' = 'universal',
'connector.topic' = 'WeatherRawData',
'format.type' = 'json',
'connector.properties.0.key' = 'bootstrap.servers',
'connector.properties.0.value' = 'kafka:9092',
'connector.properties.1.key' = 'group.id',
'connector.properties.1.value' = 'flink-input-group',
'connector.startup-mode' = 'earliest-offset'
);
CREATE TABLE ProcessedRain(
current.weather.0.description varchar
) WITH (
'connector.type' = 'kafka',
'connector.version' = 'universal',
'connector.topic' = 'WeatherProcessedData',
'format.type' = 'json',
'connector.properties.0.key' = 'bootstrap.servers',
'connector.properties.0.value' = 'kafka:9092',
'connector.properties.1.key' = 'group.id',
'connector.properties.1.value' = 'flink-output-group'
);
The error message I get :
[ERROR] Could not execute SQL statement. Reason: org.apache.flink.table.api.SqlParserException: SQL parse failed. Encountered "current" at line 1, column 20. Was expecting one of:
"PRIMARY" ...
"UNIQUE" ...
"WATERMARK" ...
<BRACKET_QUOTED_IDENTIFIER> ...
<QUOTED_IDENTIFIER> ...
<BACK_QUOTED_IDENTIFIER> ...
<IDENTIFIER> ...
<UNICODE_QUOTED_IDENTIFIER> ...
How should my CREATE TABLE be created correctly?
I think it should be
CREATE TABLE ProcessedRain (
`current.weather.0.description` VARCHAR
) WITH (
'connector.type' = 'kafka',
'connector.version' = 'universal',
'connector.topic' = 'WeatherProcessedData',
'format.type' = 'json',
'connector.properties.bootstrap.servers' = 'kafka:9092',
'connector.properties.group.id' = 'flink-output-group'
);

Problem when use Spark SQL【2.1】 to work with PostgreSQL DB

I use following test case to write data to a postgresql table, and it works fine.
test("SparkSQLTest") {
val session = SparkSession.builder().master("local").appName("SparkSQLTest").getOrCreate()
val url = "jdbc:postgresql://dbhost:12345/db1"
val table = "schema1.table1"
val props = new Properties()
props.put("user", "user123")
props.put("password", "pass#123")
props.put(JDBCOptions.JDBC_DRIVER_CLASS, "org.postgresql.Driver")
session.range(300, 400).write.mode(SaveMode.Append).jdbc(url, table, props)
}
Then, I use following spark-sql -f sql_script_file.sql to write an hive data into postgresql table.
CREATE OR REPLACE TEMPORARY VIEW tmp_v1
USING org.apache.spark.sql.jdbc
OPTIONS (
driver 'org.postgresql.Driver',
url 'jdbc:postgresql://dbhost:12345/db1',
dbtable 'schema1.table2',
user 'user123',
password 'pass#123',
batchsize '2000'
);
insert into tmp_v1 select
name,
age
from test.person; ---test.person is the Hive db.table
But when I run the above script using spark-sql -f sql_script.sql, it complains that the postgresql user/passord is invalid, the exception is as follows, I think the above two methods are basically the same, so I would ask where the problem is, thanks.
org.postgresql.util.PSQLException: FATAL: Invalid username/password,login denied.
at org.postgresql.core.v3.ConnectionFactoryImpl.doAuthentication(ConnectionFactoryImpl.java:375)
at org.postgresql.core.v3.ConnectionFactoryImpl.openConnectionImpl(ConnectionFactoryImpl.java:189)
at org.postgresql.core.ConnectionFactory.openConnection(ConnectionFactory.java:64)
at org.postgresql.jdbc2.AbstractJdbc2Connection.<init>(AbstractJdbc2Connection.java:124)
at org.postgresql.jdbc3.AbstractJdbc3Connection.<init>(AbstractJdbc3Connection.java:28)
at org.postgresql.jdbc3g.AbstractJdbc3gConnection.<init>(AbstractJdbc3gConnection.java:20)
at org.postgresql.jdbc4.AbstractJdbc4Connection.<init>(AbstractJdbc4Connection.java:30)
at org.postgresql.jdbc4.Jdbc4Connection.<init>(Jdbc4Connection.java:22)
at org.postgresql.Driver.makeConnection(Driver.java:392)
at org.postgresql.Driver.connect(Driver.java:266)
at org.apache.spark.sql.execution.datasources.jdbc.JdbcUtils$$anonfun$createConnectionFactory$1.apply(JdbcUtils.scala:59)
at org.apache.spark.sql.execution.datasources.jdbc.JdbcUtils$$anonfun$createConnectionFactory$1.apply(JdbcUtils.scala:50)
at org.apache.spark.sql.execution.datasources.jdbc.JDBCRDD$.resolveTable(JDBCRDD.scala:58)
at org.apache.spark.sql.execution.datasources.jdbc.JDBCRelation.<init>(JDBCRelation.scala:114)
at org.apache.spark.sql.execution.datasources.jdbc.JdbcRelationProvider.createRelation(JdbcRelationProvider.scala:45)
at org.apache.spark.sql.execution.datasources.DataSource.resolveRelation(DataSource.scala:330)
at org.apache.spark.sql.execution.datasources.CreateTempViewUsing.run(ddl.scala:76)
at org.apache.spark.sql.execution.command.ExecutedCommandExec.sideEffectResult$lzycompute(commands.scala:59)
at org.apache.spark.sql.execution.command.ExecutedCommandExec.sideEffectResult(commands.scala:57)
at org.apache.spark.sql.execution.command.ExecutedCommandExec.doExecute(commands.scala:75)

sqlalchemy many to many relationships (the value of a duplicate key breaks the unique constraint) flask_user role

can you help me,
when i run this script it works well
class User(db.Model, UserMixin):
__tablename__ = 'users'
id = db.Column(db.Integer, primary_key=True)
active = db.Column('is_active', db.Boolean(), nullable=False, server_default='1')
# User authentication information. The collation='NOCASE' is required
# to search case insensitively when USER_IFIND_MODE is 'nocase_collation'.
email = db.Column(db.String(255, collation='NOCASE'), nullable=False, unique=True)
email_confirmed_at = db.Column(db.DateTime())
password = db.Column(db.String(255), nullable=False, server_default='')
# User information
first_name = db.Column(db.String(100, collation='NOCASE'), nullable=False, server_default='')
last_name = db.Column(db.String(100, collation='NOCASE'), nullable=False, server_default='')
# Define the relationship to Role via UserRoles
roles = db.relationship('Role', secondary='user_roles')
# Define the Role data-model
class Role(db.Model):
__tablename__ = 'roles'
id = db.Column(db.Integer(), primary_key=True)
name = db.Column(db.String(50), unique=True)
# Define the UserRoles association table
class UserRoles(db.Model):
__tablename__ = 'user_roles'
id = db.Column(db.Integer(), primary_key=True)
user_id = db.Column(db.Integer(), db.ForeignKey('users.id', ondelete='CASCADE'))
role_id = db.Column(db.Integer(), db.ForeignKey('roles.id', ondelete='CASCADE'))
# Setup Flask-User and specify the User data-model
user_manager = UserManager(app, db, User)
# Create all database tables
db.create_all()
# Create 'member#example.com' user with no roles
if not User.query.filter(User.email == 'member#example.com').first():
user = User(
email='member#example.com',
email_confirmed_at=datetime.datetime.utcnow(),
password=user_manager.hash_password('Password1'),
)
db.session.add(user)
db.session.commit()
# Create 'admin#example.com' user with 'Admin' and 'Agent' roles
if not User.query.filter(User.email == 'admin#example.com').first():
user = User(
email='admin#example.com',
email_confirmed_at=datetime.datetime.utcnow(),
password=user_manager.hash_password('Password1'),
)
user.roles.append(Role(name='Admin'))
user.roles.append(Role(name='Agent'))
db.session.add(user)
db.session.commit()
at this stage the code is working without problems but the problem is just after when I add another user with a role that already exists
in this case the Admin role or the Agent role
for example if I add the code below an error message displays
if not User.query.filter(User.email == 'admin2#example.com').first():
user = User(
email='admin2#example.com',
email_confirmed_at=datetime.datetime.utcnow(),
password=user_manager.hash_password('Password1'),
)
user.roles.append(Role(name='Admin'))
user.roles.append(Role(name='Agent'))
db.session.add(user)
db.session.commit()
sqlalchemy.exc.IntegrityError: (psycopg2.IntegrityError) ERREUR: la valeur d'une clé dupliquée rompt la contrainte unique « roles_name_key »
DETAIL: La clé « (name)=(Admin) » existe déjà.
[SQL: 'INSERT INTO roles (name) VALUES (%(name)s) RETURNING roles.id'] [parameters: {'name': 'Admin'}] (Background on this error at: http://sqlalche.
me/e/gkpj)
I tried db driver different (pg8000, pygresql, py-postgresql) and still the same problem,
as the error message shows the problem because of the name value which is unique
name = db.Column (db.String (50), unique = True)
can you explain to me what is the error that I made, and what is the role of this part of code
# Define the relationship to Role via UserRoles
roles = db.relationship ('Role', secondary = 'user_roles')
I use flask with flask_user

WEB API Entity-Framework Parent Child Posting to SQL Database

I am writing my first WEB-API service based on data that a 3rd party will be sending. Below is the layout they will be sending:
<StandardTitleOrderRequest>
<Authentication>
<UserName>{$USERNAME}</UserName>
<Password>{$PASSWORD}</Password>
</Authentication>
<Borrowers>
<Borrower>
<FirstName>{$BORROWER_FIRST_NAME}</FirstName>
<MiddleName>{$BORROWER_MIDDLE_NAME}</MiddleName>
<LastName>{$BORROWER_LAST_NAME}</LastName>
<SSN>{$BORROWER_SSN}</SSN>
</Borrower>
</Borrowers>-
<Property>
<Address>{$SUBJECT_ADDRESS_STREET}</Address>
<City>{$SUBJECT_ADDRESS_CITY}</City>
<State>{$SUBJECT_ADDRESS_STATE}</State>
<Zip>{$SUBJECT_ADDRESS_ZIP}</Zip>
<County>{$SUBJECT_ADDRESS_COUNTY}</County>
</Property>-
<Contact>
<Name>{$CONTACT_NAME}</Name>
<Phone>{$CONTACT_PHONE}</Phone>
<Fax>{$CONTACT_FAX}</Fax>
<Email>{$CONTACT_EMAIL}</Email>
</Contact>-
<OrderInfo>
<LoanNumber>{$LOAN_NUMBER}</LoanNumber>
<LoanAmount>{$LOAN_AMOUNT}</LoanAmount>
<ToBeInsured/>
<FileNumber>{$FileID}</FileNumber>
<OrderId>{$ORDER_ID}</OrderId >
<CostCenter>{$BRANCH_NAME}</CostCenter>
<Product>{$PRODUCT_NUMBER}</Product>
<Notes>{$ORDER_NOTES}</Notes>
<ResponseURL>{$RESPONSE_URL}</ResponseURL>
<PID></PID>
<PayOffLoanNumber></PayOffLoanNumber>
<ClientCode>{$CLIENT_ID}</ClientCode>
</OrderInfo>
I have created a database with the following 4 tables (Orders, Borrowers, Contacts, Properties) the OrderID is common to each table. The order will have multiple borrowers and 1 contact and 1 property. I have a basic web api built that (using Fiddler) will allow me to GET/POST/PUT/DELETE an order or contact or borrower or property. I am not sure how to add the logic that posts the order and then each of the child elements for that order (borrower(s), contact, property). I am using VS 2017 and EF 6.
I am assuming (perhaps wrongly) that I need to add foreign keys to my tables that reference back to each other and then update the data model but when I do that I start to get various errors.
The 3rd party will be posting 1 transaction at a time so the incoming data will not be in bulk and will be transmitted as XML.
I have tried looking at various tutorials on the whole web api service but 90% of them just deal with a single table POST. Nothing really that goes into specific details about receiving XML data and posting to a parent and 1 or more children. Plus my app will currently only accept the incoming data in JSON format. Below is the code in the OrdersController that will be the basis for the post to the database (POST https://localhost:xxxx/api/Orders)am looking for some direction.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;
using OrdersDataAccess;
namespace waEtitle.Controllers
{
public class OrdersController : ApiController
{
/// <summary>
/// Get Order Information
/// </summary>
/// <returns></returns>
///
public IEnumerable<Order> Get()
{
using (FirstCloseEntities entities = new FirstCloseEntities())
{
return entities.Orders.ToList();
}
}
public HttpResponseMessage Get(int id)
{
using (FirstCloseEntities entities = new FirstCloseEntities())
{
var entity = entities.Orders.FirstOrDefault(o => o.OrderID == id);
if (entity != null)
{
return Request.CreateResponse(HttpStatusCode.OK, entity);
}
else
{
return Request.CreateErrorResponse(HttpStatusCode.NotFound, "Order with id = " + id.ToString() + " not found.");
}
}
}
public HttpResponseMessage Post([FromBody] Order order)
{
try
{
using (FirstCloseEntities entities = new FirstCloseEntities())
{
entities.Orders.Add(order);
entities.SaveChanges();
var message = Request.CreateResponse(HttpStatusCode.Created, order);
message.Headers.Location = new Uri(Request.RequestUri + order.OrderID.ToString());
return message;
}
}
catch (Exception ex)
{
return Request.CreateErrorResponse(HttpStatusCode.BadRequest, ex);
}
}
public HttpResponseMessage Delete(int ID)
{
try
{
using (FirstCloseEntities entities = new FirstCloseEntities())
{
var entity = entities.Orders.FirstOrDefault(c => c.OrderID == ID);
if (entity == null)
{
return Request.CreateErrorResponse(HttpStatusCode.NotFound, "Order with ID = " + ID.ToString() + " not found to delete.");
}
else
{
entities.Orders.Remove(entity);
entities.SaveChanges();
return Request.CreateResponse(HttpStatusCode.OK);
}
}
}
catch (Exception ex)
{
return Request.CreateErrorResponse(HttpStatusCode.BadRequest, ex);
}
}
public HttpResponseMessage Put(int id, [FromBody]Order order)
{
try
{
using (FirstCloseEntities entities = new FirstCloseEntities())
{
var entity = entities.Orders.FirstOrDefault(c => c.OrderID== id);
if (entity == null)
{
return Request.CreateErrorResponse(HttpStatusCode.NotFound, "Order with Id = " + id.ToString() + " not found to update.");
}
else
{
entity.LoanNumber = order.LoanNumber;
entity.LoanAmount = order.LoanAmount;
entity.ToBeInsured = order.ToBeInsured;
entity.FileNumber = order.FileNumber;
entity.CostCenter = order.CostCenter;
entity.Product = order.Product;
entity.Notes = order.Notes;
entity.ResponseURL = order.ResponseURL;
entity.PID = order.PID;
entity.PayOffLoanNumber = order.PayOffLoanNumber;
entity.ClientCode = order.ClientCode;
entities.SaveChanges();
return Request.CreateResponse(HttpStatusCode.OK, entity);
}
}
}
catch (Exception ex)
{
return Request.CreateErrorResponse(HttpStatusCode.BadRequest, ex);
}
}
}
}
Tables:
/* ==Scripting Parameters==
Source Server Version : SQL Server 2008 R2 (10.50.1617)
Source Database Engine Edition : Microsoft SQL Server Enterprise Edition
Source Database Engine Type : Standalone SQL Server
Target Server Version : SQL Server 2017
Target Database Engine Edition : Microsoft SQL Server Standard Edition
Target Database Engine Type : Standalone SQL Server
*/
USE [FirstCloseAPI]
GO
/****** Object: Table [dbo].[Borrowers] Script Date: 9/26/2017 1:50:18 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[Borrowers](
[borID] [int] IDENTITY(1,1) NOT NULL,
[OrderID] [int] NULL,
[FirstName] [varchar](max) NULL,
[MiddleName] [varchar](max) NULL,
[LastName] [varchar](max) NULL,
[SSN] [varchar](max) NULL,
CONSTRAINT [PK_Borrowers] PRIMARY KEY CLUSTERED
(
[borID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]
GO
/****** Object: Table [dbo].[Contacts] Script Date: 9/26/2017 1:50:18 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[Contacts](
[conId] [int] IDENTITY(1,1) NOT NULL,
[OrderID] [int] NULL,
[Name] [varchar](max) NULL,
[Phone] [varchar](max) NULL,
[Fax] [varchar](max) NULL,
[Email] [varchar](max) NULL,
CONSTRAINT [PK_Contacts] PRIMARY KEY CLUSTERED
(
[conId] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]
GO
/****** Object: Table [dbo].[Orders] Script Date: 9/26/2017 1:50:18 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[Orders](
[OrderID] [int] NOT NULL,
[LoanNumber] [varchar](max) NULL,
[LoanAmount] [money] NULL,
[ToBeInsured] [bit] NULL,
[FileNumber] [varchar](max) NULL,
[CostCenter] [varchar](max) NULL,
[Product] [varchar](max) NULL,
[Notes] [varchar](max) NULL,
[ResponseURL] [varchar](max) NULL,
[PID] [int] NULL,
[PayOffLoanNumber] [varchar](max) NULL,
[ClientCode] [varchar](max) NULL,
CONSTRAINT [PK_OrderHeader] PRIMARY KEY CLUSTERED
(
[OrderID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]
GO
/****** Object: Table [dbo].[Properties] Script Date: 9/26/2017 1:50:18 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[Properties](
[proID] [int] IDENTITY(1,1) NOT NULL,
[OrderID] [int] NULL,
[Address] [varchar](max) NULL,
[City] [varchar](max) NULL,
[State] [varchar](max) NULL,
[Zip] [varchar](max) NULL,
[County] [varchar](max) NULL,
CONSTRAINT [PK_Property] PRIMARY KEY CLUSTERED
(
[proID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]
GO
ALTER TABLE [dbo].[Borrowers] WITH NOCHECK ADD CONSTRAINT [FK_Borrowers_Orders] FOREIGN KEY([OrderID])
REFERENCES [dbo].[Orders] ([OrderID])
GO
ALTER TABLE [dbo].[Borrowers] NOCHECK CONSTRAINT [FK_Borrowers_Orders]
GO
ALTER TABLE [dbo].[Contacts] WITH NOCHECK ADD CONSTRAINT [FK_Contacts_Orders] FOREIGN KEY([OrderID])
REFERENCES [dbo].[Orders] ([OrderID])
GO
ALTER TABLE [dbo].[Contacts] NOCHECK CONSTRAINT [FK_Contacts_Orders]
GO
ALTER TABLE [dbo].[Properties] WITH NOCHECK ADD CONSTRAINT [FK_Properties_Orders] FOREIGN KEY([OrderID])
REFERENCES [dbo].[Orders] ([OrderID])
GO
ALTER TABLE [dbo].[Properties] NOCHECK CONSTRAINT [FK_Properties_Orders]
GO
Currently my GET is returning
<Order>
<Borrowers />
<ClientCode>cc1</ClientCode>
<Contacts />
<CostCenter>900-111</CostCenter>
<FileNumber>11111</FileNumber>
<LoanAmount>1111.0000</LoanAmount>
<LoanNumber>111</LoanNumber>
<Notes>notes1</Notes>
<OrderID>1</OrderID>
<PID>1</PID>
<PayOffLoanNumber>po1</PayOffLoanNumber>
<Product>letter</Product>
<Properties />
<ResponseURL>yahoo.com</ResponseURL>
<ToBeInsured>true</ToBeInsured>
</Order>
and as you can see there are no contacts or borrowers etc.
**
UPDATE: ---------------------------------------------------
**
I was able to get my Get and GET (int ID) commands to work and return the correct data by changing the procedures as:
public IEnumerable<Order> Get()
{
using (FirstCloseAPIEntities entities = new FirstCloseAPIEntities())
{
var entity = entities.Orders.ToList();
List<Borrower> borrowers = entities.Borrowers.ToList();
List<Contact> contacts = entities.Contacts.ToList();
List<Property> properties = entities.Properties.ToList();
//return entities.Orders.ToList() ;
return entity;
}
}
public HttpResponseMessage Get(int id)
{
using (FirstCloseAPIEntities entities = new FirstCloseAPIEntities())
{
var entity = entities.Orders.FirstOrDefault(o => o.OrderID == id);
List<Borrower> borrowers = entities.Borrowers.Where(b => b.OrderID == id).ToList();
List<Contact> contacts = entities.Contacts.Where(c => c.OrderID == id).ToList();
List<Property> properties = entities.Properties.Where(p => p.OrderID == id).ToList();
if (entity != null)
{
return Request.CreateResponse(HttpStatusCode.OK, entity);
}
else
{
return Request.CreateErrorResponse(HttpStatusCode.NotFound, "Order with id = " + id.ToString() + " not found.");
}
}
}
However, because I am requesting as HTML I then was getting the error:
The 'ObjectContent`1' type failed to serialize the response body for content type 'application/json; charset=utf-8'
So I had to add the following to the Global.asax.cs file:
GlobalConfiguration.Configuration.Formatters.JsonFormatter.SerializerSettings.ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore;
GlobalConfiguration.Configuration.Formatters.Remove(GlobalConfiguration.Configuration.Formatters.XmlFormatter);
This gave me back a successful response, however, no matter what I put in the headers for type application/xml application/json I am always getting the reponse back as JSON.
Content-Type: application/xml
accept: application/xml
accept-encoding: gzip, deflate
accept-language: en-US,en;q=0.8
user-agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/60.0.3112.113 Safari/537.36
Cache-Control: no-cache
Content-Length: 707
Content-Type: application/json; charset=utf-8
Date: Tue, 26 Sep 2017 19:46:42 GMT
Expires: -1
Pragma: no-cache
Server: Microsoft-IIS/10.0
X-Aspnet-Version: 4.0.30319
X-Powered-By: ASP.NET
X-Sourcefiles: =?UTF-8?B?YzpcdXNlcnNcZG91Zy5oYW1pbHRvblxkb2N1bWVudHNcdmlzdWFsIHN0dWRpbyAyMDE3XFByb2plY3RzXHdzRXRpdGxlXHdzRXRpdGxlXGFwaVxPcmRlcnNcMQ==?=
Raw
JSON
{
"OrderID": 1,
"LoanNumber": "111",
"LoanAmount": 1111,
"ToBeInsured": true,
"FileNumber": "11111",
"CostCenter": "900-111",
"Product": "letter",
"Notes": "notes1",
"ResponseURL": "yahoo.com",
"PID": 1,
"PayOffLoanNumber": "po1",
"ClientCode": "cc1",
"Borrowers": [
{
"borID": 1,
"OrderID": 1,
"FirstName": "Ura",
"MiddleName": "O",
"LastName": "Pepper",
"SSN": "111-11-1111"
},
{
"borID": 3,
"OrderID": 1,
"FirstName": "Ima",
"MiddleName": "J",
"LastName": "Pepper",
"SSN": "222-22-2222"
}
],
"Contacts": [
{
"conId": 1,
"OrderID": 1,
"Name": "Jackie the box",
"Phone": "414-555-1243",
"Fax": "414-222-1245",
"Email": "j#test.com"
}
],
"Properties": [
{
"proID": 1,
"OrderID": 1,
"Address": "123 Main Street",
"City": "Anytown",
"State": "WI",
"Zip": "10012
"County": "Westchester"
}
],
}
So I am still confused as to how to get the response in XML and then the last part is to be able to take the information that will be supplied as shown at the top of this post and POST it to the correct tables.
My code changes in the "UPDATED" remarks of my original post allowed me to GET and POST by JSON data to the web api I created on the local host so I was able to work through my issue.
My current additional issues are related to POSTing the data as XML instead of JSON and being able to move the web api to an already existing public facing website. I will post those as separate questions.

org.postgresql.util.PSQLException: No results returned by the query

hey everyone am trying to insert data in a table using #Query annotation in my spring boot app am getting a postgres Exception :
org.postgresql.util.PSQLException: No results returned by the query
this is my code :
this is the repository
#Query(value="INSERT INTO \"FCT_BY_DEV\"(\"IdDev\", \"IdFonction\") VALUES (?, ?) ",nativeQuery=true)
public String isertfonctionstodev(int dev,int fonction);
this is the controller :
#RequestMapping(value="/function/insert", method = RequestMethod.POST)
public String insererfonctions (int dev,int fonction){
System.out.println("dev="+dev+"fonction="+fonction);
fonctionRepository.isertfonctionstodev(dev, fonction);
System.out.println("********");
return "aaa";
}
am using this service by $http in angularJs
$http.post("/function/insert?dev="+$scope.id+"&fonction="+$scope.idf);
and finaly this is the server log
dev=16006fonction=14
Hibernate: INSERT INTO "FCT_BY_DEV"("IdDev", "IdFonction") VALUES (?, ?)
2016-04-27 16:52:03.204 WARN 7036 --- [nio-8080-exec-2] o.h.engine.jdbc.spi.SqlExceptionHelper : SQL Error: 0, SQLState: 02000
2016-04-27 16:52:03.204 ERROR 7036 --- [nio-8080-exec-2] o.h.engine.jdbc.spi.SqlExceptionHelper : Aucun résultat retourné par la requête.
the data is correct and i tried the same query with the same value and it worked why posgres is generating this exception and how can i fixed , thanks to any help
I think modifying queries must be annotared with an extra
#Modifying
This should solve your issue:
#Transactional
#Modifying(clearAutomatically = true)
#Query(value="update policy.tbl_policy set ac_status = 'INACTIVE' where pol_id = :policyId and version_no = :version_no and ac_status = 'ACTIVE'", nativeQuery=true)
public void updateExistingRowbyId(#Param("policyId") Long pol_id, #Param("version_no") Long version_no);
Without #Transactional annotation, following errors may occur:
javax.persistence.TransactionRequiredException: Executing an update/delete query