Pivot Runner: force delete of existing constraint that match a constraint needed for the new model - codefluent

Facing same issue, is there any progress on this one :
http://www.softfluent.com/product/codefluent-entities/knowledge-center/point-sql-server-producer-to-production-db-instead-of-using-pivot-producer
Thanks for your answer,
EDIT: this is the code used to delete all the constraints
private static void RemoveCodeFluentConstraintsTable(IList<PivotRunnerConstraint> constraints, String connectionString)
{
using (SqlConnection con = new SqlConnection(connectionString))
{
con.Open();
// Set up a command with the given query and associate
// this with the current connection.
using (SqlCommand cmd = new SqlCommand("SELECT tables.name as tableName, default_constraints.name as constraintName FROM sys.all_columns INNER JOIN sys.tables ON all_columns.object_id = tables.object_id INNER JOIN sys.schemas ON tables.schema_id = schemas.schema_id INNER JOIN sys.default_constraints ON all_columns.default_object_id = default_constraints.object_id", con))
{
foreach (PivotRunnerConstraint constraint in constraints)
{
String tableName = constraint.ParentName;
String constraintName = constraint.Name;
if (tableName != null && constraintName != null)
{
SqlCommand cmdConstraint = new SqlCommand("ALTER TABLE [MySchema].[" + tableName + "] DROP CONSTRAINT [" + constraintName + "]", con);
cmdConstraint.ExecuteNonQuery();
}
}
//con.Close();
}
}
return;
}

I went for using a custom naming convention using table name prefixing the generated constraint name.
public class MyNamingConvention : FormatNamingConvention
{
public override string GetName(INamedObject obj, IDictionary context)
{
Column column = obj as Column;
if (column != null && column.Table != null)
{
var name = context["name"] as string;
if (name != null && (name.StartsWith("DF_")))
{
return column.Table.Name + base.GetName(obj, context);
}
}
return base.GetName(obj, context);
}
}
At the same time, I also had to delete existing constraints to avoid collision:
private static void RemoveCodeFluentConstraints(string connectionString)
{
using (SqlConnection con = new SqlConnection(connectionString))
{
con.Open();
// Set up a command with the given query and associate
// this with the current connection.
using (SqlCommand cmd = new SqlCommand("SELECT c.name, t.name FROM sys.objects c, sys.objects t, sys.schemas s WHERE c.type IN('F', 'PK', 'FK', 'UQ', 'D') AND c.parent_object_id = t.object_id and t.SCHEMA_ID = s.schema_id AND t.type = 'U' AND s.name = 'MySchema' ORDER BY c.type", con))
{
using (IDataReader dr = cmd.ExecuteReader())
{
using (SqlConnection con1 = new SqlConnection(connectionString))
{
con1.Open();
while (dr.Read())
{
String constraintName = dr[0].ToString();
String tableName = dr[1].ToString();
if (tableName != null && constraintName != null)
{
String cmdConstraintSql = "ALTER TABLE [MySchema].[" + tableName + "] DROP CONSTRAINT [" + constraintName + "]";
ActivityLog.Write("Execute " + cmdConstraintSql, ActivityLogsFile);
SqlCommand cmdConstraint = new SqlCommand(cmdConstraintSql, con1);
cmdConstraint.ExecuteNonQuery();
}
}
con1.Close();
}
}
}
con.Close();
}
return;
}
Other problem were related to definition of pivot file not being picked correctly: Pivot Runner null command

Related

C# ExecuteReaderAsync Sporadic Issue

