Why returned OleDbConnection.GetSchema("Columns") has no rows while same code works for OracleConnection? - oracle

I've made a utility method to get schema from a db table. In this case Oracle 11 db.
public static DataTable GetColumnsSchemaTable(DbConnection cnctn, string tableName)
{
DataTable schemaTable;
string[] restrictions = new string[3] { null, tableName, null };
schemaTable = cnctn.GetSchema("Columns", restrictions);
/* table name is case sensitive and in XXXX db table names are UPPER */
if (schemaTable.Rows.Count == 0)
{
restrictions = new string[3] { null, tableName.ToUpper(), null };
schemaTable = cnctn.GetSchema("Columns", restrictions);
}
return schemaTable;
}
This works fine when the cnctn is created with System.Data.OracleClient provider factory. When it's created with System.Data.OleDb provider factory the table has no rows. I have an other utility method to get connection strings:
public static string GetDbConnectionString(DbConnection cnnctn, string provider, string server, string dbName, string user, string pwd)
{
if (cnnctn is OleDbConnection)
{
string usedProvider;
if (provider == null)
usedProvider = "msdaora";
else
usedProvider = provider;
return string.Format("Provider={0};Data Source={1};User Id={2};Password={3};",
usedProvider, dbName, user, pwd);
}
else if (cnnctn is System.Data.OracleClient.OracleConnection)
{
return string.Format("Data Source={0};User Id={1};Password={2};",
dbName, user, pwd);
}
else if (cnnctn is Oracle.DataAccess.Client.OracleConnection)
{
return string.Format("Data Source={0};User Id={1};Password={2};",
dbName, user, pwd);
}
else if (cnnctn is SqlConnection)
{
return string.Format("Data Source={0}; Initial Catalog={1}; User Id={2}; Password={3};",
server, dbName, user, pwd);
}
return string.Empty;
}
and the db connection works (i'm deleting rows before trying to get schema). All help will be appreciated.
Thanks & Best Regards - Matti

Ok. I sorted it out. I made this code long time ago only for now deprecated OracleClient and left the possibility to use other connections / provider factories. I didn't remember anymore that the restrictions vary from connection to connection. So the correct usage is:
string[] restrictions = new string[4] { null, null, tableName, null };
for OleDbConnection.

Related

Parse: how to determine if any given user is anonymous?

If we are dealing with the current user, it is easy by doing:
ParseAnonymousUtils.isLinked(ParseUser.getCurrentUser());
But what if I just have bunch of usernames? How can I determine which ones are anonymous? I have tried querying the User table like this:
ParseQuery<ParseUser> queryUser = new ParseUser().getQuery();
queryUser.whereEqualTo("User", usernameString);
queryUser.setLimit(1);
queryUser.findInBackground(new FindCallback<ParseUser>() {
#Override
public void done(List<ParseUser> users, ParseException e) {
if (e == null) {
if (users != null) {
for (ParseUser user : users) {
// do a check
}
}
}
}
}
And tried different ways to do the check but nothing seems to work. For example:
ParseAnonymousUtils.isLinked(user)
always returns false. I have also tried accessing the authData as String:
String authData = user.getString("authData");
if (authData == null) Log.i("authData", "null");
else Log.i("authData", authData);
but always get null. I have also tried casting it as JSONObject hoping to see if I can determine if an anonymous field exists in the JSON:
JSONObject authDataJson = (JSONObject) user.get("authData");
but also always get null.
How can I determine if any given username belongs to an anonymous user? Thanks

How to SELECT * from an wcf application, database hosted in appharbor

this is my first time playing with WCF in visual studio (2015), and I am running into some problems.
I have my database hosted in appharbor. I managed to insert new items into the database with:
public Test Insert (Test TestTable)
{
SqlConnection conGet = new SqlConnection(connectionString);
SqlCommand cmd = new SqlCommand(connectionString, conGet);
cmd.Parameters.AddWithValue("#testID", testTable.testID);
cmd.Parameters.AddWithValue("#testName", testTable.testName);
conGet.Open();
cmd.CommandText = "INSERT INTO TestTable (testID, testName) VALUES (#testID, #testName)";
cmd.ExecuteScalar();
conGet.Close();
return testTable;
}
PROBLEM: when I tried to select from it:
public Test GetData(Test test)
{
SqlConnection conPut = new SqlConnection(connectionString);
SqlCommand cmd = new SqlCommand("SELECT * FROM TestTable", conPut);
conPut.Open();
SqlDataReader rd = cmd.ExecuteReader();
if (rd.Depth>0)
{
while (rd.Read())
{
test.testID = (int)rd["testID"];
test.testName = rd["testName"].ToString();
}
}
else
{
Console.WriteLine("No rows found.");
}
conPut.Close();
return test;
}
rd (SqlDataReader) is not reading anything and just returns a null value, even though the test table has rows in it.
Please give me some pointers? I have tried several methods online, and no luck.. Thank you!
Remove that test for Depth. The Sql DataProvider doesn't support that property. It is always zero
Source: MSDN SqlDataReader.Depth
The outermost table has a depth of zero. The .NET Framework Data
Provider for SQL Server does not support nesting and always returns
zero.
If you want to test the condition of no rows then use the property HasRows
SqlDataReader rd = cmd.ExecuteReader();
if (rd.HasRows)
{
while (rd.Read())
{
test.testID = (int)rd["testID"];
test.testName = rd["testName"].ToString();
}
}
else
{
Console.WriteLine("No rows found.");
}

Is it possible to get a key value after DuplicateKeyException in spring?

I wonder if it is possible to get a key of a value after DuplicateKeyException in spring?
For example like this:
try {
KeyHolder keyHolder = new GeneratedKeyHolder();
getJdbcTemplate().update(
new PreparedStatementCreator() {
#Override
public PreparedStatement createPreparedStatement(Connection con) throws SQLException {
PreparedStatement ps = con.prepareStatement(SQL, new String[]{"ID"});
ps.setString(1, user.getUSERNAME());
ps.setString(2, user.getEMAIL());
return ps;
}
},
keyHolder);
logger.info("Insert success");
return (BigDecimal) keyHolder.getKey();
} catch (DuplicateKeyException dke) {
logger.info("Insert failed");
// get key and do sth with it
return new BigDecimal(-1);
}
Any suggestions here are welcome.
I don't see an optimal solution for this problem. Try something like this:
Preselection - Select all counts of values. (if you have constraint for mail, check whether the mail exists or not. If you have another constraint for name, check whether the name exists or not. (SELECT COUNT(name) FROM table WHERE name='SOME_NAME') You can do this, before or after experiencing a DuplicateKeyException.
Extraction - Try to extract the column which causes problems from the Exception-Message (this is dirty). In this case, you don't have to execute multiple queries.

Unable to connect to remote Oracle DB from an Azure Cloud Service

We are trying to deploy a Web Service on Azure Cloud Services that needs to access a remote Oracle DB.
We keep getting the following error when testing the connection:
System.Data.OracleClient 8.1.7 or greater required.
Here's the part of the code that we are using to connect:
using System.Data.OracleClient;
public string InsertUser_NOHA_UTENTI_Oracle(string cognome, string nome, string email)
{
string guid = Guid.NewGuid().ToString();
System.Configuration.ConnectionStringSettings css = System.Configuration.ConfigurationManager.ConnectionStrings["dbOracle"];
string query = "INSERT INTO NOHA_UTENTI (COGNOME,NOME,MAIL,TOKEN,STATO,DT_ISCRIZ,DT_CONF_ISCRIZ) values (#cognome, #nome, #email, #token, #stato, #dataIscrizione, #dataConfermaIscrizione)";
try
{
// create connection and command
using (OracleConnection cn = new OracleConnection("Data Source=(DESCRIPTION=(ADDRESS=(PROTOCOL=TCP)(HOST=xx.xx.xx.xx)(PORT=xxxx))(CONNECT_DATA=(SID=orcl)));User Id=xxxxxx;Password=xxxxxxx;"))
{
using (OracleCommand cmd = new OracleCommand(query, cn))
{
// define parameters and their values
cmd.Parameters.Add("#cognome", OracleType.VarChar, 50).Value = cognome;
cmd.Parameters.Add("#nome", OracleType.VarChar, 50).Value = nome;
cmd.Parameters.Add("#email", OracleType.VarChar, 50).Value = email;
cmd.Parameters.Add("#token", OracleType.VarChar, 50).Value = guid;
cmd.Parameters.Add("#stato", OracleType.VarChar, 1).Value = System.Configuration.ConfigurationManager.AppSettings["statoInAttesa"];
cmd.Parameters.Add("#dataIscrizione", OracleType.DateTime).Value = DateTime.Now;
cmd.Parameters.Add("#dataConfermaIscrizione", OracleType.DateTime).Value = null;
// open connection, execute INSERT, close connection
cn.Open();
cmd.ExecuteNonQuery();
cn.Close();
return guid;
}
}
}
catch (Exception ex)
{
throw ex;
}
}
We tried to follow these solutions unsuccessfully:
http://www.splinter.com.au/using-the-new-odpnet-to-access-oracle-from-c/
http://omegacoder.com/?p=445
Could someone who has successfully deployed a similar application on Azure point us in the right direction?
Thanks in advance!

NHib 3 Configuration & Mapping returning empty results?

Note: I'm specifically not using Fluent NHibernate but am using 3.x's built-in mapping style. However, I am getting a blank recordset when I think I should be getting records returned.
I'm sure I'm doing something wrong and it's driving me up a wall. :)
Background / Setup
I have an Oracle 11g database for a product by IBM called Maximo
This product has a table called workorder which lists workorders; that table has a field called "wonum" which represents a unique work order number.
I have a "reporting" user which can access the table via the maximo schema
e.g. "select * from maximo.workorder"
I am using Oracle's Managed ODP.NET DLL to accomplish data tasks, and using it for the first time.
Things I've Tried
I created a basic console application to test this
I added the OracleManagedClientDriver.cs from the NHibernate.Driver on the master branch (it is not officially in the release I'm using).
I created a POCO called WorkorderBriefBrief, which only has a WorkorderNumber field.
I created a class map, WorkorderBriefBriefMap, which maps only that value as a read-only value.
I created a console application with console output to attempt to write the lines of work orders.
The session and transaction appear to open correct,
I tested a standard ODP.NET OracleConnection to my connection string
The Code
POCO: WorkorderBriefBrief.cs
namespace PEApps.Model.WorkorderQuery
{
public class WorkorderBriefBrief
{
public virtual string WorkorderNumber { get; set; }
}
}
Mapping: WorkorderBriefBriefMap.cs
using NHibernate.Mapping.ByCode;
using NHibernate.Mapping.ByCode.Conformist;
using PEApps.Model.WorkorderQuery;
namespace ConsoleTests
{
public class WorkorderBriefBriefMap : ClassMapping<WorkorderBriefBrief>
{
public WorkorderBriefBriefMap()
{
Schema("MAXIMO");
Table("WORKORDER");
Property(x=>x.WorkorderNumber, m =>
{
m.Access(Accessor.ReadOnly);
m.Column("WONUM");
});
}
}
}
Putting it Together: Program.cs
namespace ConsoleTests
{
class Program
{
static void Main(string[] args)
{
NHibernateProfiler.Initialize();
try
{
var cfg = new Configuration();
cfg
.DataBaseIntegration(db =>
{
db.ConnectionString = "[Redacted]";
db.Dialect<Oracle10gDialect>();
db.Driver<OracleManagedDataClientDriver>();
db.KeywordsAutoImport = Hbm2DDLKeyWords.AutoQuote;
db.BatchSize = 500;
db.LogSqlInConsole = true;
})
.AddAssembly(typeof(WorkorderBriefBriefMap).Assembly)
.SessionFactory().GenerateStatistics();
var factory = cfg.BuildSessionFactory();
List<WorkorderBriefBrief> query;
using (var session = factory.OpenSession())
{
Console.WriteLine("session opened");
Console.ReadLine();
using (var transaction = session.BeginTransaction())
{
Console.WriteLine("transaction opened");
Console.ReadLine();
query =
(from workorderbriefbrief in session.Query<WorkorderBriefBrief>() select workorderbriefbrief)
.ToList();
transaction.Commit();
Console.WriteLine("Transaction Committed");
}
}
Console.WriteLine("result length is {0}", query.Count);
Console.WriteLine("about to write WOs");
foreach (WorkorderBriefBrief wo in query)
{
Console.WriteLine("{0}", wo.WorkorderNumber);
}
Console.WriteLine("DONE!");
Console.ReadLine();
// Test a standard connection below
string constr = "[Redacted]";
OracleConnection con = new OracleConnection(constr);
con.Open();
Console.WriteLine("Connected to Oracle Database {0}, {1}", con.ServerVersion, con.DatabaseName.ToString());
con.Dispose();
Console.WriteLine("Press RETURN to exit.");
Console.ReadLine();
}
catch (Exception ex)
{
Console.WriteLine("Error : {0}", ex);
Console.ReadLine();
}
}
}
}
Thanks in advance for any help you can give!
Update
The following code (standard ADO.NET with OracleDataReader) works fine, returning the 16 workorder numbers that it should. To me, this points to my use of NHibernate more than the Oracle Managed ODP.NET. So I'm hoping it's just something stupid that I did above in the mapping or configuration.
// Test a standard connection below
string constr = "[Redacted]";
OracleConnection con = new Oracle.ManagedDataAccess.Client.OracleConnection(constr);
con.Open();
Console.WriteLine("Connected to Oracle Database {0}, {1}", con.ServerVersion, con.DatabaseName);
var cmd = new OracleCommand();
cmd.Connection = con;
cmd.CommandText = "select wonum from maximo.workorder where upper(reportedby) = 'MAXADMIN'";
cmd.CommandType = CommandType.Text;
Oracle.ManagedDataAccess.Client.OracleDataReader reader = cmd.ExecuteReader();
while (reader.Read())
{
Console.WriteLine(reader.GetString(0));
}
con.Dispose();
When configuring NHibernate, you need to tell it about your mappings.
I found the answer -- thanks to Oskar's initial suggestion, I realized it wasn't just that I hadn't added the assembly, I also needed to create a new mapper.
to do this, I added the following code to the configuration before building my session factory:
var mapper = new ModelMapper();
//define mappingType(s) -- could be an array; in my case it was just 1
var mappingType = typeof (WorkorderBriefBriefMap);
//use AddMappings instead if you're mapping an array
mapper.AddMapping(mappingType);
//add the compiled results of the mapper to the configuration
cfg.AddMapping(mapper.CompileMappingForAllExplicitlyAddedEntities());
var factory = cfg.BuildSessionFactory();

Resources