ODBC Connection Time out didn't fire - c#-4.0

I'm trying to connect my asp.net application to an Informix DB using ODBCconnection.
The problem that I'm facing is if the Informix Db is down, my application takes forever trying to establish the connection.
It seems that the ConnectionTimeout doesn't work for me..
The following is the code that is used.
private string StartTimerForTest()
{
string err = "";
OdbcConnection odbc_Conn = new OdbcConnection();
odbc_Conn.ConnectionTimeout = 1;
DataTable ConnDt = new DataTable();
FormDataTable(ref ConnDt);
LoadSagaConfig(ref ConnDt);
SetOdbcConnectionstring(ref odbc_Conn, ref ConnDt);
try
{
odbc_Conn.Open();
odbc_Conn.Close();
}
catch (OdbcException ex)
{
err = ex.Message;
}
return err;
}
Any help will be much appreciated.

Related

Permission issue running Java

I'm trying to access JSON on remote server. The code works on a local replica of the database but on the server there is a "HTTP Web Server: Command Not Handled Exception" error. I have lotusscript agents doing similar things so I am thinking it is a problem with java permissions on the server.
As far as I can tell I have all permissions on the server to run the code. I've tried putting the code in to Javascript and a Java managed bean so don't think it is an issue with the code.
The server is running 11.0.1FP1 (I've read there may be issues with pol files in 11)
Any help or hints would be greatly received
public String getJSON(String url)
{
String returnCode = url;
try {
String jsonTxt = null;
URL myURL = new URL(url);
HttpURLConnection myURLConnection = (HttpURLConnection) myURL.openConnection();
if (myURLConnection.getResponseCode() < 400) {
returnCode = "Connection made";
} else {
/* error from server */
jsonTxt = "Can not access remote server";
returnCode = "Connection not made";
}
myURLConnection.disconnect();
} catch(Exception e) {
e.printStackTrace();
}
return returnCode;
}

SqlServer.Management.Smo on SQL Server 2008 R2 why does transfer of non table objects delete table data

I have a C# 4.7.1 program where I used SMO (32 bit) to copy stored procedures and views from one database (1) to a second database (2). The SQL Server is 2008 R2 SP3 on Windows Server 2008 R2.
Background: Database 1 is a copy my test database with environment specific values set correctly inside the stored procedures and views. Database 2 is a restored database to my Test system from Production. The goal was to retain the Test specific values in the stored procedures and views as well as any pre-production stored procedures and views.
The program works to retain my stored procedures and views that are Test specific but has an unwanted side-effect of deleting table data. I'm hoping someone familiar with the SMO can see what I'm doing or not doing that is causing the data in my tables to be removed.
Thank you very much for any help.
using Microsoft.SqlServer.Management.Smo;
using System;
class Program
{
static void Main(string[] args)
{
Server SourceServer = new Server(#"SQLSRVR\Instance2");
Server DestinationServer2 = new Server(#"SQLSRVR\Instance1");
try
{
//Using SQL Server authentication
SourceServer.ConnectionContext.LoginSecure = false;
SourceServer.ConnectionContext.Login = "UserID";
SourceServer.ConnectionContext.Password = "Password";
SourceServer.ConnectionContext.Connect();
DestinationServer1.ConnectionContext.LoginSecure = false;
DestinationServer1.ConnectionContext.Login = "UserID";
DestinationServer1.ConnectionContext.Password = "Password";
DestinationServer1.ConnectionContext.Connect();
Database dbSource1 = SourceServer.Databases["dbData"];
Database dbDestination1 = DestinationServer1.Databases["dbData"];
Transfer trsfrDB1 = new Transfer(dbSource1);
trsfrDB1.CopyAllObjects = false;
trsfrDB1.CopyAllSchemas = false;
trsfrDB1.CopyAllUserDefinedDataTypes = true;
trsfrDB1.CopyAllTables = false;
trsfrDB1.CopyData = false;
trsfrDB1.CopyAllStoredProcedures = true;
trsfrDB1.CopyAllViews = true;
trsfrDB1.DropDestinationObjectsFirst = true;
trsfrDB1.DestinationServer = DestinationServer1.Name;
trsfrDB1.DestinationDatabase = dbDestination1.Name;
Console.WriteLine("dbData start");
trsfrDB1.TransferData();
Console.WriteLine("dbData end");
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
Environment.Exit(1);
}
finally
{
if (SourceServer.ConnectionContext.IsOpen)
{
SourceServer.ConnectionContext.Disconnect();
}
if (DestinationServer1.ConnectionContext.IsOpen)
{
DestinationServer1.ConnectionContext.Disconnect();
}
}
}
}

Entity Framework 5 - Implementing SQL Server "Execute As User"

I am writing a database application using Visual Studio 2012 with Entity Framework 5 and SQL Server 2008. I would like Entity Framework to impersonate a SQL Server user (i.e. user without a login). I have created a new constructor for the DB context MyDatabaseEntities which includes an argument for the name of the user to impersonate. Here is the code that I've written:
public partial class MyDatabaseEntities
{
private String _impersonateUser = null;
public MyDatabaseEntities(String impersonateUser)
: base("MyConnectionString")
{
_impersonateUser = impersonateUser;
this.Database.Connection.StateChange += Connection_StateChange;
}
void Connection_StateChange(object sender, StateChangeEventArgs e)
{
if (e.CurrentState == ConnectionState.Open && e.OriginalState != ConnectionState.Open)
{
using (var cmd = this.Database.Connection.CreateCommand())
{
cmd.CommandType = CommandType.Text;
cmd.Parameters.Add(new SqlParameter("user", _impersonateUser));
cmd.CommandText = "EXECUTE AS USER = #user";
cmd.ExecuteNonQuery();
}
}
}
I had to add the check...
if (e.CurrentState == ConnectionState.Open && e.OriginalState != ConnectionState.Open)
...because the method Connection_StateChange method seems to execute even when the state hasn't changed. Then problem is that when I run the code twice,
public void RunSimpleQuery()
{
using (MyDatabaseEntities context = new MyDatabaseEntities("UserName"))
{
var result = context.TableName.ToList();
}
}
...Entity Framework throws a SqlException:
A severe error occurred on the current command. The results, if
any, should be discarded.\r\nA severe error occurred on the current
command. The results, if any, should be discarded.
Any ideas?
Update 1
I in my code above, I changed...
cmd.CommandText = "EXECUTE AS USER = #user;";
...to...
cmd.CommandText = "REVERT; EXECUTE AS USER = #user;";
...and I still get the same SqlException error.
The problem is that EF closes connection when it doesn't need it and returns it back to the pool. So when it executes some SQL again it request new connection from the pool where your event may not be initialized. But again I believe that you should try to solve this with manually controlling connection lifetime to have both benefit of connection pooling and be able to meet your requirements.
I know is an old question, but maybe will be useful for someone.
I did in a different way, using your code...
Instead of
Connection_StateChanged event
I create two methods in the same class:
public void ChangeUser(String sUser)
{
if(Database.Connection.State != ConnectionState.Open)
Database.Connection.Open();
using (var cmd = Database.Connection.CreateCommand())
{
cmd.CommandType = CommandType.Text;
cmd.Parameters.Add(new SqlParameter("user", sUser));
cmd.CommandText = "EXECUTE AS USER = #user;";
cmd.ExecuteNonQuery();
}
}
public void Revert()
{
if (Database.Connection.State != ConnectionState.Open)
Database.Connection.Open();
using (var cmd = Database.Connection.CreateCommand())
{
cmd.CommandType = CommandType.Text;
cmd.CommandText = "REVERT;";
cmd.ExecuteNonQuery();
}
}
I use it before and after execute stored procedure,
using (var db = new MyDatabaseEntities())
{
db.ChangeUser(model.Username);
var result = db.Something();
db.Revert();
return result;
}
It works fine with SPs and it doesn't throw an exception even after many executions. If I could catch an event after command execute, maybe all be encapsulated on MyDatabaseEntities.

Rollback INSERT Command in C#.NET

I had some confusion which I want to clear it - I am inserting values into database using ADO.NET. Let say I want to insert 10 item if I encounter error while inserting data of 5th item it should roll back whatever I had inserted into the database.
I just read the concept of Transaction and Rollback method and also tried to implement it in the program but still it insert 4 item and give me error message of 5th item. It doesn't roll back insert query.
Does transaction and roll back method solved my issue or I need to used other alternative.
here is my code,
for (int i = 0; i < itemLength - 1; i++)
{
//--- Start local transaction ---
myTrans = Class1.conn.BeginTransaction();
//--- Assign transaction object and connection to command object for a pending local transaction ---
_insertQry = Class1.conn.CreateCommand();
_insertQry.Connection = Class1.conn;
_insertQry.Transaction = myTrans;
_insertQry.CommandText = "INSERT INTO Product_PropertyValue(ItemNo, PropertyNo, ValueNo) VALUES (#ItemNo, #PropertyNo, #ValueNo)";
//_insertQry = new SqlCommand("INSERT INTO Product_PropertyValue(ItemNo, PropertyNo, ValueNo) VALUES (#ItemNo, #PropertyNo, #ValueNo)", Class1.conn);
_insertQry.Parameters.AddWithValue("#ItemNo", _itemNo[i]);
_insertQry.Parameters.AddWithValue("#PropertyNo", _propNo);
_insertQry.Parameters.AddWithValue("#ValueNo", _propValue);
_insertQry.ExecuteNonQuery();
myTrans.Commit();
}
Can anyone help me?
It sounds like you are trying to achieve an atomic commit. It either inserts completely or doesn't insert at all.
Try something like the following
SqlTransaction objTrans = null;
using (SqlConnection objConn = new SqlConnection(strConnString))
{
objConn.Open();
objTrans = objConn.BeginTransaction();
SqlCommand objCmd1 = new SqlCommand("insert into tbExample values(1)", objConn);
SqlCommand objCmd2 = new SqlCommand("insert into tbExample values(2)", objConn);
try
{
objCmd1.ExecuteNonQuery();
objCmd2.ExecuteNonQuery();
objTrans.Commit();
}
catch (Exception)
{
objTrans.Rollback();
}
finally
{
objConn.Close();
}
Also take a look at
http://www.codeproject.com/Articles/10223/Using-Transactions-in-ADO-NET
I did 2 modification to your code
1) Move the BeginTransaction() outside the for loop, So that all your 10 INSERt statements are in a single transaction, that is what you want if you want them to be atomic
2) added a TRY/CATCH block, so that you can roll back in case of errors.
//--- Start local transaction ---
myTrans = Class1.conn.BeginTransaction();
bool success = true;
try
{
for (int i = 0; i < itemLength - 1; i++)
{
//--- Assign transaction object and connection to command object for a pending local transaction ---
_insertQry = Class1.conn.CreateCommand();
_insertQry.Connection = Class1.conn;
_insertQry.Transaction = myTrans;
_insertQry.CommandText = "INSERT INTO Product_PropertyValue(ItemNo, PropertyNo, ValueNo) VALUES (#ItemNo, #PropertyNo, #ValueNo)";
//_insertQry = new SqlCommand("INSERT INTO Product_PropertyValue(ItemNo, PropertyNo, ValueNo) VALUES (#ItemNo, #PropertyNo, #ValueNo)", Class1.conn);
_insertQry.Parameters.AddWithValue("#ItemNo", _itemNo[i]);
_insertQry.Parameters.AddWithValue("#PropertyNo", _propNo);
_insertQry.Parameters.AddWithValue("#ValueNo", _propValue);
_insertQry.ExecuteNonQuery();
}
}
catch (Exception ex)
{
success = false;
myTrans.Rollback();
}
if (success)
{
myTrans.Commit();
}
let me know if this doesn't works.
You are on the right path, ADO.NET supports transactions so you will be able to rollback on errors.
Posting your your code here would get you more specific guidance; However since your question is very generic, I will encourage you to follow the template provided by MSDN
using (SqlConnection connection = new SqlConnection(connectionString))
{
connection.Open();
// Start a local transaction.
SqlTransaction sqlTran = connection.BeginTransaction();
// Enlist a command in the current transaction.
SqlCommand command = connection.CreateCommand();
command.Transaction = sqlTran;
try
{
// Execute two separate commands.
command.CommandText =
"INSERT INTO Production.ScrapReason(Name) VALUES('Wrong size')";
command.ExecuteNonQuery();
command.CommandText =
"INSERT INTO Production.ScrapReason(Name) VALUES('Wrong color')";
command.ExecuteNonQuery();
// Commit the transaction.
sqlTran.Commit();
Console.WriteLine("Both records were written to database.");
}
catch (Exception ex)
{
// Handle the exception if the transaction fails to commit.
Console.WriteLine(ex.Message);
try
{
// Attempt to roll back the transaction.
sqlTran.Rollback();
}
catch (Exception exRollback)
{
// Throws an InvalidOperationException if the connection
// is closed or the transaction has already been rolled
// back on the server.
Console.WriteLine(exRollback.Message);
}
}
}

Cannot open database "pubs" requested by the login. The login failed. Login failed for user 'ESLAM\Eslam_Nora'

Hello iam trying to store sum information inside a SQL Server table , but when i run the form and turned to store the data the above runtime error appears also the the pubs database icon in SQL Server is missing the (+) sign how come ! , i wrote that code for inserting , Thanks in advance.
public partial class Add_Client : Form
{
SqlConnection clientConnection;
string connString;
SqlCommand insertCommand;
public Add_Client()
{
InitializeComponent();
connString = "Data Source=.\\INSTANCE2;Initial Catalog=pubs; Integrated security=true ";
clientConnection = new SqlConnection();
clientConnection.ConnectionString = connString;
}
private void button1_ADD(object sender, EventArgs e)
{
try
{
SqlCommand insertCommand = new SqlCommand();
insertCommand.Connection = clientConnection;
insertCommand.CommandText = "INSERT INTO Client_Data values(#Client_Name,#Autorization_No,#Issue_Type,#Status)";
insertCommand.Parameters.Add("#Client_Name", SqlDbType.NVarChar, 60).Value = txt_Name.Text;
insertCommand.Parameters.Add("#Autorization_No", SqlDbType.Int, 60).Value = txt_Auth.Text.ToString();
insertCommand.Parameters.Add("#Issue_Type", SqlDbType.Text, 200).Value = txt_Iss.Text;
insertCommand.Parameters.Add("#Status", SqlDbType.Text, 200).Value = txt_Iss.Text;
//insertCommand.Parameters.Add("#Date To Memorize", SqlDbType.Date, 15).Value=Ca_Mem.se;
insertCommand.Connection.Open();
insertCommand.ExecuteNonQuery();
}
catch (Exception ex)
{
throw ex;
}
finally
{
if (clientConnection != null)
{
clientConnection.Close();
}
}
}
}
You use integrated security to access the database. Therefore your windows user needs to be authorized to access the database. Check the security settings for the server and the database.

Resources