I have a method that is getting a list of users. There is a store procedure that is expected either a username or null. It returns one or more users based on the parameter. It works fine most of the time, but I notice there are times it does not return any result even though I am passing the same exact parameter. I put a break point in the Execute Reader Async, and the line immediately following it. When the issue occurs, it reaches the first break point but not the second one. It does not throw an exception or prevent me from making another call. I can make the next call, and it will return the result as expected. I would appreciate some suggestions as to what may cause this issue?
public async Task<List<User>> GetUsers(string username, int accountType = 1)
{
List<User> users = null;
parameters = new List<SqlParameter>{
new SqlParameter{
DbType = DbType.String,
ParameterName = "#userName",
Value = username.NotEmpty() ? username : (object) DBNull.Value
},
new SqlParameter{
DbType = DbType.Int32,
ParameterName = "#accountType",
Value = accountType
}
};
try
{
using (SqlConnection con = new SqlConnection(conStr))
{
await con.OpenAsync();
using (SqlCommand cmd = new SqlCommand("spGetUsers", con))
{
cmd.Parameters.AddRange(parameters.ToArray());
cmd.CommandType = CommandType.StoredProcedure;
SqlDataReader dr = await cmd.ExecuteReaderAsync()
if (dr.HasRecord())
{
while (await dr.ReadAsync())
{
User user = new User();
user.FirstName = dr["firstName"].ToString();
user.LastName = dr["lastName"].ToString();
user.DateRegister = Convert.ToDateTime(dr["DateRegister"].ToString());
user.Active = Convert.ToBoolean(dr["Active"].ToString());
if(users == null)
{
users = new List<User>();
}
users.Add(user);
}
}
}
}
}
catch (Exception ex)
{
Util.LogError(ex.ToString());
users = null;
}
return users;
}
Update:
Yes, the error is being logged. Also, I added a breakpoint in the catch statement in case an error is thrown.
Here is the query that is used to create that store procedure:
IF EXISTS (SELECT 1 FROM SYS.objects WHERE object_id = OBJECT_ID('spGetUsers') AND TYPE IN (N'PC', N'P'))
DROP PROCEDURE spGetUsers
GO
CREATE PROCEDURE spGetUsers
#userName nvarchar(50),
#accountType int = 1
AS
BEGIN
SELECT U.firstName, U.lastName, U.DateRegister, A.Active
FROM [User] U
inner join UserAccount UA
on U.Id = UA.userid
inner join Account A
on A.Id = UA.accountId
WHERE U.Id > 0
AND UA.Id > 0
AND A.Id > 0
AND UA.AccountType IN (#accountType )
and (A.UserName in (#userName) or #userName IS NULL)
END
Extension Method to check if SQL DataReader has record
public static bool HasRecord(this System.Data.SqlClient.SqlDataReader dr)
{
if (dr != null && dr.HasRows)
{
return true;
}
return false;
}

Sparx EA Jscript Information Flows Realized

How do I retrieve a collection of all the Information Flows Realized by a connector of type Dependency using Jscript please?
First option would be to use the API.
Loop the connectors and check EA.Connector.ConveyedItems
But that will be terribly slow for anything but a trivial model.
So the only sane way is to use EA.Repository.SQLQuery(string SQL) to get a list of connectorID's and then use EA.Repository.GetConnectorByID(int ID) to get the connector objects.
The SQL query you need is something in the nature of
select *
from ((((t_connector c
inner join t_xref x on (x.Client = c.ea_guid
and x.Name = 'MOFProps'
and x.Type = 'connector property'
and x.Behavior = 'abstraction'))
inner join t_connector cf on x.Description like '%' + cf.ea_guid + '%')
inner join t_xref xf on (xf.Client = cf.ea_guid
and xf.Name = 'MOFProps'
and xf.Type = 'connector property'
and xf.Behavior = 'conveyed'))
inner join t_object o on o.ea_guid like xf.Description)
where c.Connector_Type = 'Dependency'
Replace % with * in case you are working on a .eap (MS-Access) file.
I also have an implementation in C#. On class ConnectorWrapper there is this operation to get the information flows from the dependency.
/// <summary>
/// convenience method to return the information flows that realize this Relationship
/// </summary>
/// <returns>the information flows that realize this Relationship</returns>
public virtual HashSet<UML.InfomationFlows.InformationFlow> getInformationFlows()
{
HashSet<UML.InfomationFlows.InformationFlow> informationFlows = new HashSet<UML.InfomationFlows.InformationFlow>();
string sqlGetInformationFlowIDs = #"select x.description
from (t_connector c
inner join t_xref x on (x.client = c.ea_guid and x.Name = 'MOFProps'))
where c.ea_guid = '" + this.guid + "'";
var queryResult = this.model.SQLQuery(sqlGetInformationFlowIDs);
var descriptionNode = queryResult.SelectSingleNode(this.model.formatXPath("//description"));
if (descriptionNode != null)
{
foreach (string ifGUID in descriptionNode.InnerText.Split(','))
{
var informationFlow = this.model.getRelationByGUID(ifGUID) as UML.InfomationFlows.InformationFlow;
if (informationFlow != null )
{
informationFlows.Add(informationFlow);
}
}
}
return informationFlows;
}
Once you have the InformationFlow this code gets the conveyed items
public HashSet<UML.Classes.Kernel.Classifier> conveyed
{
get
{
if (_conveyed == null)
{
string getXrefDescription = #"select x.Description from t_xref x
where x.Name = 'MOFProps'
and x.Behavior = 'conveyed'
and x.client = '" + this.guid + "'";
//xrefdescription contains the GUID's of the conveyed elements comma separated
var xrefDescription = this.model.SQLQuery(getXrefDescription).SelectSingleNode(this.model.formatXPath("//Description"));
if (xrefDescription != null)
{
foreach (string conveyedGUID in xrefDescription.InnerText.Split(','))
{
var conveyedElement = this.model.getElementWrapperByGUID(conveyedGUID) as UML.Classes.Kernel.Classifier;
if (conveyedElement != null)
{
//initialize if needed
if (_conveyed == null)
{
_conveyed = new HashSet<UML.Classes.Kernel.Classifier>();
}
//add the element
_conveyed.Add(conveyedElement);
}
}
}
}
//nothing found, return empty list.
if (_conveyed == null)
{
_conveyed = new HashSet<UML.Classes.Kernel.Classifier>();
}
return _conveyed;
}
}

android sqlite group query error:android.database.CursorIndexOutOfBoundsException:

My query in android sqlite is given below
MY column name topic,correct_answer and total_mark,test_id
MY database name no_question_list
My query given here
String query = "SELECT topic,SUM(correct_answer),SUM(total_mark) from no_question_list Where test_id='" + test_id + "'" + "group by topic,correct_answer,total_mark";
Cursor c = database.rawQuery(query , null);
if (c != null) {
if (c.moveToFirst()) {
do {
topic= c.getString(0);
}
while (c.moveToNext());
}
}
When i execute the query no error when getting error in value of Cursor
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.stepone.netquestion/com.stepone.netquestion.ResultActivity}: android.database.CursorIndexOutOfBoundsException: Index 0 requested, with a size of 0
and i tried this cursor part,it doest execute
if (c != null) {
if (c.moveToFirst()) {
do {
String topic =c.getString(c.getColumnIndex("topic"));
}
while (c.moveToNext());
}
thank for answer in advance
I do not think you need this test if(c != null) try this code
public String getCol_MPW(){
db = getReadableDatabase();
String q = "SELECT * FROM masterPW";
Cursor cursor = db.rawQuery(q,null);
if(cursor.moveToFirst()){
int i = cursor.getInt(cursor.getColumnIndex(Col_IDI));
str = cursor.getString(cursor.getColumnIndex(Col_MPW));
}
cursor.close();
db.close();
return str;
// This routine called from MainActivity determine's if a
// password has been entered in the db table named "TABLE_PW"
// See onLoad() method in MainActivity
}

Importing DBF file in SQL Server 2012

I have over 200+ dbf files having different schema. I have used SSIS to import .dbf files, but in order to automate the task I want to use OpenRowset. OpenRowSet is working fine for Excel Files, but not for .dbf.
I have written
SELECT [LRSNum],[AppUpdD],[AppStat],[PIN] FROM OPENROWSET('MICROSOFT.ACE.OLEDB.12.0','dBASE 5.0;Database=D:\Sales- data\SalesSourcefile\2016\December\Shape\Martin\real_land\', 'SELECT [LRSNum],[AppUpdD],[AppStat],[PIN] FROM real_land.dbf');
Any help will be appreciated.
I am using SQL Server 2012, Windows 8.1.
Installed Foxpro driver, but when selected foxpro using DTS, it fails.
FYI - You can do automated uploads of DBFs to SQL Server using SQL Server Upsizing Wizard for FoxPro.
With this tool, you have to do the uploading from FoxPro, and the DBFs must be attached to a FoxPro DBC.
http://www.codemag.com/article/0703052
The latest version if available from the VFPx site.
Finally, this is working
SELECT * FROM OPENROWSET ('MICROSOFT.ACE.OLEDB.12.0','dBase 5.0;HDR=YES;IMEX=2;DATABASE=\Dbf Directory\',
'SELECT * FROM dbf_filename.dbf')
I once had to do this too and wrote some C# code for the import.
Just as a try: With this line I open the connection within C#
var con = new OdbcConnection("Driver={{Microsoft dBASE Driver (*.dbf)}};Dbq=C:\\SomePath;DriverID=277;");
Might be, that you can get something out of this.
Some C# code
The following code is taken from one of my C# projects. I modified it to be neutral, but I cannot guarantee, that this is working right so:
public List<string> Ambus;
public List<string> Tbls;
public List<string> errList;
public List<string> SQLs;
private void btnImport_Click(object sender, EventArgs e) {
SqlConnection sqlcon;
SqlCommand sqlcmd;
SQLs.Clear();
Tbls.Clear();
var con = new OdbcConnection("Driver={{Microsoft dBASE Driver (*.dbf)}};Dbq=C:\\SomePath;DriverID=277;");
con.Open();
var tbls = con.GetSchema(OdbcMetaDataCollectionNames.Tables);
foreach (System.Data.DataRow r in tbls.Rows) {
Tbls.Add(r["TABLE_NAME"].ToString());
}
DataTable cols = null;
var sb = new StringBuilder();
int i = 0;
foreach (var tblnm in Tbls) {
i++;
sb.Clear();
try {
cols = con.GetSchema(OdbcMetaDataCollectionNames.Columns, new string[] { null, null, tblnm, null });
sb.AppendFormat(" CREATE TABLE dbo.[{0}](TableName VARCHAR(100) NOT NULL ", tblnm);
int count = 0;
foreach (DataRow colrow in cols.Rows) {
var colInf = string.Format(" ,{0} {1} NULL", colrow["COLUMN_NAME"].ToString(), this.createDataType(colrow["TYPE_NAME"].ToString(), colrow["COLUMN_SIZE"].ToString(), colrow["DECIMAL_DIGITS"].ToString(), colrow["NUM_PREC_RADIX"].ToString()));
sb.Append(colInf);
count++;
}
sb.Append("); ");
SQLs.Add(sb.ToString());
sb.Clear();
var cmd = new OdbcCommand("SELECT * FROM [" + tblnm + "]", con);
var reader = cmd.ExecuteReader();
while (reader.Read()) {
var vals = createVals(cols, reader, tblnm);
string insStat = string.Format(" INSERT INTO dbo.[{0}] VALUES ('{0}',{1});", tblnm, vals);
SQLs.Add(insStat);
}
}
catch (Exception exo) {
errList.Add(string.Format("{0}:{1}", tblnm, exo.Message));
}
con.Close();
sqlcon = new SqlConnection("Data Source=SomeSQLServer;Initial Catalog=master;User ID=sa;pwd=SomePwd");
sqlcon.Open();
sqlcmd = new SqlCommand("USE SomeTargetDB;", sqlcon);
sqlcmd.ExecuteNonQuery();
i = 0;
foreach (string s in SQLs) {
i++;
//Progress-output: this.Text = string.Format("{0} von {1}", i, SQLs.Count);
sqlcmd = new SqlCommand(s, sqlcon);
sqlcmd.ExecuteNonQuery();
}
sqlcon.Close();
}
}
private string createDataType(string typ, string size, string dec, string prec) {
switch (typ.ToLower()) {
case "char":
return "NVARCHAR(" + size + ")";
case "logical":
return "BIT";
case "numeric":
dec = dec == string.Empty ? null : dec;
prec = prec == string.Empty ? null : prec;
int d = int.Parse(dec ?? "0");
int p = int.Parse(prec ?? "0");
if (d == 0 && p == 0)
return "INT";
else if (d > 0 && p > 0)
return string.Format("DECIMAL({0},{1})", d, p);
else if (d == 0 && p > 0)
return "FLOAT";
else
return null;
case "date":
return "DATETIME";
default:
return null;
}
}
private string createVals(DataTable cols, OdbcDataReader reader, string tblnm) {
var sb = new StringBuilder();
sb.Append("'" + tblnm + "'");
foreach (DataRow colrow in cols.Rows) {
var val = string.Empty;
try {
val = reader[colrow["COLUMN_NAME"].ToString()].ToString();
}
catch { }
if (val.Trim().Length == 0)
val = "NULL";
else {
if (colrow["TYPE_NAME"].ToString().ToLower() == "char")
val = val.Replace("'", "''");
if (colrow["TYPE_NAME"].ToString().ToLower() == "numeric")
val = val.Replace(".", "").Replace(",", ".");
if (colrow["TYPE_NAME"].ToString().ToLower() == "date") {
var d = DateTime.Parse(val, System.Globalization.CultureInfo.CurrentCulture);
if (d.Year < 1900 || d.Year > 2020)
d = new DateTime(1900, d.Month, d.Day, d.Hour, d.Minute, d.Second);
val = d.ToString("dd.MM.yyyy HH:mm:ss");
}
val = "'" + val + "'";
}
sb.AppendFormat(",{0}", val);
}
return sb.ToString();
}

Postgresql update - Using ArrayList

I am getting an exception on update of postgres:
org.postgresql.util.PSQLException: Can't infer the SQL type...
Here is the code where in I build the sql statement dynamically and append the params:
public Boolean update(UserData usrData){
String sqlUpdateUser = "UPDATE \"USER\" ";
String sqlSetValues = "SET";
String sqlCondition = "Where \"USER_ID\" = ? ";
List<Object> params = new ArrayList<Object>();
List<Integer> types = new ArrayList<Integer>();
if(usrData.getFirstName() != null){
sqlSetValues = sqlSetValues.concat(" \"FIRST_NAME\" = ? ").concat(", ");
params.add(usrData.getFirstName());
types.add(Types.VARCHAR);
}
if(usrData.getMiddleName() != null){
sqlSetValues = sqlSetValues.concat("\"MIDDLE_NAME\" = ? ");
params.add(usrData.getMiddleName());
types.add(Types.VARCHAR);
}
params.add(usrData.getUserId());
types.add(Types.BIGINT);
Object[] updateParams = new Object[params.size()];
updateParams = params.toArray(updateParams);
Integer[] paramTypes = new Integer[types.size()];
paramTypes = types.toArray(paramTypes);
sqlUpdateUser = sqlUpdateUser.concat(sqlSetValues).concat(sqlCondition);
int rowsAffected = this.jdbcTemplate.update(sqlUpdateUser, updateParams, paramTypes);
if(rowsAffected > 0){
return Boolean.TRUE;
}else{
return Boolean.FALSE;
}
}
And table schema for the USER table is:
"FIRST_NAME" character varying(50),
"MIDDLE_NAME" character varying(50),
If I do an update statically without using the collection, but by using Array, I see no issue.
Code snipped using arrays:
Object[] param = { usrData.getFirstName(), usrData.getMiddleName(), usrData.getUserId() };
int[] type = { Types.VARCHAR, Types.VARCHAR, Types.BIGINT };
int rowsAffected = this.jdbcTemplate.update(sqlUpdateUser, param, type);
Am I missing something?
Thanks
K
Move these lines
Object[] updateParams = new Object[params.size()];
updateParams = params.toArray(updateParams);
Integer[] paramTypes = new Integer[types.size()];
paramTypes = types.toArray(paramTypes);
beneath
params.add(usrData.getUserId());
types.add(Types.INTEGER);
In your case you are missing to add usrData.getUserId() in updateParams.