reader only pulling one row in while loop C# - c#

I have two problems. One is that it is only pulling one row and sending it to ms fax when there are a few hundred to be sent. The other is that it doesn't pull any more after that first and it throws an error. I thought I was closing out my connections. I don't understand what the problem is. I have included the code and error.
Service1.cs
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.Linq;
using System.ServiceProcess;
using System.Text;
using System.Timers;
using MySql.Data.MySqlClient;
using FAXCOMLib;
using FAXCOMEXLib;
namespace ProcessFaxes
{
public partial class Service1 : ServiceBase
{
public Service1()
{
InitializeComponent();
}
public static Timer timer = new Timer();
protected override void OnStart(string[] args)
{
timer.Elapsed += new ElapsedEventHandler(Tick);
timer.Interval = 600000; // every 10 minutes
timer.Enabled = true;
// Console.ReadLine();
}
protected override void OnStop()
{
}
public static void Tick(object source, ElapsedEventArgs e)
{
string connString = "Server=localhost;Port=3306;Database=communications;Uid=root;password=pass;";
MySqlConnection conn = new MySqlConnection(connString);
MySqlCommand command = conn.CreateCommand();
MySqlConnection connupdate = new MySqlConnection(connString);
MySqlCommand commandupdate = connupdate.CreateCommand();
command.CommandText = "SELECT * FROM outbox WHERE `faxstat` = 'Y' AND `fax` <> '' AND `faxpro` = 'PENDING'";
//command.CommandText = "UPDATE blah blah";
//conn.Open();
//conn.ExecuteNonQuery();
//conn.Close();
try
{
conn.Open();
connupdate.Open();
}
catch (Exception ex)
{
// Console.WriteLine(Ex.Message);
LogException(ex.ToString());
throw; // or whatever you want to do with it
}
MySqlDataReader reader = command.ExecuteReader();
if (reader.HasRows)
{
while (reader.Read())
{
//Console.WriteLine(reader["filepath"].ToString());
SendFax(reader["id"].ToString(), reader["filepath"].ToString(), #"C:\FAXDOC\" + reader["filepath"].ToString(), reader["account"].ToString(), reader["fax"].ToString(), reader["fax_orig"].ToString());
string id = reader["id"].ToString();
commandupdate.CommandText = "UPDATE outbox SET `faxpro` = 'DONE' WHERE `id` = '" + id + "'";
commandupdate.ExecuteNonQuery();
}
}
conn.Close();
connupdate.Close();
}
public static void SendFax(string DocumentId, string DocumentName, string FileName, string RecipientName, string FaxNumber, string RecipientHomePhone2)
{
if (FaxNumber != "")
{
try
{
FAXCOMLib.FaxServer faxServer = new FAXCOMLib.FaxServerClass();
faxServer.Connect(Environment.MachineName);
FAXCOMLib.FaxDoc faxDoc = (FAXCOMLib.FaxDoc)faxServer.CreateDocument(FileName);
faxDoc.RecipientName = RecipientName;
faxDoc.FaxNumber = FaxNumber;
faxDoc.BillingCode = DocumentId;
faxDoc.DisplayName = DocumentName;
faxDoc.RecipientHomePhone = RecipientHomePhone2;
int Response = faxDoc.Send();
faxServer.Disconnect();
}
catch (Exception Ex) {
// Console.WriteLine(Ex.Message);
LogException(Ex.ToString());
throw; // or whatever you want to do with it
}
}
}
public static void LogException(string ErrorDescription)
{
// The name of our log in the event logs
string Log = "Process Faxes";
// Check to see fi the log for AspNetError exists on the machine
// If not, create it
if ((!(EventLog.SourceExists(Log))))
{
EventLog.CreateEventSource(Log, Log);
}
// Now insert your exception information into the AspNetError event log
EventLog logEntry = new EventLog();
logEntry.Source = Log;
logEntry.WriteEntry(ErrorDescription, EventLogEntryType.Error);
}
}
}
error
Event Type: Error
Event Source: Process Faxes
Event Category: None
Event ID: 0
Date: 3/6/2012
Time: 2:01:06 PM
User: N/A
Computer: FAXSERVER
Description:
MySql.Data.MySqlClient.MySqlException (0x80004005): Too many connections
at MySql.Data.MySqlClient.MySqlStream.ReadPacket()
at MySql.Data.MySqlClient.NativeDriver.Open()
at MySql.Data.MySqlClient.Driver.Open()
at MySql.Data.MySqlClient.Driver.Create(MySqlConnectionStringBuilder settings)
at MySql.Data.MySqlClient.MySqlPool.GetPooledConnection()
at MySql.Data.MySqlClient.MySqlPool.TryToGetDriver()
at MySql.Data.MySqlClient.MySqlPool.GetConnection()
at MySql.Data.MySqlClient.MySqlConnection.Open()
at ProcessFaxes.Service1.Tick(Object source, ElapsedEventArgs e) in C:\Documents and Settings\bruser\My Documents\Visual Studio 2010\Projects\ProcessFaxes\ProcessFaxes\Service1.cs:line 56

I think you should refactor a bit. I explained a little in a comment above, but here's how I would change it (I added some comments for you too):
public static void Tick(object source, ElapsedEventArgs e)
{
// Prevent another Tick from happening if this takes longer than 10 minutes
(source as Timer).Enabled = false;
// It would be better practice to put this in a settings or config file
// so you can change it without having to recompile your application
string connString = "Server=localhost;Port=3306;Database=communications;Uid=root;password=pass;";
// I won't change them here, but since these classes implement IDisposable,
// you should be using a using statement around them:
// using (var conn = new MySqlConnection(connString))
// {
// // use conn
// }
MySqlConnection conn = new MySqlConnection(connString);
MySqlCommand command = conn.CreateCommand();
MySqlCommand updateCommand = conn.CreateCommand();
command.CommandText = "SELECT * FROM outbox WHERE `faxstat` = 'Y' AND `fax` <> '' AND `faxpro` = 'PENDING'";
try
{
conn.Open();
MySqlDataReader reader = command.ExecuteReader();
if (reader.HasRows)
{
while (reader.Read())
{
SendFax(reader["id"].ToString(), reader["filepath"].ToString(), #"C:\FAXDOC\" + reader["filepath"].ToString(), reader["account"].ToString(), reader["fax"].ToString(), reader["fax_orig"].ToString());
string id = reader["id"].ToString();
// I would use a prepared statement with either this query
// or a stored procedure with parameters instead of manually
// building this string (more good practice than worrying about
// SQL injection as it's an internal app
updateCommand.CommandText = "UPDATE outbox SET `faxpro` = 'DONE' WHERE `id` = '" + id + "'";
updateCommand.ExecuteNonQuery();
}
}
}
catch (Exception ex)
{
LogException(ex.ToString());
throw;
}
finally
{
// If you're not going to use using-statements, you might want to explicitly
// call dispose on your disposable objects:
// command.Dispose();
// updateCommand.Dispose();
conn.Close();
// conn.Dispose();
}
// Enable the timer again
(source as Timer).Enabled = true;
}
As to why you're only receiving one row when you're expecting many, I suspect your SQL is at fault.

You should not be using a timer.
A timer fires at regular intervals, and does not care if the previous event has completed or not.
Look at using a Background Worker to send your faxes, having it loop over the queue, and then pause when the queue is empty.

The issue lies in your connection object. You have defined a couple of connection objects. You only need one.
Here are the two in question:
MySqlConnection connupdate = new MySqlConnection(connString);
MySqlConnection conn = new MySqlConnection(connString);
Eliminate the connection to one of them.
Here is one way to fix your code:
string connString = "Server=localhost;Port=3306;Database=communications;Uid=root;password=pass;";
using(MySqlConnection conn = new MySQLConnection(connString))
{
using(MySQlCommand command = conn.CreateCommand())
{
command.CommandText = "SELECT ...";
conn.Open();
using(MySqlDataReader reader = command.ExecuteReader())
{
//process rows...
}
}
}

Related

Xamarin MysqlConnector weird NullReferenceException error

I'm wanting to make a small and simple mobile app for a school project, I know connecting to a db from a phone is not good for security reasons but basically only I will touch it.
So to connect my Xamarin app to Mysql I downloaded the extension MysqlConnector (https://www.nuget.org/packages/MySqlConnector/2.1.8?_src=template)
Everything seemed to work at first, but now I think that there is a problem in their library that is not compatible with Xamarin:
I seem to always get a nullreference exception at the second query at line
reader = cmd.ExecuteReader();. I don't know why, nothing is null, I've printed everything.
(I've put a comment on the line where it happens) I seriously doubt it is a problem in their library since they have 37.2M downloads in total. But maybe it is just a compatability conflict, but that makes it odd that the first query works then.
Here is all my current code:
using PuppyChinoBestelling.Views;
using System;
using System.Collections.Generic;
using System.Text;
using Xamarin.Forms;
using MySqlConnector;
using System.Threading.Tasks;
namespace PuppyChinoBestelling.ViewModels
{
public class LoginViewModel : BaseViewModel
{
public Command LoginCommand { get; }
public string Mail { get; set; }
public string Pass { get; set; }
public LoginViewModel()
{
Pass = string.Empty;
Mail = string.Empty;
LoginCommand = new Command(OnLoginClicked);
}
private async void OnLoginClicked(object obj)
{
MySqlConnection conn = new MySqlConnection("private");
try
{
conn.Open();
Console.WriteLine("Conn opened!");
}
catch(Exception ex)
{
Console.WriteLine("Error " + ex.Message);
}
string sql = #"SELECT * FROM users WHERE email = #email;";
var cmd = conn.CreateCommand();
cmd.CommandText = sql;
cmd.Parameters.AddWithValue("#email", Mail);
var reader = cmd.ExecuteReader();
if (reader.HasRows)
{
sql = #"SELECT * FROM users WHERE email = #email;";
cmd = conn.CreateCommand();
cmd.Parameters.Clear();
cmd.CommandText = sql;
cmd.Parameters.AddWithValue("#email", Mail);
reader = cmd.ExecuteReader(); //null reference happening here idk why
string pwdHashed = reader.GetString(5);
bool validPwd = BCrypt.Net.BCrypt.Verify(Pass, pwdHashed);
conn.Close();
if (validPwd)
{
await Shell.Current.GoToAsync($"//{nameof(AboutPage)}");
}
else
{
Console.WriteLine("Foute logingegevens!");
}
}
else
{
Console.WriteLine("Je bestaat niet!");
}
}
}
}
Thanks in advance!
It's hard to say for certain, but it's likely the issue is because you are not closing the reader and command, and you can't have multiple commands on the same connection.
Also, you need to advance the reader using reader.Read.
In any case there is no need to run the command twice in the first place. You already had all the information on the first run.
You also need to dispose everything with using. This automatically closes the connection.
Don't SELECT *, just select the columns you need.
Ideally, you would calculate the hash for the given password, and send it to the database server to check, rather than pulling out the real password hash from the database (could be a security risk).
Don't store hashes as strings. Instead store them as binary with the varbinary data type, and cast to byte[] on the C# side.
Unclear why you are handling errors only for opening the connection, not for executing the command.
private async void OnLoginClicked(object obj)
{
const string sql = #"
SELECT Pass
FROM users
WHERE email = #email;
";
using (var conn = new MySqlConnection("private"))
using (var cmd = new MySqlCommand(sql, conn))
{
try
{
conn.Open();
Console.WriteLine("Conn opened!");
}
catch(Exception ex)
{
Console.WriteLine("Error " + ex.Message);
return; // no point continuing
}
cmd.Parameters.AddWithValue("#email", Mail);
using (var reader = cmd.ExecuteReader())
{
if (!reader.Read())
{
Console.WriteLine("Je bestaat niet!");
return; // no point continuing
}
string pwdHashed = (string)reader["Pass"];
conn.Close();
bool validPwd = BCrypt.Net.BCrypt.Verify(Pass, pwdHashed);
if (validPwd)
{
await Shell.Current.GoToAsync($"//{nameof(AboutPage)}");
}
else
{
Console.WriteLine("Foute logingegevens!");
}
}
}
}
An alternative method is to remove the reader altogether and use ExecuteScalar
private async void OnLoginClicked(object obj)
{
const string sql = #"
SELECT Pass
FROM users
WHERE email = #email;
";
using (var conn = new MySqlConnection("private"))
using (var cmd = new MySqlCommand(sql, conn))
{
try
{
conn.Open();
Console.WriteLine("Conn opened!");
}
catch(Exception ex)
{
Console.WriteLine("Error " + ex.Message);
return; // no point continuing
}
cmd.Parameters.AddWithValue("#email", Mail);
string pwdHashed = cmd.ExecuteScalar() as string;
conn.Close();
if (pwdHashed is null)
{
Console.WriteLine("Je bestaat niet!");
return; // no point continuing
}
bool validPwd = BCrypt.Net.BCrypt.Verify(Pass, pwdHashed);
if (validPwd)
{
await Shell.Current.GoToAsync($"//{nameof(AboutPage)}");
}
else
{
Console.WriteLine("Foute logingegevens!");
}
}
}

This code shows me that "CommandText has not been initialized"

I want to check ManagerUsername and ManagerEmail in the database and the display a messagebox to show the user with their password.But when I execute the code it shows me that:
"commandtext has not been initialized"
so I want to know how can I fix my code to display what I want. And also a way to improve my code to work more efficient
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Data.SqlClient;
namespace Cybertronics
{
public partial class passwordRecovery : Form
{
int pin = 0;
private int _failedAttempts = 0;
public passwordRecovery()
{
InitializeComponent();
}
private void passwordRecovery_Load(object sender, EventArgs e)
{
lblAttempt.Visible = false;
}
private void btnBackLogin_Click(object sender, EventArgs e)
{
loginFrm loginForm = new loginFrm();
this.Hide();
loginForm.Show();
}
private void btnSubmitEmail_Click(object sender, EventArgs e)
{
try
{
string emailAddress = txtEmail.Text;
string username = txtManagerUsername.Text;
string password = "ChangeMe";
CyberDatabase db = new CyberDatabase();
db.OpenConnection();
SqlCommand cmd = new SqlCommand();
SqlDataReader reader;
cmd.Parameters.AddWithValue("#ManagerUsername", username);
cmd.Parameters.AddWithValue("#ManagerEmail", emailAddress);
db.SetSqlCommand(cmd);
reader = db.Select();
cmd.CommandText = "SELECT ManagerUsername from tblManagers WHERE ManagerUsername = #ManagerUsername and ManagerEmail = #ManagerEmail";
db.SetSqlCommand(cmd);
reader = db.Select();
if (reader.HasRows)
{
reader.Read();
SqlCommand passwordUpdate = new SqlCommand();
passwordUpdate.CommandText = "UPDATE tblManagers SET ManagerPassword=#Password WHERE ManagerUsername=#ManagerUsername and ManagerEmail=#ManagerEmail";
db.SetSqlCommand(passwordUpdate);
MessageBox.Show("your new password is:" + password);
}
else
{
if (pin != 21)
{
_failedAttempts++;
MessageBox.Show("Wrong password or username fail to login. you have" + (3 - _failedAttempts) + " attempts more.", "EPIC FAIL", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
if (_failedAttempts == 3)
{
Application.Exit();
}
}
}
}
catch (SqlException sql)
{
CyberMethods.DisplayErrorMessage(sql.Message);//error message from cybermethods class for DB
}
catch (Exception exc)
{
CyberMethods.DisplayErrorMessage(exc.Message);//error message from cybermethods class
}
}
}
}
your code is very messy and untidy. It is very error prone. Check the below sample code for best practices.
using (connection)
using (SqlCommand command = new SqlCommand(
"SELECT ManagerUsername from tblManagers WHERE ManagerUsername = #ManagerUsername and ManagerEmail = #ManagerEmail",
connection))
{
connection.Open();
using (SqlDataReader reader = command.ExecuteReader())
{
if (reader.HasRows)
{
while (reader.Read())
{
Console.WriteLine("{0}\t{1}", reader.GetInt32(0),
reader.GetString(1));
}
}
else
{
Console.WriteLine("No rows found.");
}
}
}
you have multiple query statements. for the seperation of duties principles I suggest you to make 3 functions each seperate and call them respectively.
and It is wise to keep connection open then then close when all the operations finish.
For solving your error
before your first db.SetSqlCommand(cmd); just add your query statement with
cmd.CommandText = "select ....." ;

Re-try to open a SQL Server connection if failed

I have a C# application which has several methods which connect to a SQL Server database in order to execute a query.
Sometimes the connection fails and then the program exits.
A db administrator is looking on the database nevertheless I have to adapt the program in order to retry 2-3 times when a connection fails before to exiting.
I don't really know who doing this "smartly".
My connection code:
using (SqlConnection SqlCon = new SqlConnection(myParam.SqlConnectionString))
{
SqlCon.Open();
string requeteFou = "select XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX";
using (SqlCommand command = new SqlCommand(requeteFou, SqlCon))
{
using (SqlDataReader reader = command.ExecuteReader())
{
if (reader.HasRows)
{
while (reader.Read())
{
// do job
}
}
}
}
}
Since I use several methods, is there a simply way to overwrite the "connection" or "read" method in order to retry the connection 3 times for example ?
Best regards
I would use Polly for retry logic.
Very basic example retrying 3 times when there is a SqlException (not tested):
static void Main(string[] args)
{
var policy = Policy
.Handle<SqlException>()
.Retry(3);
try
{
policy.Execute(() => DoSomething());
}
catch (SqlException exc)
{
// log exception
}
}
private static void DoSomething()
{
using (SqlConnection conn = new SqlConnection(""))
{
conn.Open();
string requeteFou = "select XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX";
using (SqlCommand command = new SqlCommand(requeteFou, conn))
{
using (SqlDataReader reader = command.ExecuteReader())
{
if (!reader.HasRows) return;
while (reader.Read())
{
// do job
}
}
}
}
}
private static function()
{
DataTable dt = new DataTable();
string connectionString = "//your connection string";
String strQuery = //"Yourquery";
const int NumberOfRetries = 3;
var retryCount = NumberOfRetries;
var success = false;
while (!success && retryCount > 0)
{
try
{
SqlConnection conn = new SqlConnection(connectionString);
SqlCommand cmd = new SqlCommand();
cmd.CommandType = CommandType.Text;
cmd.CommandText = strQuery;
cmd.Connection = conn;
cmd.CommandTimeout = 180;
conn.Open();
SqlDataReader dr = cmd.ExecuteReader();
dt.Load(dr);
catch (Exception ex)
{
retryCount--;
Thread.Sleep(1000 * 60 * 15);
if (retryCount == 0)
{
//yourexception
}
}
}
}
Maybe wrap your using in a try block. Log a connection error in a catch block if you want. Put whole try{ }catch{ } in a for loop that will loop 3 times. If try block runs to the end of itself, break out of loop.
for(int i = 0; i < 3; i++)
{
try {
using (SqlConnection SqlCon = new SqlConnection(myParam.SqlConnectionString))
{
// your code
}
Thread.Sleep(1000); // wait some time before retry
break; // connection established, quit the loop
}
catch(Exception e) {
// do nothing or log error
}
}
You'd however have to handle differentiating SQL connection exception from other exceptions that you might encounter in your code.

Method with MySql query for LOAD DATA IN FILE never finishes

I am populating a MySQL table in C# using the LOAD DATA INFILE method.
Therefore I wrote a method for creating the query string...
public static string LoadDataInFile(string TempCsv, string MatchId)
{
StringBuilder MySqlString = new StringBuilder();
MySqlString.AppendFormat(#"LOAD DATA INFILE '{0}' INTO TABLE {1}_trackingdata
FIELDS TERMINATED BY ';'
IGNORE 1 LINES", TempCsv, MatchId);
return MySqlString.ToString();
}
and one that executes raw queries:
public static void ExecuteRawQuery(string Query, string ConnectionString)
{
using (MySqlConnection conn = new MySqlConnection(ConnectionString.ToString()))
{
try
{
conn.Open();
MySqlCommand cmd = new MySqlCommand(Query, conn);
cmd.ExecuteNonQuery();
conn.Close();
Console.WriteLine("Import probably done...");
return;
}
catch (MySqlException SqlException)
{
Console.ForegroundColor = ConsoleColor.DarkRed;
Console.WriteLine("SqlException: {0}", SqlException.Message);
Console.WriteLine("Exit program.");
Console.ResetColor();
Environment.Exit(0);
}
}
}
The table gets populated as expected (checked with Sequel Pro), but the application never continues.
public static void Main(string[] args)
{
// ...
ExecuteRawQuery(LoadDataInFile("myFile.csv", "123456"));
Console.WriteLine("I will never be displayed..");
// ...
}
Is there any reason why ExecuteRawQuery() never finishes? When I execute other queries (SELECT, UPDATE) everything works as expected.
I don't know why, but using the MySqlClient.MySqlBulkLoader-class solves the problem. Leaving this here for anybody experiencing the same issue:
public static void ImportCSV(string CSV, string TableName, string ConnectionString)
{
using (MySqlConnection conn = new MySqlConnection(ConnectionString.ToString()))
{
MySqlBulkLoader Bulkloader = new MySqlBulkLoader(conn);
Bulkloader.TableName = TableName;
Bulkloader.FileName = CSV;
Bulkloader.Timeout = 0;
Bulkloader.NumberOfLinesToSkip = 1;
Bulkloader.FieldTerminator = ";";
var result = Bulkloader.Load();
Console.WriteLine("Imported {0} rows into the database", result);
}
}

C# OleDBConnection connecting to previous IP?

I have multiple databases (30+) that are used at clinics and setup automatically via the license software they use. So each database is named the same and use the same port, the only thing that changes is the IP. That being said, I am using the following code to attempt to run a query against them individually. However, when I change out the IP and run the script again it is returning the results from the previous server.
using System;
using System.Diagnostics;
using System.Data.OleDb;
namespace ConnectionTest
{
class Program
{
static void Main(string[] args)
{
using (OleDbConnection conn = new OleDbConnection("Provider=SAOLEDB.10;LINKS=tcpip(host=X.X.X.X,PORT=2638);ServerName=EAGLESOFT;Integrated Security = True; User ID = dba; PWD = sql"))
{
try
{
conn.Open();
using (OleDbCommand cmd = new OleDbCommand("SELECT tran_num, provider_id, tran_date FROM transactions WHERE tran_date LIKE '2015-11-23%'", conn))
{
using (OleDbDataReader reader = cmd.ExecuteReader())
{
while (reader.Read())
{
Console.WriteLine("{0}|{1}|{2}", reader.GetValue(0).ToString(), reader.GetValue(1).ToString(), reader.GetValue(2).ToString());
}
}
}
}
catch (Exception connerr) { Debug.WriteLine(connerr.Message); }
conn.Close();
}
if (Debugger.IsAttached)
{
Console.ReadLine();
}
}
}
}
I don't see any reason why you would be getting previous results, here. Are you running multiple instances of this code at the same time? Are you manually changing the IP address in your code each time? I assume the "Transactions" object is an actual table and not something being generated on-the-fly?
With just a tiny bit of modification, you could pass the IP address as a command line parameter:
static void Main(string[] args)
{
string ip, port = null;
for (int i = 0; i < args.Length; i++)
{
if (args[i].StartsWith("/i:"))
ip = args[i].Substring(args[i].IndexOf(':') + 1);
else if (args[i].StartsWith("/p:"))
port = args[i].Substring(args[i].IndexOf(':') + 1);
}
// Default the port value to 2638 (since I have no idea if that changes).
if (string.IsNullOrEmpty(port))
port = "2638";
string connStr = string.Format("Provider=SAOLEDB.10;LINKS=tcpip(host={0},PORT={1});ServerName=EAGLESOFT;Integrated Security = True; User ID = dba; PWD = sql", ip, port);
using (OleDbConnection conn = new OleDbConnection(connStr))
{
try
{
conn.Open();
if (conn.State != System.Data.ConnectionState.Open)
// You could also implement a WHILE loop with a small delay (~1200ms) and try again to open the connection, with a counter to "fail" after a certain number (like 3) of attempts.
throw new Exception("Unable to open connection to database.");
using (OleDbCommand cmd = new OleDbCommand("SELECT tran_num, provider_id, tran_date FROM transactions WHERE tran_date LIKE '2015-11-23%'", conn))
using (OleDbDataReader reader = cmd.ExecuteReader())
while (reader.Read())
Console.WriteLine("{0}|{1}|{2}", reader.GetValue(0).ToString(), reader.GetValue(1).ToString(), reader.GetValue(2).ToString());
}
catch (Exception connerr)
{ Debug.WriteLine(connerr.Message); }
finally
{ conn.Close(); }
}
if (Debugger.IsAttached)
{
Console.ReadLine();
}
}
First and foremost (for testing purposes, that is) I would probably try removing the ServerName parameter since you're already providing an IP address explicitly.
So your connection string would be:
Provider=SAOLEDB.10;LINKS=tcpip(host=X.X.X.X,PORT=2638);Integrated Security = True; User ID = dba; PWD = sql
Similar to ORA files, DSNs, etc, it almost sounds like you have a server alias configured for EAGLESOFT that may be overwriting the IP preference in your testing.
Make sure you change EagleSoft as well as IP. You have to pass the IP address as an arg[]. Modify code as below to allow the IP to change
string host = "X.X.X.X";
string conStr = string.Format("Provider=SAOLEDB.10;LINKS=tcpip(host={0},PORT=2638);ServerName=EAGLESOFT;Integrated Security = True; User ID = dba; PWD = sql", host);
using (OleDbConnection conn = new OleDbConnection(conStr))
​

Categories